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
Eric Firing had the excellent idea of making a CODING_GUIDE which summarizes the conventions used in matplotlib development, and I've added this to svn. Feel free to make changes, additions and comments. I think we could add a lot here, including an overview of the API. Here is the document I just committed:: Devs, feel free to edit this document. This is meant to be a guide to developers on the mpl coding practices and standards == Committing Changes == When committing changes to matplotlib, there are a few things to bear in mind. * if your changes are nontrivial, please make an entry in the CHANGELOG * if you change the API, please document it in API_CHANGES, and consider posing to mpl-devel * Are your changes python2.3 compatible? We are still trying to support 2.3, so avoid 2.4 only features like decorators until we remove 2.3 support * Are your changes Numeric, numarray and numpy compatible? Try running simple_plot.py or image_demo.py with --Numeric, --numarray and --numpy (Note, someone should add examples to backend_driver.py which explicitly require numpy, numarray and Numeric so we can automatically catch these) * Can you pass examples/backend_driver.py? This is our poor man's unit test. * If you have altered extension code, do you pass unit/memleak_hawaii.py? == Naming conventions == functions and class methods : lower or lower_underscore_separated attributes and variables : lower or lowerUpper classes : Upper or MixedCase Personally, I prefer the shortest names that are still readable. == kwargs processing == Matplotlib makes extensive use of **kwargs for pass through customizations from one function to another, eg the pylab plot -> Axes.plot pass through. As a general rule, the use of **kwargs should be reserved for pass-through keyword arguments, eg def somefunc(x, k1='something', **kwargs): # do some thing with x, k1 return some_other_func(..., **kwargs) If I intend for all the keyword args to be used in somefunc alone, I just use the key/value keyword args in the function definition rather than the **kwargs idiom. In some cases I want to consume some keys and pass through the others, in which case I pop the ones I want to use locally and pass on the rest, eg I pop scalex and scaley in Axes.plot and assume the rest are Line2D keyword arguments. Whenever you mutate a kwargs dictionary (eg by popping it), you must first copy it since the user may be explitly passing in a dictionary which is used across many function calls. As an example of a copy, pop, passthrough usage, see Axes.plot: def plot(self, *args, **kwargs): kwargs = kwargs.copy() scalex = popd(kwargs, 'scalex', True) scaley = popd(kwargs, 'scaley', True) if not self._hold: self.cla() lines = [] for line in self._get_lines(*args, **kwargs): self.add_line(line) lines.append(line) popd is a matplotlib.cbook function to pop an item from a dictionary with a default value if the item doesn't exist... == class documentation == matplotlib uses artist instrospection of docstrings to support properties. All properties that you want to support through setp and getp should have a set_property and get_property method in the Artist class. Yes this is not ideal given python properties or enthought traits, but it is a historical legacy for now. The setter methods use the docstring with the ACCEPTS token to indicate the type of argument the method accepts. Eg in matplotlib.lines.Line2D def set_linestyle(self, linestyle): """ Set the linestyle of the line ACCEPTS: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' | ' ' | '' ] """ Since matplotlib uses a lot of pass through kwargs, eg in every function that creates a line (plot, semilogx, semilogy, etc...), it can be difficult for the new user to know which kwargs are supported. I have developed a docstring interpolation scheme to support documentation of every function that takes a **kwargs. The requirements are: 1) single point of configuration so changes to the properties don't require multiple docstring edits 2) as automated as possible so that as properties change the docs are updated automagically. I have added a matplotlib.artist.kwdocd to faciliate this. This combines python string interpolation in the docstring with the matplotlib artist introspection facility that underlies setp and getp. The kwdocd is a single dictionary that maps class name to a docstring of kwargs. Here is an example at the bottom of matplotlib.lines artist.kwdocd['Line2D'] = '\n'.join(artist.ArtistInspector(Line2D).pprint_setters(leadingspace=12)) Then in any function accepting Line2D passthrough kwargs, eg matplotlib.axes.Axes.plot def plot(self, *args, **kwargs): """ Some stuff omitted The kwargs are Line2D properties: %(Line2D)s kwargs scalex and scaley, if defined, are passed on to autoscale_view to determine whether the x and y axes are autoscaled; default True. See Axes.autoscale_view for more information """ pass plot.__doc__ = plot.__doc__ % artist.kwdocd Note there is a problem for Artist __init__ methods, eg Patch.__init__ which supports Patch kwargs, since the artist inspector cannot work until the class is fully defined and we can't modify the Patch.__init__.__doc__ docstring outside the class definition. I have made some manual hacks in this case which violates the "single entry point" requirement above; hopefully we'll find a more elegant solution before too long > * Are your changes python2.3 compatible? We are still trying to > support 2.3, so avoid 2.4 only features like decorators until we > remove 2.3 support Good, I thought we were still restricted to 2.2! Does this mean boilerplate.py should be updated? (Or maybe it isn't worth fiddling with it.) # wrap the plot commands defined in axes. The code generated by this # file is pasted into pylab.py. We did try to do this the smart way, # with callable functions and new.function, but could never get the # docstrings right for python2.2. See Eric >>>>> "Eric" == Eric Firing <efiring@...> writes: >> * Are your changes python2.3 compatible? We are still trying >> to support 2.3, so avoid 2.4 only features like decorators >> until we remove 2.3 support Eric> Good, I thought we were still restricted to 2.2! I was wondering how long it would take for someone to notice that <wink> I think we could lose python2.2 support if there is a good reason. Is anyone still using it? I'll also post to the user's list. Perhaps in the next release we should issue deprecation warnings for 2.2 and encourage people to post to the list if they have an objection. Typically with these things you don't see complaints until you take something away. We haven't been compiling 2.2 for windows for sometime now. JDH >>>>> "John" == John Hunter <jdhunter@...> writes: John> I think we could lose python2.2 support if there is a good John> reason. Is anyone still using it? I'll also post to the John> user's list. Perhaps in the next release we should issue John> deprecation warnings for 2.2 and encourage people to post to John> the list if they have an objection. Typically with these John> things you don't see complaints until you take something John> away. Well, I was just about to post to the user list to see if anyone objected to remove 2.2 support, and wondered, do we really support 2.2 currently? I just tried to compile under 2.2 and got peds-pc311:~/mpl> sudo python2.2 setup.py install Traceback (most recent call last): File "setup.py", line 63, in ? from setupext import build_agg, build_gtkagg, build_tkagg, build_wxagg,\ File "setupext.py", line 120, in ? win32_compiler = get_win32_compiler() File "setupext.py", line 117, in get_win32_compiler if 'mingw32' in v: TypeError: 'in <string>' requires character as left operand And this has probably been in there for a while. So we haven't supported 2.2 for sometime and noone is complaining so let's make 2.3 the official target rather than fix this. At least 2.3 compiles and runs. I'll update the docs and website when I get a minute. JDH John Hunter wrote: [...] I am in the process of changing your shiny new kwdocd machinery slightly. I added artist.kwdoc so that > artist.kwdocd['Line2D'] = '\n'.join(artist.ArtistInspector(Line2D).pprint_setters(leadingspace=12)) > becomes artist.kwdocd['Line2D'] = artist.kwdoc(Line2D) > Then in any function accepting Line2D passthrough kwargs, eg > matplotlib.axes.Axes.plot > > def plot(self, *args, **kwargs): > """ > Some stuff omitted > > The kwargs are Line2D properties: > %(Line2D)s and the line above is changed to be indented the same as the rest of the string (improves readability to my eye) > > kwargs scalex and scaley, if defined, are passed on > to autoscale_view to determine whether the x and y axes are > autoscaled; default True. See Axes.autoscale_view for more > information > """ > pass because this > plot.__doc__ = plot.__doc__ % artist.kwdocd becomes plot.__doc__ = dedent(plot.__doc__) % artist.kwdocd where dedent is now in cbook.py I can continue making the necessary changes if that is OK with you, but I don't want our versions to get tangled up if you are still working on this aspect, or if you don't like the strategy modification outlined above. I committed dedent but not the other changes. Eric >>>>> John Hunter wrote: >>>>>> Very nice. I thought about making a standalone expand_doc() function, but your incorporation of it in the class is much nicer. I think I will put this on the stack and not do it immediately. I already made all the changes I outlined (couldn't stop once I got going) and can't quite face another pass through the files right now. But in the process of making that pass, I ran into a small worm can: in the collections the kwargs and the setters don't match, so kwdocd['PatchCollection'], for example, is not quite right. The collection setter names are singular (set_color) to mirror the corresponding non-collection objects, but the kwargs are plural (colors). Although I see the (grammatical) logic of the plural form I like the singular form because I see little gain and considerable loss in having different names for the same functionality in LineCollection as compared to Line2D, for example. We could get around the problem by allowing the singular forms of the kwargs as well and deprecating the plural forms. Another small glitch: it looks like you used the inspector to assemble the kwargs list for the Axes docstring, but some of these, like figure and position, duplicate required arguments so they don't really makes sense as kwargs--even though they would work. Did you edit out other such examples? Is that the reason the Axes.__init__ kwargs list is not being generated automatically? Er >>>>> "Eric" == Eric Firing <efiring@...> writes: Eric> But in the process of making that pass, I ran into a small Eric> worm can: in the collections the kwargs and the setters Eric> don't match, so kwdocd['PatchCollection'], for example, is Eric> not quite right. The collection setter names are singular Eric> (set_color) to mirror the corresponding non-collection Eric> objects, but the kwargs are plural (colors). Although I see Eric> the (grammatical) logic of the plural form I like the Eric> singular form because I see little gain and considerable When I was doing the kwdocd stuff I noticed the same but was focused on getting the documentation infrastructure working and didn't want to get distracted. But this is in part what I was alluding to in an earlier email about the need for a cleanup. Eg, in Axes we have axisbg in the init function and the axis_bgcolor property, both of which do the same thing; ditto for frameon and frame_on I think we should handle all properties in __init__ methods with **kwargs and artist.update, rather than using explicitly named keywords. artist init methods can take explicit keyword args, but these will not be properties. When I wrote some of these methods, I put named keyword args in the __init__ methods because it made them more readable, eg with "help", and because some of these did not exist as properties. As properties were added, apparently sometimes bad names were chosen. Now that we have a system for documenting keywords automatically, the docstring aspect is not so important so we should remove the bad or inconsistent names. For deprecated kwargs (eg axisbg) we could something like the following, eg for Axes: OLD: def __init__(self, fig, rect, axisbg = None, # defaults to rc axes.facecolor frameon = True, sharex=None, # use Axes instance's xaxis info sharey=None, # use Axes instance's yaxis info label='', **kwargs ): """ New: def __init__(self, fig, rect, sharex=None, # use Axes instance's xaxis info sharey=None, # use Axes instance's yaxis info **kwargs ): """ # check for deprecated usage: kwargs = kwargs.copy() frame_on = kwargs.get(frameon) if frame_on is not None: #deprecation warning kwargs['frame_on'] = frame_on axis_bgcolor = kwargs.get(axisbg) if axis_bgcolor is not None: #deprecation warning; use axis_bgcolor rather than axisbg kwargs['axis_bgcolor'] = axis_bgcolor .... self.update(kwargs) Alternatively, we can raise a helpful exception, eg 'Use axis_bgcolor rather than axisbg' Another approach is to support these alternate names through aliases like we do in Line2D: lw for linewidth, etc.... I don't feel strongly about any of the three approaches, but we can agree on something and both fix them as we find them. It should go pretty quickly. Eric> loss in having different names for the same functionality in Eric> LineCollection as compared to Line2D, for example. We could Eric> get around the problem by allowing the singular forms of the Eric> kwargs as well and deprecating the plural forms. Or use aliases. Again, if you have a preference I am happy to go with it. I guess simplicity should rule the day rather than having an ever growing number of ways to specify what you want. Eric> Another small glitch: it looks like you used the inspector Eric> to assemble the kwargs list for the Axes docstring, but some Eric> of these, like figure and position, duplicate required Eric> arguments so they don't really makes sense as kwargs--even Eric> though they would work. Did you edit out other such Eric> examples? Is that the reason the Axes.__init__ kwargs list Eric> is not being generated automatically? No, the reason here is that you can't mutate the docstring outside the class, and you can't use the inspector until the class is defined. So init methods are special cases. There may be some sophisticated way to do it but the naive way class C: def somefunc(): 'a test %d' pass C.somefunc.__doc__ = C.somefunc.__doc__%1 Traceback (most recent call last): File "<ipython console>", line 1, in ? TypeError: attribute '__doc__' of 'instancemethod' objects is not writable Absent something sophisticated, this morning while I was thinking about the need to systematize the __init__ method kwarg handling, I considered that maybe we should build a kwdocd module using the analog of boilerplate.py. Eg we would manually build the file which defines the kwdocd dictionary in a separate file. Something like: import matplotlib.artist import matplotlib.patches for o in dir(matplotlib.patches): if not isinstance(o, Patch): continue name = o.__name__ s = matplotlib.artist.kwdoc(o) # now write a dictionary entry to kwdoc.py with key=name and val=s and ditto for all other artists. We could then use this dict in __init__ methods and class methods. Not terribly elegant, but neither is boilerplate.py, but it would generate readable code, and having the kwdocd strings in a file would have some utility for developers and users. There is a bit of a bootstrapping problem here but it could be solved w/o too much difficulty. But if we can solve the problem of outside class docstring interpolation, this will be moot. This looks like a job for c.l.py. I googled a bit and it looks like their are some approaches using metaclasses:*python*&rnum=1#f77e00ffefadf223*python*&rnum=2#af19c967ab0a87eb Both of these discuss generating a new class with a modified class docstring rather than with a modified class method docstring, but perhaps there is an analog. I confess this metaclass stuff makes me feel queezy for reasons I don't fully understand, but I like to avoid python black magic when possible. JDH
http://sourceforge.net/p/matplotlib/mailman/message/8931311/
CC-MAIN-2015-32
refinedweb
2,707
65.52
Content-type: text/html #include <stdio.h> #include <filehdr.h> #include <syms.h> #include <ldfcn.h> int ldsseek (ldptr, sectindx) LDFILE *ldptr; unsigned short sectindx; int ldnsseek (ldptr, sectname) LDFILE *ldptr; char *sectname; ldsseek seeks to the section specified by sectindx of the common object file currently associated with ldptr. ldnsseek seeks to the section specified by sectname. ldsseek and ldnsseek return SUCCESS or FAILURE. If sectindx is greater than the number of sections in the object file, ldsseek fails; if there is no section name corresponding with sectname, ldnsseek fails. If there is no section data for the specified section or if it cannot seek to the specified section, either function fails. NOTE: The first section has an index of one. The program must be loaded with the object file access routine library libmld.a. ldclose(3), ldopen(3), ldshread(3), ldfcn(4). delim off
https://backdrift.org/man/tru64/man3/ldsseek.3.html
CC-MAIN-2017-26
refinedweb
146
68.47
StabilityStability As of Deno 1.0.0, the Deno namespace APIs are stable. That means we will strive to make code working under 1.0.0 continue to work in future versions. However, not all of Deno's features are ready for production yet. Features which are not ready, because they are still in draft phase, are locked behind the --unstable command line flag. deno run --unstable mod_which_uses_unstable_stuff.ts Passing this flag does a few things: - It enables the use of unstable APIs during runtime. - It adds the lib.deno.unstable.d.tsfile to the list of TypeScript definitions that are used for type checking. This includes the output of deno types. You should be aware that many unstable APIs have not undergone a security review, are likely to have breaking API changes in the future, and are not ready for production. Standard modulesStandard modules Deno's standard modules () are not yet stable. We currently version the standard modules differently from the CLI to reflect this. Note that unlike the Deno namespace, the use of the standard modules do not require the --unstable flag (unless the standard module itself makes use of an unstable Deno feature).
https://deno.land/manual@v1.9.2/runtime/stability
CC-MAIN-2022-40
refinedweb
196
67.45
Hello, I've attempted to create program that will create a bar chart of stars to look like this... -------------------------------------- 1: *** 2: * and so on, it has to read the amount of 6 numbers from the command line and then print the correct amount of stars for each, each time I try and compile this program i get the errors 1. ANSI C++ forbids comparison between pointer and integer 2. In Function 'int main ( int, char**) I am very very new to c++ and these are errors I have never come across before, and frankly the program I have been asked to write is way out of my depth. This is what I have written, whether it even does what i want it to i do not know, but I gave my best shot.This is what I have written, whether it even does what i want it to i do not know, but I gave my best shot.Code:#include <iostream> #include <stdlib.h> #include <assert.h> using namespace std; void main ( int n, char c) /*int main (int argc, char* argv [])*/ { int n [6]; char c; int total = 0; if ( argc != 7 ) { cerr << "Usage: ./a.out n1 n2 n3 n4 n5 n6\n" ; exit(1) ; } while ( n < 6) { cin >> n [c]; c++; } for ( int i = 0; i < 6; i++) { n [i] = atoi ( argv [i+1]); assert (0 <= n [i] && n [i] <= 100); } for ( int i = 0; i < 6; i++) { total += n [i]; } cout <<"--------------------------------------------------/n" << total * c << "*"; } any suggestions for why it keeps throwing up errors would be greatly appreciated. thanks Karla.
http://cboard.cprogramming.com/cplusplus-programming/86038-barchart-unfamiliar-compiling-errors.html
CC-MAIN-2014-42
refinedweb
262
82.07
Removing xalan.jarDimitris Andreadis Feb 23, 2006 4:56 AM (I'm copying the discussion from the dev-list here for reference) "dimitris@jboss.org" wrote: I tried to remove lib/endorsed/xalan.jar in 4.0.x and the situation is as follows: Works fine under jdk1.5, but breaks under jdk5 when the XSLSubDeployer does a TransformerFactory tf = TransformerFactory.newInstance(); The problem is lib/endorsed/xml-apis.jar includes a javax.xml.transform.TransformerFactory that simply points to org.apache.xalan.processor.TransformerFactoryImpl, if the javax.xml.transform.TransformerFactory property is not set! And that overrides the jdk5 javax.xml.transform.TransformerFactory that points to com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl. If (when run under jdk5) I set -Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.intern al.xsltc.trax.TransformerFactoryImpl, but I don't know if this should work with all jdk5 jdks. What options do we have? Hack xml-apis to remove the offending javax.xml.transform.TransformerFactory class? "scott.stark@jboss.org" wrote: The question is where the the xml-apis.jar come from then? It should not include a TransformerFactory if its not from the xalan distribution which is what I suspect. The origin of the xml jars needs to be validated and if the xerces distribution defaults to configuring a TransformerFactory, that should be removed. The xml parser is needed to override the buggy jdk version. "dimitris@jboss.org" wrote: I traced this down to a TranformerFactory included in the xml-apis.jar that comes with xerces tools (e.g. Xerces-J-tools.2.7.1.zip). This is tagged as 1.3.02 and in turn originates from The xml-commons hadn't had any releases for some time, so the tagged xml-apis.jar comes directly from their cvs. I think I will remove all javax.xml.transform.** from xml-apis.jar to create a new xml-apis-no-transform.jar and include this instead. From a quick test it seems to be working with both jdk1.4 and jdk5. "scott.stark@jboss.org" wrote: This is probably a jaxp requirement to not subset the apis. The next question is whether the xml-apis.jar is needed. Is jdk1.4.x at jaxp 1.2? The xerces 2.7.x release supports jaxp 1.3. The potential problem with doing this is are there dependencies between the javax.xml.transform.* classes and the other javax.xml.* classes. The more I think about it the more I doubt this is legal for a java ee distribution. If we are bundling jaxp 1.3, we need it to be the complete 1.3 set of apis and we would just have to patch the TranformerFactory to do the right thing, whatever that is. "dimitris@jboss.org" wrote: It all boils down to here: ... return (TransformerFactory) FactoryFinder.find( /* The default property name according to the JAXP spec */ "javax.xml.transform.TransformerFactory", /* The fallback implementation class name */ "org.apache.xalan.processor.TransformerFactoryImpl"); ... I don't see how we can patch the TF to return a proper fallback implementation name, because we just don't know what that is. On Sun jdk1.4 it would be org.apache.xalan.processor.TransformerFactoryImpl On Sun jdk5 it would be com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl But on other vendor jdks, whats the correct value? And if it is just a question of setting a sensible default value, we could do just the same setting the javax.xml.transform.TransformerFactory property. But isn't this exactly the role of the TransformerFactory offered by the jdk vendor? I think the best compromise is to just remove javax.xml.transform.TransformerFactory from xml-apis.jar (replace with xml-apis-notf.jar ?) to let the vendor supplied default apply. "scott.stark@jboss.org" wrote: Setting this via a system property cannot be done as this is a global override. We could simply externalize the default factory name to an attribute of the jboss server info mbean and fallback to the jdk default if it cannot be found. I don't know if an extension class can get access to a class from the jdk rt.jar via the ClassLoader.getSystemClassLoader(). "dimitris@jboss.org" wrote: I don't follow why this is necessary. If we just remove javax.xml.transform.TransformerFactory from xml-apis.jar then the jdk bundled TransformerFactory will be used to choose the correct implementation. A user can always drop his own xalan.jar to lib/endorsed (for jdk1.4/5), or server/xxx/lib for jdk5, or use a scoped xalan.jar to override the jdk version, since xalan.jar contains: META-INF/services/javax.xml.transform.TransformerFactory file containing the class name of its implementation. "scott.stark@jboss.org" wrote: Its not clear that removal of the javax.xml.transform.* is safe. There are references to org.w3c.dom.* from the javax.xml.transform.dom for example. We cannot simply remove just the javax.xml.transform.TransformerFactory. It would have to be all javax.xml.transform.* classes. The presence of the javax.xml.transform.TransformerFactory should not affect a user being able to override the transformer by dropping in an xsl jar with a META-INF/services/javax.xml.transform.TransformerFactory entry as this takes precedence over the TransformerFactory defaults. "dimitris?) Removing javax.xml.transform.* is not clear that is safe (I guess because you might have incompatible parser api+impl <-> transformer api+impl interactions?) Ok, we are doomed :) "scott.stark?) > This is always the case though. Any attempt to override the xsl factory will be subject to matching the javax.xml.transform.* in effect. > Removing javax.xml.transform.* is not clear that is safe (I guess > because you might have incompatible parser api+impl <-> transformer > api+impl interactions?) > > Ok, we are doomed :) There are some xml parser class dependencies in the javax.xml.transform.dom and javax.xml.transform.sax packages. I just don't know if the javax.xml.transform.* in jaxp 1.3 can use the 1.2 xml parsers. It's a tradeoff between introducing a xsl parser dependency that the user may not want vs modifying the TransformerFactory to be more flexible at the cost of the user potentially have to configure the TransformerFactory default. I think modifying the TransformerFactory is the most flexible, but maybe just bundling the xsl parser is the simplest. 1. Re: Removing xalan.jarRichard Opalka Feb 5, 2010 3:51 AM (in response to Dimitris Andreadis) I don't wanna sound PITA and I know this is the never ending story discussion but why we're still not removing it? I think it's time to remove xalan from JBoss or at least from endorsed directory. I came to this when I started analyzing So my question is does some project depend on packages: * org.apache.xalan.* * org.apache.xml.* * org.apache.xpath.* from xalan.jar or it's problem of JVM incorporating buggy implementation of it? I see from that in the past there used to be a buggy implementation in JDK 4. According to there used to be some issues in the past when endosing xalan.jar together with xml-apis.jar on JDK5. But now xml-apis.jar isn't endorsed any more and we're just supporting JDK6 and above. I also see we're using some brew version of it (incorporating some xalan patches). The issues these patches are trying to solve are also in implementation of supported JVMs? I found that JBossWS depends on xalan (should be fixed soon). How about other projects? Do MC, JBossXB or some other projects depend on xalan directly? 2. Re: Removing xalan.jarBrian Stansberry Feb 6, 2010 8:47 AM (in response to Richard Opalka)I suggest you ask this question on the jboss-development mailing list. Relevant people may not follow this forum. I saw this post quite by accident. 3. Re: Removing xalan.jarjaikiran pai Feb 6, 2010 9:02 AM (in response to Richard Opalka) And since this question is more related to JBoss AS development than "Miscellaneous Development", i'll move it to our AS dev forum. 4. Re: Removing xalan.jarAles Justin Feb 8, 2010 7:45 AM (in response to Richard Opalka) How about other projects? Do MC, JBossXB or some other projects depend on xalan directly? For anything XML related, MC depends on XB. 5. Re: Removing xalan.jarRichard Opalka Feb 8, 2010 9:34 AM (in response to Dimitris Andreadis)I executed tattletale against AS trunk and it reports the following jars are dependent on xalan impl. classes: JBoss code: * jbossws-native-core.jar (JBoss Web Services) * jbossxacml.jar (JBoss Security) Thirdparty code (from apache.org) * bsf.jar * xmlsec.jar I fixed jbossws-native-core.jar to don't use xalan classes directly (JBWS-2919) I reported issue to security project to don't depend directly on xalan classes too (SECURITY-452) Unfortunately thirdparty bsf.jar and xmlsec.jar (from apache.org) depend on xalan directly too. Dimitris, I see you're the author of that brings in support for dynamic languages. From BSF configuration file I can see: --- #. # xslt = org.apache.bsf.engines.xslt.XSLTEngine, xslt --- The XSLTEngine from BSF uses xalan org.apache.xpath.objects.XObject class directly This is not instatiated until xslt script is provided to ScriptingListener. Q: Do we want to support xslt scripts as well via our scripting language support? I guess yes? Regarding xmlsec.jar from tattletale report I can see there are just two projects using it: * JBoss Web Services * JBoss Security and this xmlsec.jar depends on the following xalan impl. classes: org.apache.xml.dtm.DTM org.apache.xml.dtm.DTMManager org.apache.xml.utils.PrefixResolver org.apache.xml.utils.PrefixResolverDefault org.apache.xml.utils.URI org.apache.xml.utils.URI$MalformedURIException org.apache.xpath.CachedXPathAPI org.apache.xpath.NodeSetDTM org.apache.xpath.XPath org.apache.xpath.XPathContext org.apache.xpath.compiler.FunctionTable org.apache.xpath.functions.Function org.apache.xpath.objects.XNodeSet org.apache.xpath.objects.XObject This is the problem I don't know how to fix But I see there's no reason to have xalan in endorsed directory to make it work. We can move it away from * $JBOSS_HOME/lib/endorsed and copy it to * $JBOSS_HOME/client * $JBOSS_HOME/common/lib What do you think guys?
https://developer.jboss.org/thread/105351
CC-MAIN-2018-22
refinedweb
1,728
52.97
July 21, 2020. We've developed and open sourced TransCoder, an entirely self-supervised neural transcompiler system that can make code migration far easier and more efficient. Our method is the first AI system able to translate code from one programming language to another without requiring parallel data for training. We’ve demonstrated that TransCoder can successfully translate functions between C++, Java, and Python 3. TransCoder outperforms open source and commercial rule-based translation programs. In our evaluations, the model correctly translates more than 90 percent of Java functions to C++, 74.8 percent of C++ functions to Java, and 68.7 percent of functions from Java to Python. In comparison, a commercially available tool translates only 61.0 percent of functions correctly from C++ to Java, and an open source translator is accurate for only 38.3 percent of Java functions translated into C++. Self-supervised training is particularly important for translating between programming languages. Traditional supervised-learning approaches rely on large-scale parallel datasets for training, but these simply don’t exist for COBOL to C++ or C++ to Python, for example. TransCoder relies exclusively on source code written in just one programming language, rather than requiring examples of the same code in both the source and target languages. It requires no expertise in the programming languages, and it is easy to generalize TransCoder’s approach to additional programming languages. We have also created a new evaluation metric designed expressly for this domain. TransCoder could be useful for updating legacy codebases to modern programming languages, which are typically more efficient and easier to maintain. It also shows how neural machine translation techniques can be applied to new domains. As with Facebook AI’s previous work using neural networks to solve advanced mathematics equations, we believe NMT can help with other tasks not typically associated with translation or pattern recognition tasks. In natural language, recent advances in neural machine translation have been widely accepted, even among professional translators, who rely more and more on automated machine translation systems. However, their applications to code translation have been limited due to the scarcity of parallel data in this domain. Programmers still rely on rule-based code translators, which require experts to review and debug the output, or they simply translate code manually. TransCoder overcomes these challenges by leveraging recent advances in unsupervised machine translation to programming languages. We built a sequence-to-sequence (seq2seq) model with attention, composed of an encoder and a decoder with a transformer architecture. TransCoder uses a single shared model, based in part on Facebook AI’s previous work on XLM, for all programming languages. We trained it following the three principles of unsupervised machine translation detailed in Facebook AI’s previous research: initialization, language modeling, and back translation. We first leveraged source code from open source GitHub projects to pretrain our model using a masked language model (MLM) objective. As in the context of natural language processing, this pretraining creates cross-lingual embeddings: Keywords from different programming languages that are used in similar contexts are very close in embedding space (e.g., catch and except). The cross-lingual nature of these embeddings comes from the significant number of common tokens (anchor points) that exist across languages. Examples of anchor points include keywords common to C++, Java, and Python (e.g., for, while, if, try), as well as mathematical operators, digits, and English strings appearing in the source code. Pretraining with MLM allows TransCoder to generate high-quality representations of input sequences. However, the decoder lacks the capacity to translate, as it has never been trained to decode a sequence based on a source representation. To address this issue, we trained the model to encode and decode sequences with a Denoising Auto-Encoding (DAE) objective. The DAE objective operates like a supervised machine translation algorithm, where the model is trained to predict a sequence of tokens given a corrupted version of that sequence. The first symbol given as input to the decoder is a special token indicating the output programming language. At test time, a Python sequence can be encoded by the model and decoded using the C++ start symbol to generate a C++ translation. The quality of the C++ translation will depend on the “cross-linguality” of the model: If the Python function and a valid C++ translation are mapped to the same latent representation by the encoder, the decoder will successfully generate this C++ translation. Cross-lingual model pretraining and Denoising Auto-Encoding alone are enough to generate translations. However, the quality of these translations tends to be low, as the model is never trained to do what it is expected to do at test time, i.e., to translate functions from one language to another. To address this issue, we use back-translation, which is one of the most effective methods to leverage monolingual data in a weakly supervised scenario. We use a single model and a different start token for each target language. It is trained to translate from source to target and from target to source in parallel. The target-to-source version is used to translate target sequences into the source language, producing noisy source sequences corresponding to the ground truth target sequences. The model can then be trained in a weakly supervised manner to reconstruct the target sequences from the noisy source sequences and learn to translate from source to target. The target-to-source and source-to-target versions are trained in parallel until convergence. To evaluate their models, most previous studies of source-code translation have relied on metrics used in natural language, such as BLEU score or other methods based on the relative overlap between tokens. These types of metrics are not well suited to programming languages, however. Two programs with small syntactic discrepancies might achieve a very high BLEU score while still producing very different results when the code is executed. Conversely, semantically equivalent programs with different implementations will have low BLEU scores. An alternative metric is the reference match, or the percentage of translations that perfectly match the ground truth reference, but this often underrates the quality of the translation because it is unable to recognize semantically equivalent code. To better measure the performance of TransCoder and other code translation techniques, we’ve created a new metric called computational accuracy, which evaluates whether the hypothesis function generates the same outputs as the reference when given the same inputs. We are also releasing our test set and the scripts and unit tests we used to compute this metric. Python input def SumOfKsubArray(arr, n, k): Sum = 0 S = deque() G = deque() for i in range(k): while (len(S) > 0 and arr[S[-1]] >= arr[i]): S.pop() while (len(G) > 0 and arr[G[-1]] <= arr[i]): G.pop() G.append(i) S.append(i) for i in range(k, n): Sum += arr[S[0]] + arr[G[0]] while (len(S) > 0 and S[0] <= i - k): S.popleft() while (len(G) > 0 and G[0] <= i - k): G.popleft() while (len(S) > 0 and arr[S[-1]] >= arr[i]): S.pop() while (len(G) > 0 and arr[G[-1]] <= arr[i]): G.pop() G.append(i) S.append(i) Sum += arr[S[0]] + arr[G[0]] return Sum The example below shows how TransCoder translated sample code from Python to C++. We used this code as input into the model: TransCoder successfully translated the Python input function SumOfKsubArray into C++. It also inferred types of the arguments, return type, and parameters of the function. The model appended the Python dequeue() container to the C++ implementation dequeue<> . Here is the model’s output in C++: C++ unsupervised translation int SumOfKsubArray(int arr[], int n, int k){ int Sum = 0; deque <int> S; deque <int> G; for(int i = 0; i < k; i ++){ while((int) S.size() > 0 && arr[S.back()] >= arr[i]) S.pop_back(); while((int) G.size() > 0 && arr[G.back()] <= arr[i]) G.pop_back(); G.push_back(i); S.push_back(i); } for(int i = k; i < n; i ++){ Sum += arr[S.front()] + arr[G.front()]; while((int) S.size() > 0 && S.front() <= i - k) S.pop_front(); while((int) G.size() > 0 && G.front() <= i - k) G.pop_front(); while((int) S.size() > 0 && arr[S.back()] >= arr[i]) S.pop_back(); while((int) G.size() > 0 && arr[G.back()] <= arr[i]) G.pop_back(); G.push_back(i); S.push_back(i); } Sum += arr[S.front()] + arr[G.front()]; return Sum; } Automatic code translation has the potential to make programmers working in companies or on open source projects more efficient by allowing them to integrate various codes more easily from other teams within the company or other open source projects. It can also greatly reduce the effort and expense of updating an old codebase written in an ancient language. Advances in transcompilation could spur companies and other institutions to update to more recent languages and facilitate future innovation, which could benefit the people who use their services as well as the institutions themselves. Advances in machine translation for programming languages could also help people who don’t have the time or cannot afford courses to learn to program in multiple languages. More broadly, AI has the potential to help with other programming tasks. For example, Facebook AI has previously shared Neural Code Search, a method for using natural language in queries about code, and Getafix, a tool that learns to automatically suggest fixes for coding bugs. While TransCoder isn’t designed to help with debugging or improving code quality, it has the potential to help engineers migrate old codebases or use external code written in other languages. In order to promote future research on using deep learning for code translation, we are also releasing a test set that enables other researchers to evaluate code translation models using computational accuracy instead of semantics-blind models. We look forward to seeing how others build on our work with TransCoder and advances self-supervised learning for new kinds of translation tasks. Research Assistant Research Engineer Research Engineering Manager Research Scientist
https://ai.facebook.com/blog/deep-learning-to-translate-between-programming-languages
CC-MAIN-2021-04
refinedweb
1,678
55.03
Taking Your Database Beyond a Single Kubernetes Cluster Running a database (or indeed any application) across multiple regions or Kubernetes clusters is tricky without proper care and planning up front. Join the DZone community and get the full member experience.Join For Free Global applications need a data layer that is as distributed as the users they serve. Apache Cassandra has risen to this challenge, handling data needs for the likes of Apple, Netflix, and Sony. Traditionally, managing data layers for a distributed application was handled with dedicated teams to manage the deployment and operations of thousands of nodes — both on-premises and in the cloud. To alleviate much of the load felt by DevOps teams, we evolved a number of these practices and patterns in K8ssandra, leveraging the common control plane afforded by Kubernetes (K8s) There has been a catch though — running a database (or indeed any application) across multiple regions or K8s clusters is tricky without proper care and planning up front. To show you how we did this, let’s start by looking at a single region K8ssandra deployment running on a lone K8s cluster. It is made up of six Cassandra nodes spread across three availability zones within that region, with two Cassandra nodes in each availability zone. In this example, we’ll use the Google Cloud Platform (GCP) zone name. However, our example here could just as easily apply to other clouds or even on-prem. Here’s where we are now: The goal is to have two regions, each with a Cassandra data center. In our cloud-managed K8s deployment here, this translates to two K8s clusters — each with a separate control plane, but utilizing a common virtual private cloud (VPC) network. By expanding our Cassandra cluster into multiple data centers, we have redundancy in case of a regional outage, as well as improved response times and latencies to our client applications given local access to data. On the surface, it would seem like we could achieve this by simply spinning up another K8s cluster deploying the same K8s YAML. Then just add a couple tweaks for Availability Zone names and we can call it done, right? Ultimately the shape of the resources is very similar, and it’s all K8s objects. So, shouldn’t this just work? Well, maybe. Depending on your environment, this approach might work. If you’re really lucky, you may be a firewall rule away from a fully distributed database deployment. Unfortunately, it’s rarely that simple. Even if some of these hurdles are easily cleared, there are plenty of other innocuous things that can go wrong and lead to a degraded state. Your choice of cloud provider, K8s distro, command-line flag, and yes, even DNS — these can all potentially lead you down a dark and stormy path. So, let’s explore some of the most common issues you might run into, so you can avoid them. Common Hurdles on the Race to Scale Even if some of your deployment seems to be working well initially, you will likely encounter a hurdle or two as you grow into a multi-cloud environment, upgrade to another K8s version, or begin working with different distributions and complimentary tooling. When it comes to distributed databases there’s a lot more under the hood. Understanding what K8s is doing to enable running containers across a fleet of hardware will help you develop advanced solutions — and ultimately, something that fits your exact needs. The Need for Unique IP Addresses for Your Cassandra Nodes One of the first hurdles you might run into involves basic networking. Going back to our first cluster, let’s take a look at the layers of networking involved. In our VPC shown below, we have a Classless Inter-Domain Routing (CIDR) range representing the addresses for the K8s worker instances. Within the scope of the K8s cluster there is a separate address space where pods operate and containers run. A pod is a collection of containers that have shared resources — such as storage, networking, and process space. In some cloud environments, these subnets are tied to specific availability zones. So, you might have a CIDR range for each subnet your K8s workers are launched into. You may also have other virtual machines within your VPC, but in this example we’ll stick with K8s being the only tenant. In our example, we have 10.100.x.x for the nodes and 10.200.x.x for the K8s level. Each of the K8s workers gets a slice of the 10.200.x.x CIDR range for the pods that are running on that individual instance. Thinking back to our target structure, what happens if both clusters utilize the same or overlapping CIDR address ranges? You may remember these error messages when first getting into networking: Errors don’t look like this with K8s. You don’t have an alert that pops up warning you that your clusters cannot effectively communicate. If you have a cluster that has one IP space, and then you have another cluster for the same IP space or where they overlap, how does each cluster know when a particular packet needs to leave its address space and instead route through the VPC network to the other cluster, and then into that cluster’s network? By default there really is no hint here. There are some ways around this; but at a high level, if you’re overlapping, you’re asking for a bad time. The point here is that you need to understand your address space for each cluster and then carefully plan the assignment and usage of those IPs. This allows for the Linux kernel (where K8s routing happens) and the VPC network layer to forward and route packets as appropriate. But what if you don’t have enough IPs? In some cases, you can’t give every pod its own IP address. So, in this case, you would need to take a step back and determine what services absolutely must have a unique address and what services can be running together in the same address space. For example, if your database here needs to be able to talk to each and every other pod, it probably needs its own unique address. But if your application tiers in the East Coast and in the West Coast are just talking to their local data layer, they can have their own dedicated K8s clusters with the same address range and avoid conflict. In our reference deployment, we dedicated non-overlapping ranges in K8s clusters for the layers of infrastructure that MUST be unique and overlapping CIDR ranges where services will not communicate. Ultimately, what we’re doing here is flattening out the network. With non-overlapping IP ranges, we can now move on to routing packets to pods in each cluster. In the figure above, you can see the West Coast is 10.100, and the East Coast is 10.150, with the K8s pods receiving IPs from those ranges. The K8s clusters have their own IP space, 200 versus 250, and the pods are sliced off just like they were previously. How to Handle Routing Between the Cassandra Data Centers So, we have a bunch of IP addresses and we have uniqueness to those addresses. Now, how do we handle the routing of this data and the communication and discovery of all of this? There’s no way for the packets destined for cluster A to know how they need to be routed to cluster B. When we attempt to send a packet across cluster boundaries, the local Linux networking stack sees that this is not local to this host or any of the hosts within the local K8s cluster. It then forwards the packet on to the VPC network. From here, our cloud provider must have a routing table entry to understand where this packet needs to go. In some cases this will just work out of the box. The VPC routing table is updated with the pod and service CIDR ranges, informing which hosts packets should be routed. In other environments, including hybrid and on-premises, this may take the form of advertising the routes via BGP to the networking layer. Yahoo! Japan has a great article covering this exact deployment method. However, these options might not always be the best answer, depending on what your multi-cluster architecture looks like within a single cloud provider. Is it hybrid- or multi-cloud, with a combination of on-prem, with two different cloud providers? While you could certainly instrument all that across all those different environments, you can count on it requiring a lot of time and upkeep. Some Solutions to Consider Overlay Networks An easier answer is to use overlay networks, in which you build out a separate IP address space for your application — which, in this case, is a Cassandra database. Then you would run that on top of the existing Kube network leveraging proxies, sidecars and gateways. We won’t go too far into that in this post, but we have some great content on how to connect stateful workloads across K8s clusters that will show you at a high level how to do that. So, what’s next? Packets are flowing, but now you have some new K8s shenanigans to deal with. Assuming that you get the network in place and have all the appropriate routing, some connectivity between these clusters exists, at least at an IP layer. You have IP connectivity pods and Cluster 1 can talk to Pods and Cluster 2, but you now also have some new things to think about. Service Discovery With a K8s network, identity is transient. Due to cluster events, a pod may be rescheduled and receive a new network address. In some applications this isn’t a problem. In others, like databases, the network address is the identity — which can lead to unexpected behavior. Even though IP addresses may change, over time our storage and thus the data each pod represents stays persistent. We must have a way to maintain a mapping of addresses to applications. This is where service discovery enters the fold. In most circumstances service discovery is implemented via DNS within K8s. Even though a pod’s IP address may change, it can have a persistent DNS-based identity that is updated as cluster events occur. This sounds great, but when we enter the world of multi-cluster we have to ensure that our services are discoverable across cluster boundaries. As a pod in Cluster 1, I should be able to get the address for a pod in Cluster 2. DNS Stubs One approach to this conundrum is DNS stubs. In this configuration we configure the K8s DNS services to route requests for a specific domain suffix to our remote cluster(s). With a fully qualified domain name, we can then forward the DNS lookup request to the appropriate cluster for resolution and ultimately routing. The gotcha here is that each cluster requires a separate DNS suffix set through a kubelet flag, which isn’t an option in all flavors of K8s. Some users work around this by using namespace names as part of the FQDN to configure the stub. This works, but is a little bit of a hack instead of setting up proper cluster suffixes. Managed DNS Another solution similar to DNS stubs is to use a managed DNS product. In the case of GCP there is the Cloud DNS product, which handles replicating local DNS entries up to the VPC level for resolution by outside clusters, or even virtual machines within the same VPC. This option offers a lot of benefits, including: - Removing the overhead of managing the cluster-hosted DNS server — Cloud DNS requires no scaling, monitoring, or managing of DNS instances, because it is a hosted Google service. - Local resolution of DNS queries on each Google K8s Engine (GKE) node — Similar to NodeLocal DNSCache, Cloud DNS caches DNS responses locally, providing low latency and high scalability DNS resolution. - Integration with Google Cloud’s operations suite — This provides for DNS monitoring and logging. - VPC scope DNS — Provides for multi-cluster, multi-environment, and VPC-wide K8s service resolution. Cloud DNS abstracts away a lot of the traditional overhead that you would have. The cloud provider is going to manage the scaling, the monitoring and security patches, and all the other aspects you would expect from a managed offering. There are also some added benefits to some of the cloud providers with GKE providing a node local DNS cache, which reduces latency by running a DNS cache at a lower level so that you’re not waiting on DNS response. For the long term, a managed service specifically for DNS will work fine if you’re only in a single cloud. But, if you’re spanning clusters across multiple cloud providers and your on-prem environment, managed offerings may only be part of the solution. The Cloud Native Computing Foundation (CNCF) provides a multitude of options, and there are tons of open source projects that really have come a long way in helping to alleviate some of these pain points, especially in that cross-cloud, multi-cloud, or hybrid-cloud type of scenario. Published at DZone with permission of Christopher Bradford. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/taking-your-database-beyond-a-single-kubernetes-cl
CC-MAIN-2022-21
refinedweb
2,238
60.04
Android: Bitmap to Integer array Posted by DimasTheDriver | Oct 20th, 2011 | Filed under Programming . The array is later processed and encoded into the same Bitmap object, creating a new image that gets displayed on the screen. Here’s the code: package fortyonepost.com.btia; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.ImageView; public class BitmapToIntArrayActivity extends Activity { //a Bitmap object private Bitmap bmp; //an array that stores the pixel values private int intArray[]; //an ImageView, to render the original image private ImageView iv_originalImage; //an ImageView, to render the modified image private ImageView iv_imageFromArray; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //initialize the ImageView objects using data from the 'layout.xml' file iv_originalImage = (ImageView) findViewById(R.id.iv_originalImage); iv_imageFromArray = (ImageView) findViewById(R.id.iv_imageFromArray); //initialize the Bitmap Object bmp = BitmapFactory.decodeResource(getResources(), R.drawable.four_colors); //Guarantees that the image is decoded in the ARGB8888 format bmp = bmp.copy(Bitmap.Config.ARGB_8888, true); //draw the Bitmap, unchanged, in the ImageView iv_originalImage.setImageBitmap(bmp); //Initialize the intArray with the same size as the number of pixels on the image intArray = new int[bmp.getWidth()*bmp.getHeight()]; //copy pixel data from the Bitmap into the 'intArray' array bmp.getPixels(intArray, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight()); //replace the red pixels with yellow ones for (int i=0; i < intArray.length; i++) { if(intArray[i] == 0xFFFF0000) { intArray[i] = 0xFFFFFF00; } } //Initialize the bitmap, with the replaced color bmp = Bitmap.createBitmap(intArray, bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_8888); //Draw the bitmap with the replaced color iv_imageFromArray.setImageBitmap(bmp); } } There are a few assumptions made by the above Activity: the first is that a PNG image named ‘four_colors’ is placed at one of the project’s drawable folders. Also, there are two ImageView objects declared at the ‘main.xml‘ file. That said, at the beginning of the code, two member variables are being declared. They are, respectively, a Bitmap object and an Integer array. The former is the object that the PNG will be decoded into and the latter is the intArray that will hold the pixel information (lines 12 and 15). Next, there are two ImageView objects being declared (line 18 and 19). Their purpose is to render the image onto the screen. Then, there’s the onCreate() method, which is executed when the BitmapToIntArrayActivity is just created. At this method, the two ImageView instances are initialized with the data contained at the main.xml file (line 30 and 31). Following that, the bmp object is initialized by the BitmapFactory which decodes the four_colors image (line 34). To avoid headaches regarding the pixel format, the bmp is copied to itself, by calling the copy method which sets it to the ARGB8888 (alpha, red, green, blue, 8 bits per pixel) encoding format (line 36). Moving on to line 39, the bmp is set to be displayed at the screen using the ImageView named iv_originalImage. Finally, the intArray is initialized with the same length as the number of pixels on the Bitmap (line 42). Since there’s an array to copy the pixel data into, the getPixels() from the bmp object is called (line 45). It takes seven parameters. The first one is the array where the pixels will be copied to. The second parameter defines the index of the array where the pixel data should start being copied to. The pixels are going to be copied from the beginning, so the argument 0 is being passed. The third parameter defines the number of pixels of each row of the image. The forth and fifth parameters are the X and Y pixel coordinates in the image where the data should start being copied from. The sixth and seven parameters are the number of rows and columns to read from the image. Now, after the getPixels() method, the pixel color information from the image is going to be stored at a position in the array with four hexadecimal pairs, in the ARGB8888 (alpha, red, green, blue, 8 bits per pixel) format. The first pair is the alpha channel. The second third and forth pairs, are respectively the red, green and blue channels. For example, a pixel with a value of 0XFF0000FF, has an opaque blue color. And a pixel with a value of 0X99FF0000 is a translucent red color. Case the image just needs to be read as a pixel array, there’s nothing left to be done. However, chances are that some sort of operation or algorithm must be applied to the array of pixels, and the results must be later decoded into the bmp object again. For the above example, a simple for loop tries to find all opaque red pixels (0XFFFF0000). If it does, the red color is replaced by a yellow one (lines 48 through 54). To encode the array into the Bitmap, the static method CreateBitmap() is called, which takes four parameters: the byte array, the width and height of the image, and the pixel format (line 57). Lastly, the last piece of code inside the OnCreate() method displays this newly initialized bmp object in the screen. This is achieved by calling the setImageBitmap() method from the iv_imageFromArray object, passing the bmp as a parameter (line 60). Here’s a screenshot of the application: A screenshot of the above Activity. On a side note: for this example project, one copy of the four_colors image had been added to the three drawable folders (drawable-hdpi, drawable-mdpi, drawable-ldpi). It was necessary because, if the image gets scaled, the color replacement code could add some artifacts on the resulting image, since it’s testing for a specific color. To avoid that, try to initialize the Bitmap object using a BitmapFactory.Options object with the inScaled flag set to false. good job! 3q! Extremely helpful. Thank you.
http://www.41post.com/4396/programming/android-bitmap-to-integer-array
CC-MAIN-2014-42
refinedweb
989
56.45
As a Kubernetes Administrator, you will come across broken pods. Being able to identify the issue and quickly fix the pods is essential to maintaining uptime for your applications running in Kubernetes. In this hands-on lab, you will be presented with a number of broken pods. You must identify the problem and take the quickest route to resolve the problem in order to get your cluster back up and running. Learning Objectives Successfully complete this lab by achieving the following learning objectives: - Identify the broken pods. Use the following command to see what’s in the cluster: kubectl get all --all-namespaces - Find out why the pods are broken. Use the following command to inspect the pod and view the events: kubectl describe pod <pod_name> -n web - Repair the broken pods. Use the following command to repair the broken pods in the most efficient manner: kubectl edit deploy nginx -n web Where it says image: nginx:191, change it to image: nginx. Save and exit. Verify the repair is complete: kubectl get po -n web See the new replica set: kubectl get rs -n web - Ensure pod health by accessing the pod directly. List the pods including the IP addresses: kubectl get po -n web -o wide Start a busybox pod: kubectl run busybox --image=busybox --rm -it --restart=Never -- sh Use the following command to access the pod directly via its container port, replacing POD_IP_ADDRESSwith an appropriate pod IP: wget -qO- POD_IP_ADDRESS:80
https://acloudguru.com/hands-on-labs/repairing-failed-pods-in-kubernetes
CC-MAIN-2022-33
refinedweb
245
58.01
Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org. [Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] st: Importing command log/output log into review window Dear all, Is it possible to import the commands from a saved output log into the review window. I save my outputs in the output log but many a times I realize that I either added new data and have to reanalyze the whole thing again. As of now, I copy the command individual into the command window, fix the breaks created by the output log. If there was an easy way to import the commands on to the review window, this process would be much easier. Is there a way to import this into the review window? thanks, Sripal. * * For searches and help try: * * *
http://www.stata.com/statalist/archive/2011-05/msg01352.html
CC-MAIN-2017-30
refinedweb
144
68.5
ISO Namespace Validation Dispatching Language (NVDL) is a little language for taking an XML documents, sectioning it off into single namespace sections, attaching or detatching these sections in various ways, and then sending the resulting sections to the appropriate validation scripts. NVDL solves several problems that come up with namespaces, and as with DSRL takes a very different approach than XSD takes (not saying one is better or worse: they have different capabilities and therefore may even be used together). One of these problems is the problem that often the official schema has a wildcard to say “at this point you can put any element”, but you really want to limit this to your own elements only and you don’t want to edit the official schemas (and thereby create versioning and configuration issues). Another of these issues can be found in ODF. It allows foreign elements anywhere, and in order to validate against the schemas you have to strip these out. However, this does not mean just remove the foreign element and their children, you have to leave the non-foreign descendents in place. Now this is something that W3C XSD cannot really handle well. You can have a wildcard to allow foreign elements, and process them laxly so that when you come to an ODF namespace you start validating, but you don’t have the capability of validating that these elements are correct against the content model you want on the parent of the wildcard. You lose synch. Here is the section of ODF 1.1 clause 1.5 which gives the constraint:, or shall write documents that are valid against the OpenDocument schema if all foreign elements are removed before validation takes place. Hmmm, seems like a job for NVDL. Here is a rough NVDL script to do this. (It is untested, but thanks to members of the DSDL maillist for vetting it.) This script just takes the contents.xml file and removes all elements from a foreign namespace. It uses wildcards a bit. Then it sends the result to be validated using the schema. Note that this is a very coarse sieve: there is no need to get too smart with which namespaces are actually allowed under the main office namespace, because validation will handle that. The purpose of the script is to minimally preprocess the file so that the right elements get dispatched to the appropriate validator. <rules xmlns="" startMode="root"> <mode name="root"> <!-- Validation for content.xml --> <namespace ns="urn:oasis:names:tc:opendocument:xmlns:office:1.0"> <validate schema="super-odf.rng" useMode="odf"/> </namespace> </mode> <mode name="odf"> <namespace ns="urn:oasis:names:*"> <attach/> </namespace> <namespace ns="*"> <attach/> </namespace> <namespace ns="*"> <attach/> </namespace> <anyNamespace> <unwrap/> </anyNamespace> </mode> </rules> So there you have it: a nice declarative way to specify the validation pre-processing which can be actually run with the various NVDL processors around the place. Now we could duplicate this script to handle the other XML files in an ODF ZIP archive: to say that stylesheets files should start with the appropriate namespaces etc. (I think it would be possible to combine them all into one file, actually, so that different root namespaces would cause the stripped document to be dispatched to be validated by different schemas as appropriate.) Now
http://www.oreillynet.com/xml/blog/2008/06/a_simple_iso_nvdl_script_for_p.html
CC-MAIN-2013-20
refinedweb
549
61.06
Question: Is there any performance difference between an instance method and an extension method? Solution:1 Don't forget extension methods are just static method calls wrapped in syntactic sugar. So what you're really asking is Is there a performance difference between static and instance methods The answer is yes and there are various articles available on this subject Some links Solution:2 I would doubt there would be any performance difference because it is all syntactic sugar. The compiler just compiles it just as any other method call, except it is to a static method on a different class. Some more details from my blog about the syntactic sugar: Solution:3 It doesn't make any significant difference. See this article. I've verified the results of the test, and did another test where the static variant had a parameter with type Sample. All of them took 11495ms (+/- 4ms) on my system for 2.1 billion calls. As the article says, you shouldn't be worrying about this. Most examples and tests here aren't valid because they allow for method inlining. Especially easy on the compiler if the method is empty ;) (interesting to see that the test was slower on my system than the one in the article.. it's not exactly slow, but it might be because of the 64bit OS) Solution:4 There is a slight performance difference, due to the number of arguments being passed into the method. For instance, look at the following classes: public class MyClassInstance { public int MyProperty { get; set; } public MyClassInstance(int prop) { MyProperty = prop; } public void IncrementInstance() { MyProperty++; } } public static class MyClassStatic { public static void IncrementStatic(this MyClassInstance i) { i.MyProperty++; } } running the following code: DateTime d = DateTime.Now; MyClassInstance i = new MyClassInstance(0); for (int x = 0; x < 10000000; x++) { i.IncrementInstance(); } TimeSpan td = d - DateTime.Now; DateTime e = DateTime.Now; for (int x = 0; x < 10000000; x++) { i.IncrementStatic(); } TimeSpan te = e - DateTime.Now; td = .2499 sec te = .2655 sec due to the fact that the instance method doesn't have to pass any arguments. heres a slightly dated, but good article on performance Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2018/10/tutorial-performance-extension-method.html
CC-MAIN-2019-04
refinedweb
377
55.95
Why React-Native is Awesome Why React-Native is Awesome What is React Native? Basically it’s just React but for mobile. That’s it. There are some minor differences in element tags: you’ll use a View (or UIView for iOS) component rather than a div, an Image rather than img and there are no CSS files. The developer experience remains the same. If you have some knowledge with Objective-C or Java, you’ll have an easier time developing for mobile. Example: Basic HTML Code <div class=”container”> <img src=”” /> </div> React Native <View className={style.container} /> <Image source={{ uri: ‘’ }}> <View> It’s Really Writing Native The real catch about React-Native is that it’s actually native unlike other “Javascript for mobile” approaches which wrap your Javascript code in a fancy web view. They sometimes implement a native UI behavior, like animations but you still writing a web app and the “wrapper” does the work for you. In React, components have their own appearance which means that React handles the rendering for you. The compiler is built with an additional clean abstraction layer which separates these two functions. In order to render these. In React-Native, you write the same old Javascript, CSS and HTML you used to before, But now instead for compiling down to native code, React Native takes your application and runs it using the host platform’s Javascript Engine, without blocking the main UI thread. You get the best of both worlds - native performance, animations and behavior, without writing actually native code with Objective-C or Java, something you can never quite match with other cross-platform methods like Cordova or Titanium. Vibrant Ecosystem Since the majority of React-Native is just plain Javascript, it reaps the benefits of all the advancements in the language and it’s ecosystem. Why wait for the framework developers to implement a simple function like iterating and object and manipulating it, if you can use lodash or Ramda? Or some other fancy libraries. Thanks to the declarative views, certain libraries are perfectly suitable for usage in React-Native, such as Redux. Redux is great library for manipulating your application’s state. It’s highly testable, encourages you to write small functions that are explicit about what and how the data would change. Once you use these features of redux, your app can take all the advantages of powerful features, like global undo/redo and hot reloading. Example: Using Ramda or Lodash as extension library in React Native: class DemoComponent extends Component { render () { const friends = [ {first: ‘John’, last: ‘Doe’, is_online: true }, {first: ‘Jane’, last: ‘Doe’, is_online: false }, {first: ‘Foo’, last: ‘Bar’, is_online: true }, ]; return ( <View> { R.filter(f => f.is_online, friends).map(f => <View> { f.last }, {f.first} </View> ) } </View> ); } } Result: <View> <View> Doe, John </View> <View> Bar, Foo </View> </View>
https://www.spectory.com/blog/Why%20React-Native%20is%20Awesome
CC-MAIN-2019-18
refinedweb
473
51.89
Re: Email Programming using System.Web.Mail - From: "Ed Bitzer" <edbitzer@xxxxxxxxx> - Date: Thu, 17 Jan 2008 07:12:04 -0500 "Stephany Young" <noone@localhost> wrote in message news:eIYqnxLWIHA.1188@xxxxxxxxxxxxxxxxxxxxxxx Time for everyone to get on the same page I think. The first thing that you need to confirm is that you are, in fact, using an instance of the System.Net.Mail.SmtpClient class to senn your emails. If you're not then it's all back to square one. If you are then it would be interesting to see how you instantiate the instance. 'The book' says that if you do not supply a target 'host', either in the constructor or by setting the Host property then the instance will use whatever is specified in your application or machine configuration files. (It will 'look' in the application configuration first but if that doesn't specify the appropriate information then it will fall back to the machine configuration file.) While it doesn't say so in so many words, it implies that it doesn't 'look' anywhere else, therefore I would expect that, if you don't specify it and it isn't specified in either of the configuration files, an exception would be thrown when you call the Send method. I have just confirmed this by using: Dim _client As New SmtpClient _client.Send(New MailMessage("fromaddress", "toaddress", "Test", "Test")) It results in an InvalidOperationException with the message 'The SMTP host was not specified.'. The moment I specify a valid server then it works: Dim _client As New SmtpClient("server") _client.Send(New MailMessage("fromaddress", "toaddress", "Test", "Test")) If you are definitely NOT specifying a 'host' in your code then that means that you MUST have a 'host' specified in one or more of your config files. All it is now, is a matter of you looking to see what it is. I know of no automatic mechanism that will put such information in the configuration files (but that doesn't mean such a mechanism doesn't exist). The SmtpClient class is, as it's name suggests, a 'client' object and not a 'server' object. It will only connect to an 'up-line' SMTP server. If the recipient's 'mailbox' is not directly served by that server then the message will be relayed on to the appropriate server. "Ed Bitzer" <edbitzer@xxxxxxxxx> wrote in message news:evO2gSIWIHA.5816@xxxxxxxxxxxxxxxxxxxxxxx "rowe_newsgroups" <rowe_email@xxxxxxxxx> wrote in message news:d3d28beb-9f22-4180-a2bf-e0e83fb07327@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx On Jan 16, 12:19 pm, "Ed Bitzer" <edbit...@xxxxxxxxx> wrote: I have been able using the namespace System.Web.Mail and its method Smtp.mail.send to mail simple text messages to a small group within our 55 and older community. I need help expanding the programs capabilities. Searching this forum I did not find any related information so if I have chosen poorly, I would appreciate a suggestion of a more appropriate dotnet forum. Now what I wish is the ability to send bcc's rather than to: (would be sending to all 250 residents and would have to send in groups of 50 as required by Comcast to curtail spammers) and also wonder if this namespace handles base64 encoding so that I can send a pdf attachment. Appreciate, Ed Though it might not help with encoding (not sure) two excellent sites you need to check out are: And IMO if you are using 2.0 or higher you should be using System.Net.Mail Thanks, Seth Rowe [MVP] Seith and Patrice too, I have waded my way through all the references gave and digested sufficiently to create a prototype that sends an email To: somebody, with Bcc's to several others and can handle one or more pdf attachments encoded with Base64 - and it works<g>. Obviously you guys gave me excellent directions. I do have one more questions and that is how is this stuff getting to the recipients. I am sending from my home. I am providing system.web.mail with no information about my ISP. Does my program act as a Server and do its own thing looking up the DNS information for each of the recipients ISP's? When I use commercial software such as Thunderbird or OE I must spell out the smtp servicer and provide a username and password. Ed Stephany, I just want you and the others to know how much I appreciate your efforts on my behalf. I need to digest your latest comments but first I want all to know that I have a prototype working thanks to the references given, especially the excellent summary of threads provided at. (I am using Net 1.1 and therefore System.Web.Mail) If I do not provide an SMTP server the program works (my simple minded understanding is that VB.Net has a basic SMTP code within but better yet I can specify my local ISP, provide the username and password. If I understand correctly by this is safer avoiding any reflection that my ISP is providing an open relay. Ed . - Follow-Ups: - Re: Email Programming using System.Web.Mail - From: Stephany Young - References: - From: Ed Bitzer - Re: Email Programming using System.Web.Mail - From: rowe_newsgroups - Re: Email Programming using System.Web.Mail - From: Ed Bitzer - Re: Email Programming using System.Web.Mail - From: Stephany Young - Prev by Date: Re: writing to a file? - Next by Date: Re: List Colors At Runtime - Previous by thread: Re: Email Programming using System.Web.Mail - Next by thread: Re: Email Programming using System.Web.Mail - Index(es):
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.vb/2008-01/msg01045.html
crawl-002
refinedweb
930
62.88
@jsonql/client@jsonql/client This is jsonql browser client comes with jsonql-client (http) and optional socket clients, plus various modules for ui frameworks Basic ExampleBasic Example Stock http client const config = {} // your configuration options Using the static client with pre-generated contract (works better with Third party JS frameworks) const client =clientquery Third party JS Framework modulesThird party JS Framework modules We have developed several modules to integrate with some of the third party JS frameworks. Vuex moduleVuex module Vuex store support was add in version 1.5.19 First create a new Vuex store file (let say call it jsonql.js) const jsonqlVuexModule = Now in your store.js where you define your Vuex store VueVuex This Vuex module is namespaced. In your component {{hello}} Prefix your resolver with their typePrefix your resolver with their type There is a little different between our core jsonql client and in the above module. Normally, the client will namespaced each methods under their type: We try to be compatible with the Vuex (or most of the js state machine) style, we remove the namespace, and just construct the resolver under the client, there is one little potential danger, when you don't name each of your resolver with a unique name. But again this is an edge case, I don't think anyone in their right mind will have a query.login, auth.login at the same time? But when you find yourself in this situation. You can use the prefix option. // here we pass the prefix: true optionconst jsonqlVuexModule = Then it will turn query.helloWorld into queryHelloWorld. {{hello}} If you need this option, then remember, everything will prefix with their resolver type name, in camel case. Vuex getter: getJsonqlResultVuex getter: getJsonqlResult You should notice there is a Vuex getter method call getJsonqlResult, and you pass the resolver name (with prefix if you use prefix:true option). Then you will get back the last resolver call result via this getter. The reason is in the Vuex model, after the call to resolver, we store (commit) the result in our internal result state, and key with the resolver name. And whenever a new result return, it will get overwritten, because it's a flat object. Of course, you can simply call the actions, and wait for the promise to resolve. You will get the same effect. For example: <template><div>hello</div></template><script>// do your import vuex etc{hello: 'waiting ...'}{this}{...}</script> Vuex getter: getJsonqlErrorVuex getter: getJsonqlError Whenever an error happens, we do the same like success result, we commit to our internal error state, and you can use this getter to get it. And after we commit, we will throw it again which wrap in a generic Error. So you can also catch it again. For example: <template><div><p>hello</p><span class="error">error</span></div></template><script>// do your import vuex etc{hello: 'waiting ...'}{this}computed:...{return this}{...}</script> This getter is literally identical to getJsonqlResult. NEWBRAN LTD UK & T01SOURCE CN
https://preview.npmjs.com/package/@jsonql/client
CC-MAIN-2020-45
refinedweb
503
62.48
On Wed, 11 Oct 2006, Gergo Szakal wrote: > > On Wed, 11 Oct 2006, Gergo Szakal wrote: > > > > > a2ps: gethostname: Cannot allocate memory > > > > That sure is strange. > > > > Is your document so large that processing it uses its available memory? > > > > Can you try printing a smaller document? > > Ehe, that's my printcap. It *is* small enough. ;-) I overlooked that part. I found this German webpage that suggests using enscript instead of a2ps if you get that error. But it looks like the real problem is a broken a2ps and your dragonfly.jancso.szote.u-szeged.hu hostname is too long for it. Maybe your "a2ps" needs to be upgraded. See this patch from FreeBSD: FreeBSD's ports/print/a2ps-letter/files/patch-lib-xgethostname.c has: --- lib/xgethostname.c.orig Tue Nov 20 20:26:31 2001 +++ lib/xgethostname.c Tue Nov 20 20:26:03 2001 @@ -21,6 +21,7 @@ # include <config.h> #endif +#include <sys/param.h> #include <sys/types.h> #include <errno.h> @@ -38,7 +39,7 @@ int gethostname (); #ifndef INITIAL_HOSTNAME_LENGTH -# define INITIAL_HOSTNAME_LENGTH 34 +# define INITIAL_HOSTNAME_LENGTH MAXHOSTNAMELEN #endif char * Looks like your hostname is one character too long for a2ps :) If you have the problem with pkgsrc, please send an email to pkgsrc-users list or submit a NetBSD "pkg" PR (problem report).
http://leaf.dragonflybsd.org/mailarchive/users/2006-10/msg00143.html
CC-MAIN-2014-41
refinedweb
213
69.89
ALM Rangers - A Treasure Hunt Through ALM Readiness By ALM Rangers | April 2013 In this article,we introduce the sample Windows Store app, ALM Readiness Treasure Map, and share the design, coding and testing experiences of the Visual Studio ALM Rangers in building the app. It’s designed to provide a master catalog of the content available to help developers become proficient in Application Lifecycle Management (ALM) practices. The ALM Rangers are a group of experts who promote collaboration among the Visual Studio product group, Microsoft Services and the Microsoft MVP community by addressing missing functionality, removing adoption blockers, and publishing best practices and guidance based on real-world experiences. What Did We Do and Why? We have a confession to make: We love Visual Studio and Visual Studio Team Foundation Server (TFS). Microsoft produces some of the best software development tools available. We’re not just saying that because we work for Microsoft—we felt this way long before joining the company. These suites provide an incredible number of features but can prove daunting to new users. How do developers start learning to use these tools? This question presented itself to us in a slightly different fashion. ALM Rangers present at TechReady conferences that typically have a number of sessions describing how to improve knowledge of Microsoft development tools. The conferences even hold interactive sessions where participants can provide feedback to the internal groups building these products. We found these to be exciting opportunities for developers and consultants. After joining the ALM Rangers team, we started exploring the published guidance and quickly realized there was a significant amount of content to digest; we were unsure of where to begin studying. What we really wanted was a resource to help us become proficient in ALM practices. We began building the ALM Readiness Treasure Map Windows Store app to lead users through the materials on their journey to becoming experts. Figure 1 shows you the results of our work. It contains five categories, each with multiple topics of study: - Prepare - Quick intro - Guidance - Tooling - Workshops Figure 1 The Treasure Map Windows Store App These areas contain guides, hands-on labs, and videos to make it as easy as possible for users to pick up the skills they need quickly and effectively. Navigating the materials works particularly well on new touch-enabled devices, such as the Microsoft Surface. To provide the optimal experience, we enlisted the help of an expert UX designer and senior developers to build the app. The ALM Readiness Treasure Map Solution: UX Design Nuggets Making a Good First Impression The treasure map tile (see Figure 2) is eye-catching and bright, with an orange background used to symbolize sand. Immediately, the user sees the theme of the app—this is clear because of the palm tree and the path leading to where “X” marks the spot of the treasure. The app title is clearly visible on the tile. Making sure that the tile depicts what your app is actually about creates a good first impression. The last thing you want is for users to open your app and be confused about why they’re using it and how it can help them. Figure 2 The Treasure Map Windows Store App Tile We’ve leveraged the splash screen (see Figure 3) to show a bit more of the app’s personality and to help ensure a good launch experience. The treasure map’s splash screen renders an extended path to the treasure, which is a smooth, polished loading experience. It’s uncluttered and straightforward by design, reflecting how the UX will be. In addition, a unique screen can help reinforce the brand. Figure 3 The Treasure Map Windows Store App Splash Screen The homepage—the treasure map itself—appears once the app has loaded. Again, our clear, content-focused design immediately confirms the purpose of the app. We wanted to make this page fantastic so the user would want to explore the rest of the app. The homepage is where the journey begins and, at a glance, the user knows this is going to be a journey. The titles are the source for navigation, and because of our “content over chrome” design, they stand out. The app’s content is emphasized by removing any non-functional elements. Anyone looking to find information quickly can find all the links on the screen without having to navigate through the app, which provides a great experience for all types of users. Sometimes Overlooked, but Crucial The Windows 8 UI uses the principle of a grid system across all its apps. This principle promotes a clean, uncluttered design. The Treasure Map app employs the grid system everywhere except on the homepage and the result is that content is highly visible—more content, less chrome. This content over chrome principle is one of the more unique principles of the Windows Store app style, where visual unity contributes to a great UX. The homepage is the only page that’s an exception to this rule. We’re portraying a journey and a pirate theme that we wouldn’t have been able to achieve without visual representations. Typography is sometimes overlooked and many people don’t realize how much it can strengthen the brand of the app. Using fonts correctly and consistently helps achieve clarity and gives a clean, uncluttered look that makes the app easier to read and therefore use. The recommended fonts are Segoe UI (primarily used for UI elements like buttons), Calibri (used for reading and writing, such as in e-mails) and Cambria (for larger blocks of text). We used Segoe UI for all text other than the headers. For those, we used Blackadder ITC to establish a stronger theme (see Figure 4). We do break the font rule here, because we wanted the app’s appearance to be consistent with a paper-based map, as this helps to reinforce the pirate theme. So, in this case, it does work well. Figure 4 The Typography We Used in the Treasure Map Windows Store App Seamless and fluid navigation is crucial to provide that ease of use and great UX. Two forms of navigational patterns are recommended: the hierarchical system and the flat system (see Figure 5). The hierarchical system is what most apps use. It’s the most common and will be the most familiar type of navigation to many users. It’s also the best system to create that fluid feel yet still be easy to use. The flat system is used mainly in games, browsers, or document-creation apps, where the user can only go backward and forward at the same hierarchical level. The Treasure Map app uses the hierarchical system, and we believe that it uses it well. The homepage would be classified as the hub, and each section creates the first hierarchical branch, from where each section then creates another hierarchical branch. For example, from the homepage, the user can navigate to the Prepare section, where the user can explore other Prepare subsections. Figure 5 Recommended Navigational Patterns Usability It’s important to assess the UX of the app to improve the design so that the app is: - Easy to use - More valuable to users—for example, in the features it can offer - More desirable to use Assessing your design gives you confidence that the app has an outstanding UX and that users will find it useful, usable and desirable. So how do we assess the UX of the app? There are many ways to do this, but two common ones are self-assessments and cognitive walkthroughs, as shown in Figure 6. Figure 6 Assessing the UX of the App There are four success metrics that will help in both the self-assessment of the app as well as the cognitive walkthrough of the app. These are: - Great at: What’s the app great at? What are the focal points of the visuals? - Usable: What should users be able to understand, know or do more successfully because of the app? - Useful: What do you want the users to value? - Desirable: What parts of the app do you want to delight users or make them love? We used both self-assessments and cognitive walkthroughs. The self-assessments were carried out through each sprint and reviewed at our weekly stand-ups. The cognitive walkthroughs were carried out during the design process and through every sprint. Assessing the UX of our app helped us to understand the desire and emotional connection to experiences that a user may acknowledge. To sum up UX design: - Make sure that the tile depicts what your app is about. - Create a unique splash screen to reinforce your brand. - Write content with a clear focus. - Use the recommended grid layout to create a simple and clean design. - Don’t forget about typography. Use the recommended fonts where possible, such as Segoe UI, Calibri or Cambria. - Have a clear navigation pattern. Choose from either the hierarchical system or the flat system. - Assess the usability of your app throughout the development cycle. The Coding Jewels Before coding started, we set forth a series of coding goals for this project. These goals became the mantra for how we designed and developed the codebase. - Adaptability: Requirements can change, features can be added or cut, and designs can be thrown away in favor of something completely different. Adaptability is the name of the game! - Simplicity: Simplicity is essential for many advantages in software design, in particular for maintainability and fixability. - Testability: Quality assurance must be a high priority for every project, and the codebase must allow for comprehensive and “simple” testing. - Performance and fluidity: The app’s UX must be positive from the start. The app must display information in a timely manner, must always be responding to user input and mustn’t lag. - Team environments: Rarely is an app built by an individual contributor or even an individual team. We made sure that the app was built in a way that could be scaled to many more team members. So now that we had our goals defined, how in the world did we achieve writing an app in such a short time—working part-time—while not only meeting the functional requirements, but also our non-functional requirements as well? Luckily for us, this wheel has been built before and the construction of our app was a matter of applying proven patterns and practices to our app: - C# and XAML: We decided to use C# and XAML, primarily because the majority of the contributors on this project are familiar with this approach. This includes the languages themselves as well as the tooling and support for them. - Model-View-ViewModel (MVVM): This is a pattern for separating your presentation layer from your business logic from your objects. We chose this particular pattern because the C# and XAML technologies lend themselves very well to it. But more important, with a single pattern, we were able to begin chiseling away at our non-functional requirements. The goals that MVVM most positively affected were adaptability, testability, team environments and simplicity. Adaptability is improved in that you can interchange any of the functional pieces of your app. Perhaps a new presentation for a particular view model has been finished, and you can instantly replace it without changing any other code. Testability is improved because each core functional piece of code is separated into its own individual responsibilities, which means tests can be written against those directly and automated. Team environments are improved because you have a defined set of contracts among the app’s moving parts, allowing teams to work in parallel with one another. Simplicity is improved in that each moving part is its own defined moving part and interacts in a specific way. For more information, see “What’s New in Microsoft Test Manager 2012” at msdn.microsoft.com/magazine/jj618301. - Resources: Following the spirit of MVVM and separation of roles and replaceable parts, we decided to add resources for the definition of our fonts, buttons and other similar design elements. This helped improve team environments, simplicity and adaptability. - But what did we do about performance and fluidity? We followed the async/await pattern for long-running processes. This is one of the areas where developers might struggle in building Windows Store apps, but it doesn’t have to be. Luckily, Windows Store apps using C# and XAML are powered by the Microsoft .NET Framework 4.5, which lets you easily include asynchronous workloads into your app through this pattern. If it’s so easily done, why do folks struggle with it? The answer to this question usually boils down to using logic that’s long-running and isn’t provided out of the box by the .NET Framework. An example of this could be logic to calculate plot points for a chart based on complex mathematics. A full understanding of async and await is crucial for providing a fluid, high-performing app. For more information, see “Async Performance: Understanding the Costs of Async and Await” at msdn.microsoft.com/magazine/hh456402. Other considerations included: - Touch language: From a development perspective, this couldn’t be any easier. Nearly every out-of-the-box control supports touch in all of the ways that you expect. From a coding perspective, this was the easiest part of the app to build for. - Charms: Interacting with the charms was simple as well. Register these in your appxmanifest and add in the event handlers to each page for the specific charms you want to register, such as Search or Share. We had no issues dealing with charms. They worked well, like a charm should work. - Tiles, splash screens and orientations: All of these were handled in the appxmanifest and then through event hooks in the app at the app level. It was straightforward, and everything is detailed in the sample code. How It All Really Worked Here’s how things worked out in actual practice: - MVVM commands: MVVM was fantastic in theory. However, in reality, it proved a bit different from the usual Windows Presentation Foundation (WPF) and Silverlight development, particularly for implementing commands, because our old samples didn’t work. Luckily, Command<T> was fairly easy to implement in the new framework and can be seen in our sample app. But our woes didn’t end with commands, because ListViewBase items don’t have an attached command property! We decided to solve this for demonstrational purposes in two ways: First, we decided to solve this problem using an unused property: The property to which it’s bound returns “null” and doesn’t throw any exceptions (even if you turn all exceptions on), which is nice, but the key is in the set. In the set, instead of setting anything, we make a navigation call and pass as a parameter the index of the selected item. Second, we decided to create an attached dependency property of type ICommand. The sample implementation is in the class “ItemClickCommand” within the folder “MVVMSupport.” - Multiple view states lead to massive view files: Our view files became extremely large and more difficult to manage, primarily due to multiple view states. A different layout per view state is generally required, and you could even have different views for different display dimensions or changing dimensions, and so on. Our approach was to split them up into multiple .xaml files, using one .xaml file per view per state. For example, if we had a view called “HomePageView,” we’d have “HomePageView.xaml” inside a full, snapped and filled folder, each one in the folder for its state. - Adapting in the real world: This was a good story. After we had developed the large parts of our app—switching data providers, switching UIs and adding new charm interactions to all of the appropriate places—adapting it to changing requirements became a piece of cake. Issues were easy to track down, and much of the planning paid off because the designers could work in parallel with the developers and the sponsors. To summarize this section, from a coding standpoint, Windows Store apps are straightforward to develop properly. Following a few predefined rules, mentalities and patterns lets you create a good app quickly. The primary concerns are app view state, app lifecycle state, charm interaction, fluidity and ensuring that you code in a way that allows your design team to iterate designs at will. For more information, see dev.windows.com. Testing and Verifying Solution Quality One of the core acceptance requirements we defined from the start was to raise the sample code quality and be part of our overall quality dog-fooding program (see aka.ms/df_tooling). Stringent quality gates for geopolitical, namespace, code analysis and StyleCop (see stylecop.codeplex.com) compliance helped us produce a better solution, albeit only a sample. Testing should not be an afterthought and is as important with samples as it is with mission-critical solutions. It’s easier to enforce code quality, and to manage user expectations and requirements from the start, rather than be faced with hundreds of compliance bugs and irate testers and have to deal with feature and code churn during a belated quality-improvement cycle. Because the intention was a quick sample solution, we primarily adopted a “black box” testing strategy focusing on behavior as part of the system and user acceptance testing (UAT). The former was manually performed by the team, focusing on expected features and non-functional requirements, and exploring edge-cases where the internals were understood. The community was invited to assist with the UAT validation, performing exploratory testing based on real-world scenarios and expectations, and unearthing bugs and missing, impractical, and unclear features. As shown in Figure 7 (with the numerals here corresponding to the red-circled numbers in the figure), we typically used the Microsoft Test Manager exploratory testing feature (1) and the simulator (2) to evaluate the sample solution on a Surface-type device, captured detailed comments (3) and recorded the test session (4) for future reference. Figure 7 Exploratory Testing In the future, we’ll seriously consider the definition of more-structured test cases and the use of Microsoft Fakes to help us implement the unit and smoke testing. This will allow us to automatically and continuously validate feature changes and associated code changes. What’s Next? We will evolve the ALM Readiness Treasure Map app, and we’re considering an online update feature for the readiness reference assets. For more information, see “Understanding the Visual Studio ALM Rangers” at aka.ms/vsarunderstand; “Visual Studio ALM Ranger Solutions” at aka.ms/vsarsolutions; the ALM Readiness Treasure Map sample code at aka.ms/almtreasure; and the app itself in the Windows Store at aka.ms/vsartmapapp. We welcome your candid feedback and ideas! Anisha Pindoria is a UX developer consultant with Microsoft Consulting Services in the United Kingdom. Dave Crook is a developer consultant with Microsoft Consulting Services East Region, where his focus is Visual Studio and Team Foundation Server. Robert Bernstein is a senior developer with the Microsoft Consulting Services Worldwide Public Sector Cyber Security Team. Robert MacLean is a software developer nestled in a typical open-plan development office at BBD (bbd.co.za). Willy-Peter Schaub is a senior program manager with the Visual Studio ALM Rangers at the Microsoft Canada Development Center. Thanks to the following technical expert for reviewing this article: Patricia Wagner (Microsoft) Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
https://msdn.microsoft.com/en-us/magazine/dn166932.aspx
CC-MAIN-2019-04
refinedweb
3,269
52.6
The Atlassian Community can help you and your team get more value out of Atlassian products and practices. Hi Everybody! In our Jira 8.3.2. we have a lot of calculated fields that, based on an issue field, perform a JQL on the rest of the projects and gather a list of issues. From that list of issues we then get some custom field values and calculate them in order to get a total value (for ex. total estimated effort for a project). The scripts are written and running using Scriptrunner v6.6.0. Lately, we've noticed some errors in the logs when the fields are calculated: 2020-10-10 10:13:47,174 g2gcrm-69914:Cron Service ERROR anonymous [c.o.scriptrunner.customfield.GroovyCustomField] Script field failed on issue: XXXX-2127, field: Custom Field21 java.lang.IllegalStateException: Incorrect usage of JIRA/lucene search API. You can only create/use: ManagedIndexSearcher inside a context (request or Jira-Thread-Local). Check: JiraThreadLocalUtils for details. The errors don’t appear on one of our staging environments but are present on the live instance which I assume is because the live environment is much busier and there are a lot of queries in the Lucene index. I did some research and on the JiraThreadLocalUtil class, but unfortunately there is not much documentation to rely on. The bit of code that I assume generates this error looks like: com.atlassian.jira.issue.search.SearchResults searchResults = null; try { searchResults = searchService.search(user, query, pagerFilter); } catch (SearchException e) { e.printStackTrace(); return (Double) 0 ; } I saw one idea on a post about using “ ThreadLocalUtil” in the loop, transforming to: jiraThreadLocalUtil.preCall() try { try { searchResults = searchService.search(user, query, pagerFilter); } catch (SearchException e) { e.printStackTrace(); return (Double) 0 ; } } finally { jiraThreadLocalUtil.postCall(log, null) } However, this approach seems to break other things in Jira. I noticed some strange behavior when running filters that include the scripted fields: page formatting is off, results are not showing, "Activity" stream section is not showing, etc. Has anybody noticed this behavior and have any ideas on how to overcome this? I'm going to post the answer here, as with the help of Adaptavist support I resolved the issue by refactoring the code to: try { ThreadLocalSearcherCache.startSearcherContext() searchResults = searchService.search(user, query, pagerFilter); } catch (SearchException e) { e.printStackTrace(); return (Double) total; } finally { ThreadLocalSearcherCache.stopAndCloseSearcherContext() } by using methods from a different class: import com.atlassian.jira.issue.index.ThreadLocalSearcherCache although the documentation for this class states: Low level lucene searcher context. You almost never want to use this. Most of the time you want: JiraThreadLocalUtils.wrap(Runnable)or JiraThreadLocalUtils.wrap(java.util.concurrent.Callable) Hey. I'm still curious as to why this happens. I have encountered the same behavior. Shouldn't each instance of a scripted field, that exists in an issue, have a context i.e. project + issuetype? Or is there something I'm not understanding correctly. Would really appreciate it if somebody could shed some light on this whole thing, like what is the problem or why there is no context, when there should be.
https://community.atlassian.com/t5/Marketplace-Apps-Integrations/Incorrect-usage-of-JIRA-lucene-search-API/qaq-p/1503542
CC-MAIN-2022-40
refinedweb
516
50.23
Yes it’s new, I just open sourced it 😛 The other day I wanted to measure some DOM nodes. This is useful when you have to align items, or respond to browser width, or … lots of reasons okay. I had to align a curvy line with elements that aren’t under my control. This little stepper component uses flexbox to evenly space circles, CSS layouting aligns the title, and you see where this is going. Doesn't look like much but it's handy for data visualization. Especially when you want to align things with other things. I used a few of those snippets to position a curved line on this stepper pic.twitter.com/W9RLizRLPG — Swizec Teller (@Swizec) March 12, 2019 SVG in the background detects position of itself, positions of the title and circle, and uses those to define the start and end line of my curve. 👌 Many ways you can do this. @lavrton linked to a list of existing NPM packages that sort of do it. @mcalus shared how he uses react-sizeme to get it done. All great, but I wanted something even simpler. I also didn’t know about them and kind of just wanted to make my own. Here’s an approach I found works great Last night I figured out how to measure DOM dimensions with React Hooks. I'm sure it's been covered before but I had fun finding out. #200wordsTIL pic.twitter.com/TmFWZ9Chk0 — Swizec Teller (@Swizec) March 12, 2019 useDimensions hook This seemed like a neat approach so I turned it into an open source React Hook. You might enjoy it. Yep that’s it. It really is that simple. useRefcreates a React.ref, lets you access the DOM useStategives you place to store/read the result useLayoutEffectruns before browser paint but after all is known getClientBoundingRect()measures a DOM node. Width, height, x, y, etc toJSONturns a DOMRect object into a plain object so you can destructure Here’s how to use it in your project 👇 First, add useDimensions to your project $ yarn add react-use-dimensions or $ npm install --save react-use-dimensions Using it in a component looks like this import React from 'react'; import useDimensions from 'react-use-dimensions'; const MyComponent = () => { const [ref, { x, y, width }] = useDimensions(); return ( <div ref={ref}> This is the element you'll measure </div> ) } useDimensions returns a 2-element array. First the ref, second the dimensions. This is so multiple useDimensions hooks in the same component don’t step on each others’ toes. Create as many refs and measurement objects as you’d like. const MyComponent = () => { const [stepRef, stepSize] = useDimensions(); const [titleRef, titleSize] = useDimensions(); console.log("Step is at X: ", stepSize.x); console.log("Title is", titleSize.width, "wide"); return ( <div> <div ref={stepRef}>This is a step</div> <h1 ref={titleRef}>The title</h1> </div> ) } MIT License of course. Consider retweeting if you think it’s neat 🔥useDimensions is now an open source react hook 🔥 🐙 GitHub –> ✍ short blog –> Simple and works great 👌 pic.twitter.com/8ZWYUCUhIe — Swizec Teller (@Swizec) March 13, 2019 Enjoy .
https://swizec.com/blog/usedimensions-a-react-hook-to-measure-dom-nodes/swizec/8983
CC-MAIN-2019-22
refinedweb
514
64.61
First C# Program In the previous section, we have created a console project. Now, let's write simple C# code to understand important building blocks. Every console application starts from the Main() method of Program class. The following example code displays "Hello World!!" on the console. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpTutorials { class Program { static void Main(string[] args) { string message = "Hello World!!"; Console.WriteLine(message); } } } The following image illustrates the important parts of the above example. Let's understand the above C# structure. - Every .NET application takes the reference of the necessary .NET framework namespaces that it is planning to use with the "using" keyword e.g. using System.Text - Declare the namespace for the current class using the "namespace" keyword e.g. namespace CSharpTutorials.FirstProgram - We then declared a class using the "class" keyword: class Program - The Main() is a method of Program class which is the entry point of the console application. - String is a data type. - 'message' is a variable, that holds a value of a specified data type. - "Hello World!!" is the value of the message variable. - Console is a .NET framework class. WriteLine() is a method which you can use to display messages to the console. Compile and Run C# Program In order to see the output of the above C# program, we have to compile it and run it by pressing Ctrl + F5, or clicking Run button or by clicking the "Debug" menu and clicking "Start Without Debugging". You will see following output in the console: So this is the basic code items that you will probably use in every C# code. Let's learn about C# Class in the next section.
https://www.tutorialsteacher.com/csharp/first-csharp-program
CC-MAIN-2019-18
refinedweb
291
60.31
On Wed, Nov 7, 2012 at 12:35 PM, christofer.dutz@c-ware.de < christofer.dutz@c-ware.de> wrote: > Well this was allways my final goal. But I know that re-implemnting > something like Flexmojos would take quite some time. So my shedule was to > fix what was allready available and provide everyone with a solution that > they could use and after that to start working on something new. I would > call my work on the new FDK structure and adjusting FM to is finished and > now I would concentrate on the next generation maven plugin. > > Chris > > Chris, I am sure that the Apache Flex community would be able to help you out with your future efforts on this next generation maven plugin. Thanks, Om > > > -----Ursprüngliche Nachricht----- > Von: carlos.rovira@gmail.com [mailto:carlos.rovira@gmail.com] Im Auftrag > von Carlos Rovira > Gesendet: Mittwoch, 7. November 2012 21:28 > An: flex-dev@incubator.apache.org > Betreff: Re: [Discussion] Implementing a dedicated maven-flex-plugin > > Hi Chris, > > I think you are choosing the right path. People using old SDKs could use > old flexmojos dependency...people using apache flex could use your new > version. So I think your plan should be ok for all users of Flex. > > > > > 2012/11/7 christofer.dutz@c-ware.de <christofer.dutz@c-ware.de> > > > Hi, > > > > as most of you probably know, I'm currently working on a tool to > > generate Mavenized FDKs. In parallel I am adjusting Flexmojos to > > support the new Apache FDKs so people can build Flex applications using > Maven. > > > > So far so good. After finishing the Generator and adjusting Flexmojos > > to all of my changes, the last step was to generate the 4.8 FDK using > > the maven group id org.apache.flex instead of com.adobe.flex. > > > > Now this introduced MAJOR problems. Currently you could use Flexmojos > > with 4.8, if you compile the entire Plugin against the group id of > > apache or you could use the adobe fdks after compiling it against the > adobe group id. > > The main reason is that otherwise Maven imports two versions of the > > jars (the one of the FDK you want and the one Flexmojos was compiled > against). > > > > Sorting this out would be a total nightmare as there are really > > magical hacks working inside the build which cause any change in the > > scopes of dependencies to blow everything up. > > I guess this is because Flexmojos includes insanely much code for > > supporting legacy FDKs (back to 2.0 FDKs) and a ton of different tools > > for different parts of the build lifecycle. > > > > My question now would be if it would not be better to officially leave > > Flexmojos to be compiled against com.adobe.flex and to include an > > option in the generator to generate the Apache FDKs to the Adobe > > namespace and to let users be happy with that and use it. > > > > In parallel I would volunteer to start work on a new plugin aimed at > > apache flex, but leaving away support of the Adobe FDKs. I would > > suggest to concentrate on the main path, supporting only apache fdks, > > only flexunit > > 4.1 for unit-testing, only the newest granite code generator and so > > on. In this case this should be a manageable task, even if it will take > a while. > > As soon as the Version 1.0 is out we could start extending this to > > support more stuff our users would need. I think continuing to add > > more and more code to Flexmojos will only make it an unmaintainable > > monster whith all the problems comming from that. > > > > As I mentioned, I would volunteer to start such a thing and I think > > using Flexmojos as an inspiration on how to possibly implement > > something like that it should be manageable. > > > > What do you think? > > > > Chris > > > > > > -- > Carlos Rovira > Director de Tecnología > M: +34 607 22 60 05 > F: +34 912 35 57 77 > > > >
http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201211.mbox/%3CCACK5iZeMH9m4=FgPF814K7jjPBPqg6dSf+eRs1-rowAHYFGueg@mail.gmail.com%3E
CC-MAIN-2015-11
refinedweb
645
64
Parsing XML into a Perl structure Discussion in 'XML' started by zzapper, Sep 29, 2004. Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum. - Similar Threads Parsing XML into PHP to insert into a MySQL DBimpulse(), Oct 13, 2006, in forum: XML - Replies: - 0 - Views: - 2,649 - impulse() - Oct 13, 2006 Parsing XML input from web form into namespaced xml fileJason, Apr 27, 2007, in forum: XML - Replies: - 2 - Views: - 715 - Jason - Apr 28, 2007 Parsing Path Data into Tree StructureDale, Apr 30, 2004, in forum: Perl Misc - Replies: - 3 - Views: - 220 - Dale - May 1, 2004 Different results parsing a XML file with XML::Simple (XML::Sax vs. XML::Parser)Erik Wasser, Mar 2, 2006, in forum: Perl Misc - Replies: - 5 - Views: - 744 - Peter J. Holzer - Mar 5, 2006 Perl Complex Data Structure Parsingbanker123, Dec 3, 2006, in forum: Perl Misc - Replies: - 4 - Views: - 233 - Alan_C - Dec 5, 2006
http://www.thecodingforums.com/threads/parsing-xml-into-a-perl-structure.167918/
CC-MAIN-2015-48
refinedweb
184
71.18
. Before you start, make sure you've installed the Cygwin packages openssh, openssl, cvs, m4 and autoconf. You also need to make sure that the user environment variable MAKE_MODE is set to UNIX. If you don't do this you get very weird messages when you type make, such as: On a Win2k machine, open up a bash and do Check that your login entry is on the first line of that file. If not, move it to the top. It's OK for 'Administrator' to be the first entry, assuming you are one. However, Win9x doesn't support the calls that mkpasswd relies on (e.g., NetUserEnum). If you run mkpasswd you get errors like: The passwd file is used by ssh in a fairly rudimentary manner, so I'd simply synthesise/copy an existing Unix /etc/passwd, i.e., create an /etc/passwd file containing the line where <login> is your login id. Generate a key, by running c:/user/local/bin/ssh-keygen1. This generates a public key in .ssh/identity.pub, and a private key in .ssh/identity In response to the 'Enter passphrase' question, just hit return (i.e. use an empty passphrase). The passphrase is a password that protects your private key. But it's a pain to type this passphrase everytime you use ssh, so the best thing to do is simply to protect your .ssh directory, and .ssh/identity from access by anyone else. To do this!) If you have problems running ssh-keygen1 from within bash, start up cmd.exe and run it as follows: If you don't have an account on cvs.haskell.org, send your .ssh/identity.pub to the CVS repository administrator (currently Jeff Lewis <jlewis@cse.ogi.edu>). He will set up your account. If you do have an account on cvs.haskell.org, use TeraTerm to logon to it. Once in, copy the key that ssh-keygen1 deposited in /.ssh/identity.pub into your ~/.ssh/authorized_keys. Make sure that the new version of authorized_keys still has 600 file permission. From the System control panel, set the following user environment variables (see the GHC user guide) HOME: points to your home directory. This is where CVS will look for its .cvsrc file. CVS_RSH: c:/path_to_Cygwin/bin/ssh CVSROOT: :ext:username@cvs.haskell.org:/home/cvs/root, where username is your userid CVSEDITOR: bin/gnuclient.exe if you want to use an Emacs buffer for typing in those long commit messages. Put the following in $HOME/.cvsrc: These are the default options for the specified CVS commands, and represent better defaults than the usual ones. (Feel free to change them.). Try doing cvs co fpconfig. All being well, bytes should start to trickle through, leaving a directory fptools in your current directory. (You can rm it if you don't want to keep it.) The following messages appear to be harmless: At this point I found that CVS tried to invoke a little dialogue with me (along the lines of `do you want to talk to this host'), but somehow bombed out. This was from a bash shell running in emacs. I solved this by invoking a Cygnus shell, and running CVS from there. Once things are dialogue free, it seems to work OK from within emacs. If you want to check out part of large tree, proceed as follows: This sequence checks out the papers module, but none of its sub-directories. The "-l" flag says not to check out sub-directories. The "-f" flag says not to read the .cvsrc file whose -P default (don't check out empty directories) is in this case bogus. The cvs update command sucks in a named sub-directory. There is a very nice graphical front-end to CVS for Win32 platforms, with a UI that people will be familiar with, at wincvs.org. I have not tried it yet. In the ./configure output, ignore "checking whether #! works in shell scripts... ./configure: ./conftest: No such file or directory", and "not updating unwritable cache ./config.cache". Nobody knows why these happen, but they seem to be harmless. You have to run autoconf both in fptools and in fptools/ghc. If you omit the latter step you'll get an error when you run ./configure: You need ghc to be in your PATH before you run configure. The default GHC InstallShield creates only ghc-4.08, so you may need to duplicate this file as ghc in the same directory, in order that configure will see it (or just rename ghc-4.08 to ghc. And make sure that the directory is in your path.
https://downloads.haskell.org/~ghc/5.00/docs/building/winbuild.html
CC-MAIN-2016-40
refinedweb
774
76.62
Mark Brown Tuition Physics, Mathematics and Computer Science Tuition & Resources Introduction to Python using Turtle : A Review Posted on 11-06-19 in Computing This post is part : - What Turtle is and how to write basic commands - What loops are and why we use them - What variables are and why we use them - How we can use loops to change parameters such as colour and width What is Turtle? TODO potted history of LOGO goes here Insert photo of actual robot Turtle is a Python module for teaching students the relation between code and action. Writing a command to go forwards, makes the turtle on the screen go forwards! The aim of this course is to relate essential components of programming to a visual representation. In this way students can, hopefully, gain an understanding on the material. How to write basic commands In turtle we must important the module. In this course we use : import turtle as tl commands are then written suffixed the tl with a dot like so import turtle as tl tl.forward(100) # move forwards 100 units tl.left(90) # turn left 90 degrees tl.backward(50) # move backwards 50 units In this way we can have the Turtle draw patterns of our choosing. What is a loop and why is it important? A loop is a way of repeating code. This is done so we do not write excessively long programs. It also makes our code much easier to read! Consider an example where we draw a square import turtle as tl for _ in range(4): tl.forward(100) tl.right(90) This is much easier to read and debug than just expanding this over far too many lines. What is a variable and why is it important? A variable is essentially a labelled box. The label, chosen by you, tells the programmer what is contained within. We define variables using the = symbol. Importantly we can alter variables. This allows us to produce more complex patterns. Consider how we make a spiral import turtle as tl side = 50 edges_to_draw = 12 for _ in range(edges_to_draw): tl.forward(side) tl.left(90) side = side + 10 Using loops on lists The final part of this section looks at using lists with loops. Lists are collections of values. Consider the following example import turtle as tl tl.width(10) # set the pen width! for colour in ('red', 'green', 'blue', 'yellow'): tl.pencolor(colour) # note the spelling! tl.forward(100) tl.left(90) The key difference from the original square drawn above is that each side of the square is now a different colour. Review Exercises Write the code to produce the following videos. Ensure that you use loops where appropriate! Summary In this section we have covered a brief introduction to programming using Turtle. Important concepts imparted are variables and loops.
https://markbrowntuition.co.uk/computing/2019/06/11/introduction-to-python-using-turtle-a-review/
CC-MAIN-2022-33
refinedweb
474
66.54
ZOJ-3838-Infusion Altar Infusion Altar Time Limit: 2 Seconds Memory Limit: 65536 KB Bob. InfusionAltar, ‘#’ means Runic Matrix, ‘o’ means Arcane Pedestal, ‘.’ means an empty place, ‘a’-‘z’ means occult paraphernalia(like skulls, crystals and candles) Bob placed around the Infusion Altar. There will not be characters other than ‘a’-‘z’, ‘.’, ‘#’. . Input ‘a’-‘z’ and ‘.’ will appear out of the Infusion Altar. Output One integer for each test case which is the least number of blocks that should be changed. Sample Input 3 3 o.o .#. 5 .aab. bo.ob b.#.a bo.ob bbab. 5 aabba ao.oa a.#.a ao.oa aaaaa Sample Output 0 3 2 Hint The first sample is a standard Infusion Altar. In second sample, Bob will change his secret chamber to the following map. .bab. bo.ob a.#.a bo.ob .bab. 题目大意:根据这四条线对称。圆圈对称8个相等,线上对称4个相等。 o.o 以下是代码: #include <iostream> #include <algorithm> #include <cstring> #include <string> #include <map> #include <set> #include <cstdio> #include <cmath> #include <vector> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; string s[110]; int ans = 0,cnt = 0; for (int i = 0; i < n; i++) cin >> s[i]; for (int i = 0; i < n / 2; i++) { for (int j = 0; j < n / 2; j++) { if (i > j) //处理圆圈处,对称8个相等 { cnt = 1; int maxcnt = 1; string ret = ""; ret += s[i][j]; ret += s[j][i]; ret += s[n - 1 - i][j]; ret += s[j][n - i - 1]; ret += s[i][n - 1 - j]; ret += s[n - 1 - j][i]; ret += s[n - 1 - i][n - 1 - j]; ret += s[n - 1 - j][n - 1 - i]; sort(ret.begin(),ret.end()); for (int i = 0;i < 7; i++) { if (ret[i] == ret[i + 1]) { cnt++; maxcnt = max(cnt,maxcnt); } else cnt = 1; } ans += 8 - maxcnt; } else if (i == j) //处理对角线 { cnt = 1; int maxcnt = 1; string ret = ""; ret += s[i][j]; ret += s[i][n - j - 1]; ret += s[n - i - 1][j]; ret += s[n - i - 1][n - j - 1]; sort(ret.begin(),ret.end()); for (int i = 0;i < 3; i++) { if (ret[i] == ret[i + 1]) { cnt++; maxcnt = max(cnt,maxcnt); } else cnt = 1; } ans += 4 - maxcnt; } } } int i = (n - 1) / 2; //处理另外两条直线 for (int j = 0; j < n / 2; j++) { cnt = 1; int maxcnt = 1; string ret = ""; ret += s[i][j]; ret += s[i][n - j - 1]; ret += s[j][i]; ret += s[n - j - 1][i]; sort(ret.begin(),ret.end()); for (int i = 0;i < 3; i++) if (ret[i] == ret[i + 1]) { cnt++; maxcnt = max(maxcnt,cnt); } else cnt = 1; ans += 4 - maxcnt; } cout << ans << endl; } return 0; }
http://blog.csdn.net/loy_184548/article/details/46828701
CC-MAIN-2018-09
refinedweb
443
72.6
Hi again! So here's what im trying to do this time: 1.Open a file. 2.Capitalize the first letter of every line. 3.Put it in another file. I got stuck with the third part. It capitalize every word on the console but not in the created file. I hope i dont abuse your patience. Tx.I hope i dont abuse your patience. Tx.Code:#include <iostream> #include <fstream> using namespace std; int main() { ifstream TheFile("f2.txt"); ofstream TheCopy; TheCopy.open ("YourCopy.txt",ios::app); string ch; while (getline(TheFile,ch)) { cout.put((int toupper(ch))); else cout.put(ch); TheCopy << ch; } TheCopy.close(); TheFile.close(); cout << endl; system("pause"); }
http://cboard.cprogramming.com/cplusplus-programming/96988-ofstream.html
CC-MAIN-2015-35
refinedweb
113
73.44
Murthy's blog Webservices made simple using Ruby Was fortunate to take a look at Ruby Scripting language, got this chance while looking into Scripting Service Engine (One stop solution to run any script file in Open-ESB though it is in it's early stages we kind of tried to achieve JSR223 support in Open-ESB space. Of course lot of effort is going in that area ) As a hard core fan of webservice could not stop myself to see how ruby supports webservices implementation. After struggling for sometime could implement a server and client application. First let's see how to write a server implementation, First we require soap library how do we load it... require 'soap/rpc/standaloneServer' Now define a class class StockQuoteServer < SOAP::RPC::StandaloneServer Add the method which you would like to implement add_method(self,'getStockQuote','from') What that method can consists... def getStockQuote(from) puts "getStockQuote Service Called....." if from.eql?("SUNW") price = 4.92 return price end end You know what, we are done with Server implementation and now the question is how do you expose the service? Here is the answer server = StockQuoteServer.new('hws','urn:hws','0.0.0.0',Port) server.start is it fair enough? Oh boy we are done with creating a webservice. Now you will ask me how do you invoke it? It is even simple, can't believe it? First bind the client to the endpoint exposed @endpoint = "{Port}/" @client = SOAP::RPC::Driver.new(@endpoint, 'urn:hws') @client.add_method("getStockQuote","from") Invoke the client @client.getStockQuote(index) that's it and we are done now. So how do you feel about it, do you think it is fairly simple or you have a different feeling (I don't think so) Find server and client applications. Posted at 06:19PM Jul 02, 2007 by pedapudinarayana in Personal | Comments[2] Posted by Manidhar Puttagunta on July 17, 2007 at 02:42 AM IST # Posted by Narayana on August 04, 2007 at 11:09 AM IST #
http://blogs.sun.com/narayana/entry/webservices_made_simple_using_ruby
crawl-002
refinedweb
338
64.2
This paper introduces a new kind of primary expression that allows parameter packs to be expanded as a sequence of operators. We call these "fold expressions", named after the ubiquitous fold algorithm that applies a binary operator to a sequence values (also called accumulate in the standard library). Today, when we want to compute folds over a parameter pack, we have to resort to a handful of overloads of a variadic template in order to compute the result. For example, a simple summation might be implemented like this: auto sum() { return 0; } template<typename T> auto sum(T t) { return t; } template(typename T, typename... Ts) auto sum(T t, Ts... ts) { return t + sum(ts...); } We should be able to do better. In particular, given a function parameter pack args, we would like to be able to compute its summation like this. (args + ...) This is a significant savings in keystrokes, and programmers are much less likely to get this wrong than the implementation above. There are a number of binary operators for which folding can defined. One such is the , operator. The , operator can be used, for example, to apply a function to a sequence of elements in a parameter pack. For example, printing can be done like this: template<typename T> void print(const T& x) { cout << x << '\n'; } template<typename T> void for_each(const auto&... args) { (print(args), ...); } N4040 describes how a constrained-type-specifier is transformed into a declaration and its constraints. For example: template<typename T> concept bool Integral = std::is_integral<T>::value; template<Integral T> // "Integral T" is a constrained-parameter void foo(T x, T y); template<typename T> requires Integral<T> // Becomes this. void foo(T x, T y); Hypothetically, this works to declare constrained template parameter packs. template<Integral... Ts> // "Integral Ts" is a constrained-parameter void foo(Ts...); What are the corresponding requirements? Can we do this? template<typename... Ts> requires Integral<Ts>... // error: ill-formed void foo(Ts...); This doesn't work because we can't expand an argument pack in this context. What about this? template<typename... Ts> requires std::all_of({Ts...}) // OK? void foo(Ts...); That might work if we had range algorithms and those algorithms were declared constexpr. Unfortunately, we have neither. However, with this fold syntax, that transformation is straightforward. template<typename... Ts> requires (Integral<Ts> && ...) void foo(Ts...); The proposal adds a new kind of primary-expression, called a fold-expression. A fold expression can be written like this: (args + ...) The arguments are expanded over the + operator as left fold. That is: ((args$0 + args$1) + ...) + args$n Or, you can write the expression with the parameter pack on the right of the operator, like this: (... + args) With this spelling, the arguments are expanded over the operator as a right fold: args$0 + (... + (args$n-1 + args$n)) The fold of an empty parameter pack evaluates to a specific value. The choice of value depends on the operator. The set of operators and their empty expansions are in the table below. If a fold of an empty parameter pack is produced for any other operator, the program is ill-formed. However, all binary operators are supported to allow the use of folds over arbitrary overloaded operators. In order to support expansions over a parameter pack and other operands, or to customize the behavior for a fold over an empty parameter pack, you can also use the mathematically oriented phrasing: (args + ... + an) This expands as a left fold, including the an as the last term in the sequence. Only one of the operands can be a parameter pack. You can also expand a right fold. (a0 + ... + args) Modify the grammar of primary-expression in [expr.prim] to include fold expressions. primary-expression: fold-expression Add the a new subsection to [expr.prim] called "Fold expressions". A fold expression allows a template parameter pack ([temp.variadic]) over a binary operator. fold-expression: ( cast-expression fold-operator ... ) ( ... fold-operator cast-expression ) ( cast-expression fold-operator ... fold-operator cast-expression ) fold-operator: one of + - * / % ^ & | ~ = < > << >> += -= *= /= %= ^= &= |= <<= >>= == != <= >= && || , .* ->* An expression of the form (e op ...) where op is a fold-operator is called a left fold. The cast-expression e shall contain an unexpanded parameter pack. A left fold expands as expression ((e$1 op e$2) op ...) op e$n where $n is an index into the unexpanded parameter pack. An expression of the form (... op e) where op is a fold-operator is called a right fold. The cast-expression e shall contain an unexpanded parameter pack. A right fold expands as expression e$1 op (... (e$n-1 op e$n)) where $n is an index into the unexpanded parameter pack. [ Example: template bool all(Args... args) { return (args && ...); } all(true, true, true, false); Within the instantiation of all, the returned expression expands to ((true && true) && true) && false, which evalutes to false. — end example ] In an expression of the form (e1 op ... op e2) either e1 shall contain an unexpanded parameter pack or e2 shall contain an unexpanded parameter pack, but not both. If e1 contains an unexpanded parameter pack, the expression is a left fold and e2 is the rightmost operand the expansion. If e2 contains an unexpanded parameter pack, the expression is a right fold and e1 is the leftmost operand in the expansion. [ Example: template<typename... Args> bool f(Args... args) { return (true + ... + args); // OK } template<typename... Args> bool f(Args... args) { return (args && ... && args); // error: both operands contain unexpanded parameter packs — end example] When the unexpanded parameter pack in a fold expression expands to an empty sequence, the value the expression is shown in Table N; the program is ill-formed if the operator is not listed in Table N.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4191.html
CC-MAIN-2017-47
refinedweb
955
51.24
SystemSettingsView #include <BaseMode.h> Detailed Description Provides a interface for System Settings views. BaseMode is a standard interface for all plugins to System Settings to allow them to provide their own interface to KDE control modules. The developer need only ensure that they perform all initialization of their plugin in initEvent() to ensure that the plugin is displayed, and initial actions are loaded. Definition at line 49 of file BaseMode.h. Member Enumeration Documentation These flags are used to control the presence of the Search and Configure actions on the toolbar. Definition at line 75 of file BaseMode.h. Constructor & Destructor Documentation Constructs a BaseMode for use in System Settings. Plugin developers should perform all initialisation in initEvent() not here. - Parameters - Definition at line 44 of file BaseMode.cpp. Normal destructor. Plugin developers only need destroy what they created not what is provided by BaseMode itself. Definition at line 50 of file BaseMode.cpp. Member Function Documentation Provides information about the plugin, which is used in the About dialog of System Settings. This does not need to be implemented, and need only be implemented if the author wants information about the view displayed in the About dialog. - Returns - The about data of the plugin. Definition at line 73 of file BaseMode.cpp. Triggers a reload of the views actions by the host application. - Warning - Actions previously contained in the list must not be destroyed before this has been emitted. Provides the list of actions the plugin wants System Settings to display in the toolbar when it is loaded. This function does not need to be implemented if adding actions to the toolbar is not required. - Returns - The list of actions the plugin provides. Definition at line 83 of file BaseMode.cpp. Allows views to add custom configuration pages to the System Settings configure dialog. - Warning - Deleting the config object will cause System Settings to crash Definition at line 110 of file BaseMode.cpp. Causes System Settings to hide / show the toolbar items specified. This is used to control the display of the Configure and Search actions - Parameters - Provides access to the configuration for the plugin. - Returns - The configuration group for the plugin. Definition at line 128 of file BaseMode.cpp. Used to give focus to the plugin. Plugin should call setFocus() on the appropriate widget - Note - Failure to reimplement will cause keyboard accessibiltity and widget focusing problems Definition at line 106 of file BaseMode.cpp. Performs internal setup. Plugin developers should perform initialisation in initEvent() not here. - Parameters - Definition at line 55 of file BaseMode.cpp. Prepares the BaseMode for use. Plugin developers should perform initialisation here, creating the Models. They should perform widget initialisation the first time mainWidget() is called, not here. Definition at line 64 of file BaseMode.cpp. Causes the view to unload all modules in the module view, and return to their module selection state. - Warning - Failure to reimplement will cause modules to not be unloaded when changing views. This must be implemented. Definition at line 102 of file BaseMode.cpp. Allows views to load their configuration before the configuration dialog is shown Views should revert any changes that have not been saved. Definition at line 115 of file BaseMode.cpp. Returns the widget to be displayed in the center of System Settings. The widget should be created the first time this function is called. - Warning - This function is called multiple times, ensure the widget is only created once. - Returns - The main widget of the plugin. Definition at line 68 of file BaseMode.cpp. Provides access to the ModuleView the application uses to display control modules. - Warning - Failure to reimplement will cause modules not to be checked for configuration changes, and for the module to not be displayed in the About dialog. It must be implemented. - Returns - The ModuleView used by the plugin for handling modules. Definition at line 78 of file BaseMode.cpp. Returns the root item of the list of categorised modules. This is usually passed to the constructor of MenuModel. - Warning - This is shared between all views, and should not be deleted manually. - Returns - The root menu item as provided by System Settings. Definition at line 123 of file BaseMode.cpp. Should be implmented to ensure that views settings are saved when the user confirms their changes Views should also apply the configuration at the same time. Definition at line 119 of file BaseMode.cpp. The state of the plugin ( position of the splitter for instance ) should be saved to the configuration object when this is called. Definition at line 98 of file BaseMode.cpp. Called when the text in the search box changes allowing the display to be filtered. - Warning - Search will not work in the view if this function is not implemented. Definition at line 93 of file BaseMode.cpp. Provides the service object, which is used to retrieve information for the configuration dialog. - Returns - the service object of the plugin. Definition at line 88 of file BaseMode.cpp. Should be emitted when the type ( list of modules / display of module ) of displayed view is changed. - Parameters - - Warning - Failure to emit this will result in inconsistent application headers and change state. Provides access to item views used by the plugin. This is currently used to show the enhanced tooltips. - Returns - A list of pointers to item views used by the mode. The list can be empty. Definition at line 133 of file BaseMode.cpp. The documentation for this class was generated from the following files: Documentation copyright © 1996-2020 The KDE developers. Generated on Sat Mar 28 2020 08:30:53 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/4.x-api/kde-workspace-apidocs/systemsettings/core/html/classBaseMode.html
CC-MAIN-2020-16
refinedweb
949
59.5
scratchpad dragonchild The idea I had was to: <ol> <li>Clone the subrefs <li>Remove the ops which create the callframe and set @_ to the params passed in (except for the first one). <li>Add in an op for a label at the end of the tree corresponding to SUB_N: (where N is the sub #. <li>Replace the ops for "return (...)" with ops for "@_ = (...);goto SUB_N;" (except for the last one). <li>String the converted subrefs together. </ol> <p>I'm figuring that the lexical pads don't need to be messed with because the ops should be referring to them by memory address. And, I do want the addresses to remain the same when cloning. The reason being: <code> { my $counter; sub inc_counter { $counter++ } } </code> <p>If I chain inc_counter(), I want it to keep incrementing $counter. Maybe it is an option to clone_subref()? <p>I figured that B::Generate should be able to do this very easily, except I haven't the foggiest where to start. :-)
http://www.perlmonks.org/?displaytype=xml;node_id=358276
CC-MAIN-2016-07
refinedweb
170
73.78
Make keepalived healthcheck more configurable Bug Description Since the Newton release, users of HA routers have had a keepalived healthcheck that fails if it doesn't get a response to a single ping or if the expected tenant network address is not configured in the local namespace being watched. While this works for most cases where an environment is stable it appears to produce a lot of instability as soon as an environment gets loaded or a node fails and transitions/ In order to avoid transient problems like this from causing further instability we would like to be able to make the healthcheck a little more tolerant of transient issues. Currently the healthcheck script is generated by Neutron for each router and its contents are not configurable. It would be great to be able to change e.g. the number of pings that it will do before declaring a failure. I think that this is pretty good idea for some use cases. But as keepalived have got tons of different options can You maybe write exactly which of them You want to include and make configurable through neutron config files? Or maybe we should do it differently and e.g. propose some template of the config file and fill this template with variables, like interface name, IP addresses, etc. for specific router. That way user may be able to configure whatever keepalived options he would need by preparing this template file to the l3 agent. What do You think about it?
https://bugs.launchpad.net/neutron/+bug/1892200
CC-MAIN-2022-27
refinedweb
251
67.38
Create a pager owned vmo. #include <zircon/syscalls.h> zx_status_t zx_pager_create_vmo(zx_handle_t pager, uint32_t options, zx_handle_t port, uint64_t key, uint64_t size, zx_handle_t* out); Creates a VMO owned by a pager object. size will be rounded up to the next page size boundary, and options must be zero or ZX_VMO_NON_RESIZABLE. On success, the returned vmo has the same rights as a vmo created with zx_vmo_create(), as well as having the same behavior with respect to ZX_VMO_ZERO_CHILDREN. Syscalls which operate on VMOs require an explicit flag to allow blocking IPC to the userspace pager service; beyond this, whether or not a VMO is owned by a pager does not affect the semantics of syscalls. TODO(stevend): Update differences after updates to cloning and decommit Page requests will be delivered to port when certain conditions are met. Those packets will have type set to ZX_PKT_TYPE_PAGE_REQUEST and key set to the value provided to zx_pager_create_vmo(). The packet's union is of type zx_packet_page_request_t: typedef struct zx_packet_page_request { uint16_t command; uint16_t flags; uint32_t reserved0; uint64_t offset; uint64_t length; uint64_t reserved1; } zx_packet_page_request_t; offset and length are always page-aligned. The value of any bits in flags for which flags are not defined is unspecified - currently no flags are defined. The trigger and meaning of the packet depends on command, which can take one of the following values: ZX_PAGER_VMO_READ: Sent when an application accesses a non-resident page in a pager's VMO. The pager service should populate the range [offset, offset + length) in the registered vmo with zx_pager_supply_pages(). Supplying pages is an implicit positive acknowledgement of the request. ZX_PAGER_VMO_COMPLETE: Sent when no more pager requests will be sent for the corresponding VMO, either because of zx_pager_detach_vmo() or because no references to the VMO remain. If pager is closed, then no more packets will be delivered to port (including no ZX_PAGER_VMO_COMPLETE message). Furthermore, all future accesses will behave as if zx_pager_detach_vmo() had been called. pager must be of type ZX_OBJ_TYPE_PAGER. port must be of type ZX_OBJ_TYPE_PORT and have ZX_RIGHT_WRITE. zx_pager_create_vmo() returns ZX_OK on success, or one of the following error codes on failure. ZX_ERR_INVALID_ARGS out is an invalid pointer or NULL, or options is any value other than 0 or ZX_VMO_NON_RESIZABLE. ZX_ERR_BAD_HANDLE pager or port is not a valid handle. ZX_ERR_ACCESS_DENIED port does not have ZX_RIGHT_WRITE. ZX_ERR_WRONG_TYPE pager is not a pager handle or port is not a port handle. ZX_ERR_OUT_OF_RANGE The requested size is larger than the maximum vmo size. ZX_ERR_NO_MEMORY Failure due to lack of memory. zx_pager_detach_vmo() zx_pager_supply_pages() zx_port_wait()
https://fuchsia.googlesource.com/fuchsia/+/4b2a7378368301a5c187a6111ae336f4fe2cccda/zircon/docs/syscalls/pager_create_vmo.md
CC-MAIN-2020-16
refinedweb
413
55.03
Explanation: To switch contents displayed in the region dynamically, while dropping task flow on to the page, we select the Dynamic Region for holding the task flow. The af:region components generated in the JSF page remains same for both the static and dynamic regions. However, when we choose a dynamic region as a container for task flows, the taskFlowId referenced by the corresponding task flow binding will be pointing to an EL expression that evaluates to the task flow ID at runtime. When you drop a bounded task flow onto a JSF page to create an ADF dynamic region, JDeveloper adds an af:regiontag to the page. The af:regiontag contains a reference to a task flow binding. The sample of the metadata that JDeveloper adds to the JSF page is shown below: Requirement: I have a dynamicRegionDemo.jspx page. On that page I will have two sections: - left section where we will have three af:button named as Show view1.jsff, Show view2.jsff, and Show view3.jsff. - right section which will have display the dynamicRegion based on the af:button clicked. Solution: For solution to the above requirement follow the steps as shown below Step 1: Create an Oracle ADF Fusion Web.Name the application as dynamicRegionDemo. Step 2: Create three bounded task flows: btf1, btf2, and btf3. Open btf1 and drag and drop view activity form the component palette on the btf1. Name the view activity as view1. Double click on the view1 view activity to create the view1.jsff. Inside view1.jsff drag and drop af:outputText and set the value as value="view1.jsff". Open btf2 and drag and drop view activity form the component palette on the btf2. Name the view activity as view2. Double click on the view2 view activity to create the view2.jsff. Inside view2.jsff drag and drop af:outputText and set the value as value="view2.jsff". Open btf3 and drag and drop view activity form the component palette on the btf3. Name the view activity as view3. Double click on the view3view activity to create the view3.jsff. Inside view3.jsff drag and drop af:outputText and set the value as value="view3.jsff". Step 3: Create dynamicRegionDemo.jspx page. Drag and drop af:panelSplitter. Set splitterPosition="100". The af:panelSplitter will have two f:facet named as first and second. Inside the first facet drag and drop af:panelGroupLayout and set layout="vertical". Drag and drop three af:button inside af:panelGroupLayout and named the af:button as "Show view1.jsff", "Show view2.jsff", and "Show view3.jsff". Step 4: Create MyBean.java class having pageFlowScope. In MyBean.java class create private String currentTaskFlow = "btf1"; and also generate the accessors of currentTaskFlow as shown below: Step 5: Inside the first button that is drag and drop af:setPropertyListener. When we drag and drop af:setPropertyListener from the component palette we will get the below popup: Click on the icon beside To and we will get the below popup where we will set the expression as #{pageFlowScope.MyBean.currentTaskFlow} Set From as btf1 and Type as action and Click OK. Set the af:setPropertyListener for the other "Show view2.jsff" af:button as to= "#{pageFlowScope.MyBean.currentTaskFlow}" from=“btf2“ and type=“action“. Also set the af:setPropertyListener for the other "Show view3.jsff" af:button as to="#{pageFlowScope.MyBean.currentTaskFlow}" from="btf3" and type="action" Step 6: Drag and drop btf1.xml inside the second facet as a Dynamic Region as shown below: When we click on Dynamic Region we will get the below popoup where we will select Managed Bean as MyBean and Click on OK. Then we will get the below popup where we will simply click OK Thus the corressponding code gets created in MyBean.java. By default String taskFlowId and its accessors get created. Now we will change the name of the String taskFlowId to view1TaskFlowId. This is just for simplification purpose. Also we will make the changes for the accessors as well as shown below: Now we will go to the getDynamicTaskFlowId method and modify the code as shown below: Similarly drag and drop the othetr two bounded task flows that is btf2.xml and btf3.xml as a Dynamic Region as shown below. We can see that it it throwing error. Reason is we have have only one Dynamic Region not three. So I will comment the two of the dynamiicRegions: dynamicRegion2 and dynamicRegion3. Now change the String taskFlowId1 and String taskFlowId and its accessors also. Step 7: Thus the complete MyBean.java code is shown below: package com.susanto; import java.io.Serializable; import oracle.adf.controller.TaskFlowId; public class MyBean implements Serializable { private String currentTaskFlow = "btf1"; private String view1TaskFlowId = "/BTF/btf1.xml#btf1"; private String view2TaskFlowId = "/BTF/btf2.xml#btf2"; private String view3TaskFlowId = "/BTF/btf3.xml#btf3"; public MyBean() { } public TaskFlowId getDynamicTaskFlowId() { if (this.getCurrentTaskFlow().equalsIgnoreCase("btf1")) { return TaskFlowId.parse(view1TaskFlowId); } else if (this.getCurrentTaskFlow().equalsIgnoreCase("btf2")) { return TaskFlowId.parse(view2TaskFlowId); } else if (this.getCurrentTaskFlow().equalsIgnoreCase("btf3")) { return TaskFlowId.parse(view3TaskFlowId); } else return TaskFlowId.parse(view1TaskFlowId); } public void setDynamicTaskFlowId(String taskFlowId) { this.view1TaskFlowId = taskFlowId; } public void setCurrentTaskFlow(String currentTaskFlow) { this.currentTaskFlow = currentTaskFlow; } public String getCurrentTaskFlow() { return currentTaskFlow; } public TaskFlowId getDynamicTaskFlowId1() { return TaskFlowId.parse(view2TaskFlowId); } public void setDynamicTaskFlowId1(String taskFlowId) { this.view2TaskFlowId = taskFlowId; } public TaskFlowId getDynamicTaskFlowId2() { return TaskFlowId.parse(view3TaskFlowId); } public void setDynamicTaskFlowId2(String taskFlowId) { this.view3TaskFlowId = taskFlowId; } } Step 8: Thus the complete dynamicRegion.jspx code is shown below: Step 9: Save all and run the application. Thus the ran application is shown below: Step 9: Save all and run the application. Thus the ran application is shown below: Click on the Show view2.jsff button then view1.jsff gets changed to view2.jsff. Click on the Show view3.jsff button then view2.jsff gets changed to view3.jsff. Hence, the solution to our requirement. Thanks & Regards, Susanto Paul
http://susantotech.blogspot.in/2016/02/dynamic-region-in-oracle-adf.html
CC-MAIN-2018-13
refinedweb
979
52.87
Home » Support » Index of All Documentation » How-Tos » How-Tos for Modeling, Rendering, and Compositing Systems » Using Wing IDE with Source Filmmaker Wing IDE is an integrated development environment that can be used to develop, test, and debug Python code written for Source Filmmaker (SFM), a movie-making tool built by Valve using the Source game engine. Wing can debug Python code that's saved in a file, but not code entered in the Script Editor window. As of version 0.9.8.5 (released May 2014), this includes scripts run from the main menu. In all versions, code in imported modules may be debugged. When debugging Python code running under SFM, the debug process is initiated from outside of Wing IDE, and must connect to the IDE. This is done with wingdbstub, as described in in the Debugging Externally Launched Code section of the manual. Because of how SFM sets up the interpreter, you must set kEmbedded=1 in your copy of wingdbstub.py. As of May 2014, SFM comes with wingdbstub.py in the site-packages directory in its Python installation. If an older version of SFM is being used or if Wing IDE is installed into a nonstandard directory, copy wingdbstub.py from your Wing IDE install directory to the site-packages directory. The default location of the site-packages directory is: <STEAM>\steamapps\common\SourceFilmmaker\game\sdktools\python\2.7\win32\Lib\site-packages Before debugging, click on the bug icon in lower left of Wing's window and make sure that Accept Debug Connections is checked. After that, you should be able to reach breakpoints by causing the scripts to be invoked from SFM. To start debugging and ensure there's a connection from the SFM script being debugged to Wing, execute the following before any other code executes: import wingdbstub wingdbstub.Ensure() To use the python executable found in the SFM application directory to run Wing's Python Shell tool and to debug standalone Python scripts, enter the full path of the python.exe file in the Python Executable field of the Project Properties dialog. Related Documents Wing IDE provides many other options and tools. For more information: - Wing IDE Reference Manual, which describes Wing IDE in detail. - Wing IDE Quickstart Guide which contains additional basic information about getting started with Wing IDE. - Wing IDE Tutorial which provides a tour of Wing IDE's feature set.
http://www.wingware.com/doc/howtos/sfm
CC-MAIN-2015-32
refinedweb
402
62.88
Finding the volume of a unit cell at a fixed pressure Posted June 12, 2013 at 04:17 PM | categories: uncategorized | tags: | View Comments A typical unit cell optimization in DFT is performed by minimizing the total energy with respect to variations in the unit cell parameters and atomic positions. In this approach, a pressure of 0 GPa is implied, as well as a temperature of 0K. For non-zero pressures, the volume that minimizes the total energy is not the same as the volume at P=0. Let \(x\) be the unit cell parameters that can be varied. For P ≠ 0, and T = 0, we have the following \(G(x; p) = E(x) + p V(x)\) and we need to minimize this function to find the groundstate volume. We will do this for fcc Cu at 5 GPa of pressure. We will assume there is only one degree of freedom in the unit cell, the lattice constant. First we get the \(E(x)\) function, and then add the analytical correction. from jasp import * from ase import Atom, Atoms from ase.utils.eos import EquationOfState LC = [3.5, 3.55, 3.6, 3.65, 3.7, 3.75] volumes, energies = [], [] ready = True P = 5.0 / 160.2176487 # pressure in eV/ang**3 for a in LC: atoms = Atoms([Atom('Cu',(0, 0, 0))], cell=0.5 * a*np.array([[1.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0]])) with jasp('../bulk/Cu-{0}'.format(a), xc='PBE', encut=350, kpts=(8,8,8), atoms=atoms) as calc: try: e = atoms.get_potential_energy() energies.append(e) volumes.append(atoms.get_volume()) except (VaspSubmitted, VaspQueued): ready = False if not ready: import sys; sys.exit() import numpy as np energies = np.array(energies) volumes = np.array(volumes) eos = EquationOfState(volumes, energies) v0, e0, B = eos.fit() print 'V0 at 0 GPa = {0:1.2f} ang^3'.format(v0) eos5 = EquationOfState(volumes, energies + P * volumes) v0_5, e0, B = eos5.fit() print 'V0 at 5 GPa = {0:1.2f} ang^3'.format(v0_5) V0 at 0 GPa = 12.02 ang^3 V0 at 5 GPa = 11.62 ang^3 You can see here that apply pressure decreases the equilibrium volume, and increases the total energy. Copyright (C) 2013 by John Kitchin. See the License for information about copying.
http://kitchingroup.cheme.cmu.edu/blog/2013/06/12/Finding-the-volume-of-a-unit-cell-at-a-fixed-pressure/
CC-MAIN-2018-30
refinedweb
390
67.65
Coffeehouse Thread8 posts Forum Read Only This forum has been made read only by the site admins. No new threads or comments can be added. how to WPF in Windows.Forms with .NET 3.0 RC1 Back to Forum: Coffeehouse Conversation locked This conversation has been locked by the site admins. No new comments can be made. This is fun+cool, daddy-o. Start experimenting WPF on XP: 0) Download the .NET 3.0 RC1 and SDK and install them. Get them from here: 1) Add these References to projects you want to host WPF controls: PreesentationCore PresentationFramework WindowsBase WindowsFormsIntegration 2) Add these using statements to your Form: using System.Windows.Forms.Integration; using System.Windows.Controls; 3) To avoid ambiguity, explicitly state namespaces for controls like 'Button' and 'ListBox': System.Windows.Forms.Button // .NET 2.0 System.Windows.Controls.Button // .NET 3.0 4) Place two Panels on your Form from the ToolBox. 5) Put this code in your Form's OnLoad event: ElementHost hostListBox = new ElementHost(); System.Windows.Controls.ListBox wpfListBox = new System.Windows.Controls.ListBox(); for (int i = 0; i < 10; i++) wpfListBox.Items.Add("Item " + i.ToString()); hostListBox.Dock = DockStyle.Fill; hostListBox.Child = wpfListBox; ElementHost hostButton = new ElementHost(); System.Windows.Controls.Button wpfButton = new System.Windows.Controls.Button(); wpfButton.Content = "Avalon Button"; hostButton.Dock = DockStyle.Fill; hostButton.Child = wpfButton; this.panel1.Controls.Add(hostListBox); this.panel2.Controls.Add(hostButton); Or another way is: using N2 = System.Windows.Forms; using N3 = System.Windows.Controls; N2.Button b2 = ... N3.Button b3 = ... jfoscoding just posted a set of articles about WPF from a Windows Forms perspective. Check out this other thread on Channel 9 with a list of some resources as well... Thanks, Rob Relyea Program Manager, WPF Team Is there a way to instantiate .NET 3.0 RC1 WPF items from a .NET 1.1 Winform? Perhaps something like this would be clearer in code: using Forms = System.Windows.Forms; using Wpf = System.Windows.Controls; Not within the same process. WPF is built on CLR v2 and therefore isn't compatibile with CLR v1.1. Thanks, Rob There is a way... or at least I expect that there is as I've come up with a little hack to allow the use of 2.0 classes within an 1.1 app and it should be possible to also have it apply to 3.0... one of these days I'll finish the write up on it. See, I'm locked into a 1.1 form. But, the box has the 2.0 and 3.0 Framework on it, so I"m wondering if there isn't a Hack for this. I don't need it on a production machine, only for a demonstration.
https://channel9.msdn.com/Forums/Coffeehouse/231600-how-to-WPF-in-WindowsForms-with-NET-30-RC1
CC-MAIN-2017-17
refinedweb
455
61.63
But I'm thinking I may want to read that binary file, and put the contacts into a combo box for the user to select who they would like to call. I KIND OF know how this would work, but I want to double check so I don't waste 2 days figuring this out. 1. I have to read the file in, and parse each field to a new String array 2. I have to use the String array to populate the combo box 3. Display the combo box (JDialog?), and let the user select a contact to call. Does that sound right? Any advice? Here is the code that creates my Contacts file: import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class Contacts { public static void main(String[] args) { Contacts fileIO = new Contacts(); String lName[] = new String[3]; String fName[] = new String[3]; String phone[] = new String[3]; lName[0] = "Who"; lName[1] = "Potter"; lName[2] = "Hobbit"; lName[3] = "The Gray"; fName[0] = "Doctor"; fName[1] = "Harry"; fName[2] = "Frodo"; fName[3] = "Gandolf"; phone[0] = "(770) 335 2536"; phone[1] = "(842) 589 1111"; phone[2] = "(910) 963 2201"; phone[3] = "(770) 457 1625"; for(int i = 0; i<3; i++) { fileIO.Write(lName[i], fName[i], phone[i]); } }//END MAIN public void Write(String lName, String fName, String phone) { DataOutputStream output; output = null; File fileOut = new File("myContacts.data"); try { output = new DataOutputStream(new FileOutputStream(fileOut)); } catch(IOException i) {System.out.println(i);} try{ //try for write output.writeUTF("Last Name: "); output.writeUTF(lName); output.writeUTF("First Name: "); output.writeUTF(fName); output.writeUTF("Phone: "); output.writeUTF(phone); }catch (IOException i) {System.out.println("error in write");} try{ //try for close output.close(); }catch (IOException i) {System.out.println("error in close");} } }//END CONTACTS This post has been edited by synlight: 03 August 2012 - 11:29 AM
http://www.dreamincode.net/forums/topic/287821-binary-file-to-combobox/page__p__1677755
CC-MAIN-2016-07
refinedweb
317
76.11
There are some amazing math artworks on Wolfram Alpha. I was captivated by parametric equations that draw the faces of well known people and all using a few Sin functions. How is this achieved? It seems like a lot of work to go to if the curves are constructed by manual trial and error. The good news is that they are not - we show you how. First we need to look at what people have produced. If you go to Wolfram Alpha and search for "person curve" you will discover that are more than 140 examples of these mathematical portraits. A popular and fairly typical one is of Albert Einstein: What you are looking at is an x, y plot of a pair of functions. If you look at the Equations window below the plot you will see that these are no simple functions: Someone spent days or months handcrafting equations that produce the portraits in mathematical form - or did they? If you are going to produce a mathematical equation then presumably you know some math and math can always help you eliminate tedious work - unless, that is, you are still at the stage of confusing math with arithmetic. There is a mathematical procedure for producing these equations and it isn't that difficult, even though it does involve some reasonably advanced ideas. Let's find out how it all works by way of first a simple illustration using Mathematica and then an equivalent Python program. First what is a parametric equation? Standard graphs simply plot one value of y for each value of x and clearly this is not what is happening here. To create graphs that have multiple values of y for each value of x you have to do things slightly differently and this is where parametric functions come in. A pair of parametric functions give you a value fo x and a value of y for each value of their parameter. That is x=f(t) and y=g(t) To create a plot all you have to do is take different values of t and plot the resulting x and y values. For example in Mathematica you can write: f[t_] := Sin[t]g[t_] := Cos[t]ParametricPlot[{f[t], g[t]}, {t, 0, 2*Pi}] And a plot will be drawn of all the x,y pairs for t from 0 to 2*Pi and the result is a circle (allowing for distortion due to the aspect ratio): You can create the same plot in Python as long as you have MatPlotLib, Numpy and/or SciPy installed. import numpy as npimport matplotlib.pyplot as pltt = np.arange(0,2*np.pi, 0.1);plt.plot(np.sin(t), np.cos(t))plt.show() import numpy as npimport matplotlib.pyplot as plt t = np.arange(0,2*np.pi, 0.1);plt.plot(np.sin(t), np.cos(t))plt.show() If you vary the mix of trigonometric functions you can create closed curves with complicated shapes. For example: So our problem now is to work out a combination of Sin functions of different amplitudes and frequencies to change the complex but messy curve above into something that looks like Einstein. This is not going to be easy.
http://i-programmer.info/projects/119-graphics-and-games/5735-how-to-draw-einsteins-face-parametrically.html
CC-MAIN-2014-15
refinedweb
543
68.4
mlab 1.1.2 Mlab is a high-level python to Matlab bridge that lets Matlab look like a normal python library This python library is based on the work of original mlabwrap project and Dani Valevski (from Dana Pe'er's lab): Primer Quick installation: pip install mlab Start working with the library by picking a MATLAB release that you have locally installed: from mlab.releases import latest_release from matlab import matlabroot print matlabroot() where latest_release is a MlabWrap instance, matlabroot is wrapper around MATLAB function. Please note that matlab module is dynamically created instance, which is in this case referencing latest_release object. MATLAB installation discovery mechanism is implemented by mlab.releases module in such a way, that you have to specify the release version you want to use first, by importing it. Only then you can import from matlab module: from mlab.releases import R2010b from matlab import matlabroot Also see mlab.releases.get_available_releases(). Contents Primer Description Related News License Download Installation Linux Windows Documentation Tutorial Comparison to other existing modules What's Missing? Implementation Notes Troubleshooting Strange hangs under Matlab R2008a matlab not in path "Can't open engine" "`GLIBCXX_3.4.9' not found" on importing mlab (or similar) Old Matlab version OS X Notes on running Windows Function Handles and callbacks into python Directly manipulating variables in Matlab space Support and Feedback Credits Description Mlabwrap is a high-level python to Matlab bridge that lets Matlab look like a normal python library. Thanks for your terrific work on this very-useful Python tool! George A. Blaha, Senior Systems Engineer, Raytheon Integrated Defense Systems mlab is a repackaging effort to make things up-to-date. Related Thereis is a copy of mlabwrap v1.1-pre () patched as described here: with a patch fixing the error: mlabraw.cpp:225: *error*: invalid conversion from const mwSize* to const int* Also note that in Ubuntu you need to sudo apt-get install csh For details see News 2013-07-26 1.1.1 Repacking a library as mlab project. Including code for Windows (matlabraw.cpp is off for now)..) installation is now easier, in particularly LD_LIBRARY_PATH no longer needs to be set and some quoting issues with the matlab call during installation have been addressed. sparse Matlab matrices are now handled correctly (mlab.sparse([0,0,0,0]) will now return a proxy for a sparse double matrix, rather than incorrectly treat at as plain double array and return junk or crash). replaced the (optional) use of the outdated netcdf package for the unit-tests with homegrown matlab helper class. several bugs squashed (length of mlabraw.eval'ed strings is checked, better error-messages etc.) and some small documentation improvements and quite a few code clean-ups. Many thanks to Iain Murray at Toronto and Nicolas Pinto at MIT for letting themselves be roped into helping me test my stupidly broken release candidates. License mlab (and mlabwrap) is under MIT license, see LICENSE.txt. mlabraw is under a BSD-style license, see the mlabraw.cpp. Download <http: github. Installation mlab should work with python>=2.7 (downto python 2.2, with minor coaxing) and either numpy (recommended) or Numeric (obsolete) installed and Matlab 6, 6.5, 7.x and 8.x under Linux, OS X and Windows (see OS X) on 32- or 64-bit machines. Linux If you're lucky (linux, Matlab binary in PATH): python setup.py install (As usual, if you want to install just in your homedir add --prefix=$HOME; and make sure your PYTHONPATH is set accordingly.) If things do go awry, see Troubleshooting. Windows Assuming you have python 2.7.5 (e.g. C:Python27) and setuptools ("easy_install.exe") installed and on your PATH. 1) Download and install numpy package. You can use packages provided by Christoph Gohlke: Also see official SciPy website for latest status, it might that: easy_install.exe numpy would do the trick. You would also need The PyWin32 module by Mark Hammond: <string>:172: (WARNING/2) Literal block expected; none found. <string>:170: (INFO/1) Enumerated list start value not ordinal-1: "2" (ordinal 2) easy_install.exe pywin32 also see Windows in Troubleshooting. Documentation for lazy people >>> from mlab.releases import latest_release as matlab >>> matlab.plot([1,2,3],'-o') ugly-plot a slightly prettier example >>> from mlab.releases import latest_release as matlab >>> from numpy import * >>> xx = arange(-2*pi, 2*pi, 0.2) >>> mlab.surf(subtract.outer(sin(xx),cos(xx))) surface-plot for a complete description: Just run pydoc mlab. for people who like tutorials: see below Tutorial to calculate the singular value decomposition of a matrix. So first you import the mlab pseudo-module and Numeric: >>> from mlab__';<br=""]]) Comparison to other existing modules To get a vague impression just how high-level all this, consider attempting to do something similar to the first example with pymat (upon which the underlying mlabraw interface to Matlab. What's Missing? Handling of as arrays of (array) rank 3 or more as well as non-double/complex arrays (currently everything is converted to double/complex for passing to Matlab and passing non-double/complex from Matlab is not not supported). Both should be reasonably easy to implement, but not that many people have asked for it and I haven't got around to it yet. Better support for cells. Thread-safety. If you think there's a need please let me know (on the StackOverflow tagged query); at the moment you can /probably/ get away with using one seperate MlabWrap object per thread without implementing your own locking, but even that hasn't been tested. Implementation Notes. Troubleshooting Strange hangs under Matlab R2008a It looks like this particular version of matlab might be broken (I was able to reproduced the problem with just a stripped down engdemo.c under 64-bit linux). R2008b is reported to be working correctly (as are several earlier versions). matlab not in path should be called). "Can't open engine". "`GLIBCXX_3.4.9' not found" on importing mlab (or similar) As above, first try to see if you can get engdemo.c to work, because as long as even the examples that come with Matlab don't compile, chances of mlabwrap compiling are rather slim. On the plus-side if the problem isn't mlabwrap specific, The Mathworks and/or Matlab-specific support forums should be able to help. Old Matlab version). OS X Josh Marshall tried it under OS X and sent me the following notes (thanks!). Notes on running" Windows <string>:526: (INFO/1) Duplicate implicit target name: "windows". Function Handles and callbacks into python)). Directly manipulating variables in Matlab space In certain (rare!) certain cases it might be necessary to directly access or set a global variable in matlab. In these cases you can use mlab._get('SOME_VAR') and mlab._set('SOME_VAR', somevalue). Support and Feedback Post your questions directly on Stack overflow with tags matlab, mlab and python Credits Alejandro Weinstein for patches of 1.1pre Alexander Schmolck and Vivek Rathod for mlabwrap:. - Downloads (All Versions): - 0 downloads in the last day - 17 downloads in the last week - 294 downloads in the last month - Author: Yauhen Yakimovich - Download URL: - License: MIT - Package Index Owner: yyakimovich - DOAP record: mlab-1.1.2.xml
https://pypi.python.org/pypi/mlab/1.1.2
CC-MAIN-2016-18
refinedweb
1,211
56.86
IO in Files – Examples and explanation of fgets, fputs, fprintf, fscanf, fread, fwrite In the previous tutorial, we saw how a user can store a number of characters in a file using the function fputc() along with some other basic operations on file. Now, If we want to store a complete string at one go what should we do? Or what if we want to write numbers in the file or a combination of numbers and characters? Or write a record in a file using structures? Using fputc() will not be very feasible. So we are now going to see other file library functions that allow us to solve these problems. String I/O in Files Using a while loop and the function fputc() to store a string or a character array in a file will make the program more complex and a bit inefficient as well. Therefore, to avoid these we have another function fputs() which directly copies the whole string to the file without the use of any loop.Here is the syntax of the fputs() function: fputs (string_variable,file_pointer); where the file pointer points to the file where the string is to be added. Similarly, when reading a String from a file we can simply use the function fgets() to read it from the file instead of using the while loop to retrieve each character from the file one by one.Here is the syntax of the fgets() function: fgets(string_name, length of the string, file pointer); Unlike the fputs() function the fgets() function takes three arguments: the name of the variable that will store the string, the length of the string and the file pointer which points to the file from where we have to read the data. The Program below copies the string in file Doc1.txt to another file Doc2.txt using the functions fgets() and fputs(): #include <stdio.h> int main() { FILE *fp,*fw;//file pointers for the respective read and write mode. char s[30]; fp=fopen("E://Doc1.txt","r");//The file that contains the String fw=fopen("E://Doc2.txt","w");//The file from which the string is being copied /*while runs until it gets NULL*/ while(fgets(s,30,fp)!=NULL) { //reading the string from the file Doc1.txt fputs(s,fw);//copying to the file Doc2.txt printf("%s",s); } fclose(fp); fclose(fw); return 0; } Output:- Codingeek..!! Hello people...!! I/O of Records in Files using Structures In the previous section, we have been dealing with string data only. What if we have a record which contains string data, number data as well as float data? We have already seen that we can easily handle records using structures. Now, the problem arises as to how we can add the numeric data to the file without worrying about the type conversions? This problem can be easily solved using the function fprintf(). fprintf() is very similar to the function printf() and it allows the user to write any type of data into.the file. The only difference being the file pointer present in the arguments. Similarly, to read any type of data from the file we can use the function fscanf(). fscanf() is similar to scanf() with the only difference being the file pointer present in the arguments. Here is a program that reads the records from one file Doc1.txt and copies it to another file Doc2.txt: #include <stdio.h> #include <stdlib.h> int main() { FILE *fp,*fw; /*creating a structure to store the particulars of the students from the file Doc1.txt*/ struct student { char name[20]; int id; float marks; }; struct student s; fp=fopen("E://Doc1.txt","r");//The file from which data is copied fw=fopen("E://Doc2.txt","w");//the new file into which the data is copied /*copying the student record from Doc1.txt to Doc2.txt. The file runs until end of file is reached*/ while(fscanf(fp,"%s%d%f",&s.name,&s.id,&s.marks)!=EOF) { fprintf(fw,"%s %d %f",s.name,s.id,s.marks); fprintf(fw,"\n");//To add new line after every record that is read from the File } fclose(fp); fclose(fw); return 0; } The Output is shown in the following figure: Using fwrite() and fread() to read and write data in files Now, in case we have a lot of data elements or fields in the structure then writing the data or reading the data using the function fprintf() or fscanf() won’t be efficient. Hence we have another function fwrite() to write the structure data into the file and fread() to read the structure data from the file. The function fwrite() takes four arguments, i.e., - The address of the structure, - The size of the structure in bytes, - The number of structure that we want to write to the file at a time and - The file pointer. The program below takes student details from the user and copies it to the file using the function fwrite(). #include <stdio.h> #include <stdlib.h> int main() { FILE *fw; //adding three records to the file. It can be any desired value or can be dependent on user input. //It is hard coded only for the sake of simplicity, in real scenarios these are not hardcoded values. int count=3; /*creating a structure to store the particulars of the students from the file Doc1.txt*/ struct student { char name[20]; int id; int age; float marks; }; struct student s; fw=fopen("E://Doc2.dat","w");//the new file into which the data is copied while(count!=0) { printf("Enter the name,id,age and marks of a student:\n"); scanf("%s %d %d %f",&s.name,&s.id,&s.age,&s.marks); fwrite(&s,sizeof(s),1,fw);//writes the data stored in the function to the file fflush(stdin);//to flush out the data remaining in the buffer count--; } fclose(fw); return 0; } The function fread() takes the same number of arguments,i.e., the address of the structure, the size of the structure, the number of structures whose data is to be read and the file pointer. The program below reads the data that we entered using the fwrite() function from Doc2.dat and prints it: #include <stdio.h> #include <stdlib.h> int main() { FILE *fp; /*creating a structure to store the particulars of the students from the file Doc1.txt*/ struct student { char name[20]; int id; int age; float marks; }; struct student s; fp=fopen("E://Doc2.dat","rb");//the new file from which data is read if(fp==NULL) { printf("Cannot open file"); exit(1); } /*reading the data from the file using fread()*/ while(fread(&s,sizeof(s),1,fp)==1) { printf("%s %d %d %f ",&s.name,&s.id,&s.age,&s.marks); printf("\n"); } fclose(fp); return 0; } Library function fflush() In the code, we come across a new function called fflush(stdin). This function flushes out all the data that is present in the buffer to the disk. We use this function because of the ambiguity of the scanf() function which stores the enter or new line data in the buffer only unless the file ends. stdin stands for standard input device or the keyboard in this context. Note: Also, we see that the file that we created is not a text file but are actually .dat files. The reason being the fact that the text file would occupy more bytes because the characters in a text file are stored in the form of a string. And if we open this file Doc.dat using notepad we will see unidentified symbols. So that’s all for this tutorial. Hope this helps and you like the tutorial. Do ask for any queries in the comment box and provide your valuable feedback. Do come back for more because learning paves way for a better understanding. Keep Coding!! Happy Coding!! 🙂
https://www.codingeek.com/tutorials/c-programming/inputoutput-in-files/
CC-MAIN-2019-30
refinedweb
1,320
72.46
A configuration file(s) management library Project description Table of contents Overview kon is a very simple configuration file(s) management system that parses one or more configuration files in a path and provides an object tree that can be accessed directly. It also attempts to parse the data as concrete types so that you don’t have to explicitly get specific types, only for INI files. This does introduce some constraints and deviations from default implementations in python, but the convenience is generally worth it. Moreover this behavior can be overridden. kon currently handles only INI and JSON files. Installation Install the extension using pip: $ pip install kon or easy_install: $ easy_install kon Usage Basic Usage You can instantiate a Konfig object by calling its constructor: from kon import Konfig cfg = Konfig('/path/to/folder/or/ini-file') # this can also accept options for loading by handlers cfg.load() The load method will try to get an appropriate file handler based on the filename extension. If none exists, it will skip that file. The file handlers are instantiated with any default values you may want to provide the configuration. For each file handler it then calls the instance’s load method. This method can accept handler specific loading options. Currently supported handlers and their behaviors are documented below. If you want to specify default arguments, you can pass them in as keywords arguments to the constructor and they are passed through to the file handlers used to load the files. from kon import Konfig cfg = Konfig('/path/to/folder/or/ini-file', a=1, b=2.2, c=False) cfg.load() Load Behavior The load method does a couple of things. - It will walk the directory tree starting from the root directory you provide in the constructor call and create objects per directory as it goes along. - Once it encounters a file, it will try to get a file handler for that type of file. - If it cannot get a file handler, the file will be skipped. - If it can get the file handler, it will instantiate it, pass it in the defaults it got and then call it’s load method passing in any parameters it got. For e.g. if you have a directory tree like the following: kon ├── a.ini ├── b │ ├── c.ini │ ├── d.json │ ├── e │ │ └── e.ini │ ├── g.json │ └── h.ini ├── i.ini ├── j.ini └── k.ini The corresponding object tree created by load before calling the handlers load will be exactly like the tree above sans the filename extension. In the event that you have a folder and a file by the same prefix, for e.g.: kon ├── a.ini └── a.ini └── c.ini it will result in a single object kon.a with merged sub-children. JSONFileHandler This handler parses JSON files that it finds in the path specified or an individual file if it is so specified. Internally it delegates to the default python json library. Options - preserve_case - If set to false normalizes the key names to be lower case. By default the json loads function preserves case. This is the opposite of what happens with INIFileHandler. - encoding - Passthrough option for json.loads INIFileHandler This handler parses INI files that it finds in the path specified or an individual file if it is so specified. Internally it uses SafeConfigParser to load and parse the files. The individual sections, options and values are processed again. Options - preserve_case - If set to true preserves the case of the option names. Sections are still case-insensitive. By default SafeConfigParser normalizes all option names to lower case. This will prevent that. - dict_type - Passthrough option for SafeConfigParser, see below - allow_no_value - Passthrough option for SafeConfigParser, see below Customizing SafeConfigParser If you want to customize the way the internal SafeConfigParser works you can use the arguments as specified in the RawConfigParser constructor documentation and pass them to the load method call on a Konfig instance. Warning Do not pass in the defaults argument as that will be ignored. The defaults that are sent to the parser should be provided as keyword arguments to the constructor. For example: cfg = Konfig('/path/to/folder/or/ini-file') cfg.load(dict_type=OrderedDict, allow_no_value=True) Implementation Details Konfig uses SafeConfigParser to load the INI file. Consequently you get the built-in parsing and interpolation capabilities of the parser. Because SafeConfigParser does not automatically coerce the values to an appropriate type, kon will try to do it’s best to do some for you. The following cast attempts are made in order of precedence: - int - float - boolean - list, dict or tuple (using ast.literal_eval) Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/kon/
CC-MAIN-2018-22
refinedweb
795
56.45
Deploy! Note The following chapter can be sometimes a bit hard to get through. Persist and finish it; deployment is an important part of the website development process. This chapter is placed in the middle of the tutorial so that your mentor can help with the slightly trickier process of getting your website online. This means you can still finish the tutorial on your own if you run out of time. server providers available on the internet. We will use one that has a relatively simple deployment process: PythonAnywhere. PythonAnywhere is free for small applications that don't have too many visitors so it'll definitely be enough for you now. The other external service we'll be using is GitHub, which is a code hosting service. There are others out there, but almost all programmers have a GitHub account these days, and now so will you! These three places will be important to you. Your local computer will be the place where you do development and testing. When you're happy with the changes, you will place a copy of your program on GitHub. Your website will be on PythonAnywhere and you will update it by getting a new copy of your code from GitHub. Git Note If you already did the Installation steps, there's no need to do this again – you can skip to the next section and start creating your Git repository. Starting our Git repository Git tracks changes to a particular set of files in what's called a code repository (or "repo" for short). Let's start one for our project. Open up your console and run these commands, in the djangogirls directory: Note Check your current working directory with a pwd(Mac OS X/Linux) or cd(Windows) command before initializing the repository. You should be in the djangogirlsfolder. command-line $ git init Initialized empty Git repository in ~/djangogirls/.git/ $ git config --global user.name "Your Name" $ git config --global user.email you@example.com Initializing the git repository is something we need to do only once per project (and you won't have to re-enter the username and email ever again). Git will track changes to all the files and folders in this directory, but there are some files we want it to ignore. We do this by creating a file called .gitignore in the base directory. Open up your editor and create a new file with the following contents: .gitignore *.pyc *~ __pycache__ myvenv db.sqlite3 /static .DS_Store And save it as .gitignore in the "djangogirls" folder. Note The dot at the beginning of the file name is important! If you're having any difficulty creating it (Macs don't like you to create files that begin with a dot via the Finder, for example), then use the "Save As" feature in your editor; it's bulletproof. Note One of the files you specified in your .gitignorefile is db.sqlite3. That file is your local database, where all of your posts are stored. We don't want to add this to your repository because your website on PythonAnywhere is going to be using a different database. That database could be SQLite, like your development machine, but usually you will use one called MySQL which can deal with a lot more site visitors than SQLite. Either way, by ignoring your SQLite database for the GitHub copy, it means that all of the posts you created so far are going to stay and only be available locally, but you're going to have to add them again on production. You should think of your local database as a good playground where you can test different things and not be afraid that you're going to delete your real posts from your blog. It's a good idea to use a git status command before git add or whenever you find yourself unsure of what has changed. This will help prevent any surprises from happening, such as wrong files being added or committed. The git status command returns information about any untracked/modified/staged files, the branch status, and much more. The output should be similar to the following: command-line $ git status On branch master Initial commit Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore blog/ manage.py mysite/ nothing added to commit but untracked files present (use "git add" to track) And finally we save our changes. Go to your console and run these commands: command-line $ git add --all . $ git commit -m "My Django Girls app, first commit" [...] 13 files changed, 200 insertions(+) create mode 100644 .gitignore [...] create mode 100644 mysite/wsgi.py Pushing your code to GitHub Go to GitHub.com and sign up for a new, free user account. (If you already did that in the workshop prep, that is great!) Then, create a new repository, giving it the name "my-first-blog". Leave the "initialize with a README" checkbox unchecked, leave the .gitignore option blank (we've done that manually) and leave the License as None. Note The name my-first-blogis important – you could choose something else, but it's going to occur lots of times in the instructions below, and you'd have to substitute it each time. It's probably easier to just stick with the name my-first-blog. On the next screen, you'll be shown your repo's clone URL. Choose the "HTTPS" version, copy it, and we'll paste it into the terminal shortly: Now we need to hook up the Git repository on your computer to the one up on GitHub. Type the following into your console (Replace <your-github-username> with the username you entered when you created your GitHub account, but without the angle-brackets): command-line $ git remote add origin<your-github-username>/my-first-blog.git $ git push -u origin master Enter your GitHub username and password and you should see something like this: command-line Username for '': hjwp Password for '': Counting objects: 6, done. Writing objects: 100% (6/6), 200 bytes | 0 bytes/s, done. Total 3 (delta 0), reused 0 (delta 0) To * [new branch] master -> master Branch master set up to track remote branch master from origin. Your code is now on GitHub. Go and check it out! You'll find it's in fine company – Django, the Django Girls Tutorial, and many other great open source software projects also host their code on GitHub. :) Setting up our blog on PythonAnywhere Note You might have already created a PythonAnywhere account earlier during the install steps – if so, no need to do it again.. Pulling our code down on PythonAnywhere When you've signed up for PythonAnywhere, you'll be taken to your dashboard or "Consoles" page. Choose the option to start a "Bash" console – that's the PythonAnywhere version of a console, (don't forget to use your GitHub username in place of <your-github-username>): PythonAnywhere command-line $ git clone<your-github-username>/my-first-blog.git This will pull down a copy of your code onto PythonAnywhere. Check it out by typing tree my-first-blog: PythonAnywhere command-line $ tree my-first-blog my-first-blog/ ├── blog │ ├── __init__.py │ ├── admin.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py └── mysite ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py Creating a virtualenv on PythonAnywhere Just like you did on your own computer, you can create a virtualenv on PythonAnywhere. In the Bash console, type: PythonAnywhere command-line $ cd my-first-blog $ virtualenv --python=python3.5 myvenv Running virtualenv with interpreter /usr/bin/python3.5 [...] Installing setuptools, pip...done. $ source myvenv/bin/activate (myvenv) $ pip install django~=1.10.0 Collecting django [...] Successfully installed django-1.10.4 Note The pip installstep can take a couple of minutes. Patience, patience! But if it takes more than five minutes, something is wrong. Ask your coach. Creating the database on PythonAnywhere: PythonAnywhere command-line (mvenv) $ python manage.py migrate Operations to perform: [...] Applying sessions.0001_initial... OK (mvenv) $ python manage.py createsuperuser Publishing our blog as a web app.5, and click Next to finish the wizard. Note Make sure you choose the "Manual configuration" option, not the "Django" one. We're too cool for the default PythonAnywhere Django setup. ;-) Setting the virtualenv You'll be taken to the PythonAnywhere config screen for your webapp, which is where you'll need to go whenever you want to make changes to the app on the server. . Configuring the WSGI file: <your-username>_pythonanywhere_com_wsgi.py import os import sys path = os.path.expanduser('~/my-first-blog')()) This file's job is to tell PythonAnywhere where our web app lives and what the Django settings file's name is. The StaticFilesHandler is for dealing with our CSS. This is taken care of automatically for you during local development by the runserver command. We'll find out a bit more about static files later in the tutorial, when we edit the CSS for our site. Hit Save and then go back to the Web tab. We're all done! Hit the big green Reload button and you'll be able to go view your application. You'll find a link to it at the top of the page. Debugging tips.5. There are also some general debugging tips on the PythonAnywhere wiki. And remember, your coach is here to help! You are live! The default page for your site should say "It worked!", just like it does on your local computer. Try adding /admin/ to the end of the URL, and you'll be taken to the admin site. Log in with the username and password, and you'll see you can add new Posts on the server. Once you have a few posts created, you can go back to your local setup (not PythonAnywhere). From here you should work on your local setup to make changes. This is a common workflow in web development – make changes locally, push those changes to GitHub, and pull your changes down to your live Web server. This allows you to work and experiment without breaking your live Web site. Pretty cool, huh? Give yourself a HUGE pat on the back! Server deployments are one of the trickiest parts of web development and it often takes people several days before they get them working. But you've got your site live, on the real Internet, just like that!
https://tutorial.djangogirls.org/en/deploy/
CC-MAIN-2017-34
refinedweb
1,745
65.93
Prerequisites for WCF-based code samples in Project 2013 Learn information to help you create projects in Visual Studio by using the WCF-based code samples that are included in the Project Server Interface (PSI) reference topics. Last modified: March 09, 2015), and change generic constant values to match your environment. Set up a test Project Server system. Use a test Project Server system whenever you are developing or testing. Even when your code works perfectly, interproject dependencies, reporting, or other environmental factors can cause unintended consequences. In some cases, you may have to do remote debugging on the server. You may also have to set up an event handler by installing an event handler assembly on each Project Server computer in the SharePoint farm, and then configuring the event handler for the Project Web App instance by using the Project Server Settings page in the General Application Settings of SharePoint Central Administration. Set up a development computer. You usually access the PSI through a network. The code samples are designed to be run on a client that is separate from the server, except where noted. Install the correct version of Visual Studio. Except where noted, the code samples are written in Visual C#. They can be used with Visual Studio 2010 or Visual Studio 2012. Ensure that you have the most recent service pack installed. Copy Project Server DLLs to the development computer. Copy the following assemblies from [Program Files]\Microsoft Office Servers a PSI proxy assembly and IntelliSense descriptions. Install the IntelliSense files. To use IntelliSense descriptions for classes and members in Project Server assemblies, copy the updated IntelliSense XML files from the Project 2013 change the default application namespace by changing the application properties. For example, the code sample for works with either assembly. For example, the namespace of the Resource service in the WCF-based proxy assembly and in the ASMX-based proxy assembly is SvcResource. You can, of course, change the namespace names— if you ensure that they match in the proxy assembly and in the ProjectServerServices.xml IntelliSense file. If a code sample uses a different name for a PSI\IntelliSense folder of the Project 2013 example. Local references for the code sample are listed in using statements at the top of the sample. In Solution Explorer, right-click the References folder, and then choose Add Reference. Choose Browse, and then browse to the location where you stored the Project Server DLLs that you copied previously. Choose the DLLs Project Professional 2013 client to open the project from the Project Server computer, and view the items that you want. View published projects on the Project Center page of Project Web App (). View the Queue log in Project Web App. Open the Server Settings page (choose the Settings icon in the top-right corner), and then choose My Queued Jobs under the Personal Settings section (). In the View drop-down list, you can sort by the job status. The default status is In Progress and Failed Jobs in the Past Week. Use the Server Settings page in Project Web App () to manage all queue jobs and delete or force check-in enterprise objects. You must have administrative permissions to access those links on: Enterprise Custom Fields and Lookup Tables Manage Queue Jobs Delete Enterprise Objects Force Check-in Enterprise Objects Enterprise Project Types Workflow Phases Workflow Stages Project Detail Pages Time Reporting Periods Timesheet Settings and Defaults Line Classifications Additional settings are managed by SharePoint Server 2013 for each Project Web App instance, rather than by a specific Project Web App Server Settings page. In the SharePoint Central Administration application, choose General Application Settings, choose Manage under Project Server Settings, and then choose the Project Web App instance in the drop-down list on the Server Settings page. For example, choose Server Side Event Handlers to add or delete event handlers for the selected Project Web App instance.
https://msdn.microsoft.com/en-us/library/ee872368(v=office.15).aspx
CC-MAIN-2016-44
refinedweb
653
61.87
Re: Which is simpler? (Was Re: [Suspend2-devel] Re: [ 00/10] [Suspend2] Modules support.) - From: "Rafael J. Wysocki" <rjw@xxxxxxx> - Date: Wed, 8 Feb 2006 15:23:14 +0100 Hi, On Wednesday 08 February 2006 14:23, Bodo Eggert wrote: There are some questions I have while looking at this HOWTO, which I think should be answered there: Pavel Machek <pavel@xxxxxx> wrote: Suspend-to-disk HOWTO[...] ~~~~~~~~~~~~~~~~~~~~ ./suspend /dev/<your_swap_partition> Does it need to be mounted (so it possibly gets filled and thereby unusable), or can it be a mkswapped partition? A mkswapped one will do. Actually a mounted one will do either and the data on it won't get damaged. Can it even be a swap-file? No. Probably not, unless you want to resume by ro-nojournalreplay-mounting the corresponding partition. How big does it have to be, compared to the RAM? As big + n? Bigger? BIGGER? May be smaller. You'll need at most 1/2 of your RAM size of free space on it. I'll put the answers in the howto, thanks for the hint. Greetings, Rafael - To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@xxxxxxxxxxxxxxx More majordomo info at Please read the FAQ at - Follow-Ups: - References: - Prev by Date: Re: [RFC] EXPORT_SYMBOL_GPL_FUTURE() - Next by Date: Re: The issues for agreeing on a virtualization/namespaces implementation. - Previous by thread: Re: Which is simpler? (Was Re: [Suspend2-devel] Re: [ 00/10] [Suspend2] Modules support.) - Next by thread: Re: Which is simpler? (Was Re: [Suspend2-devel] Re: [ 00/10] [Suspend2] Modules support.) - Index(es):
http://linux.derkeiler.com/Mailing-Lists/Kernel/2006-02/msg02954.html
crawl-002
refinedweb
270
66.94
cc [ flag ... ] file ... -lcurses [ library ... ] #include <curses.h> The baudrate() routine returns the output speed of the terminal. The number returned is in bits per second, for example 9600, and is an integer. With the erasechar() routine, the user's current erase character is returned.(). With the killchar() routine, the user's current line kill character is returned.() function returns a logical OR of all video attributes supported by the terminal. This information is useful when a curses program needs complete control over the appearance of the screen. The termname() routine returns the value of the environment variable TERM (truncated to 14 characters). longname() and termname() return NULL on error. Routines that return an integer return ERR upon failure and an integer value other than ERR upon successful completion. See attributes(5) for descriptions of the following attributes: curs_initscr(3CURSES), curs_outopts(3CURSES), curses(3CURSES), attributes(5) The header <curses.h> automatically includes the headers <stdio.h> and <unctrl.h>. Note that termattrs() may be a macro.
http://www.shrubbery.net/solaris9ab/SUNWaman/hman3curses/curs_termattrs.3curses.html
CC-MAIN-2015-22
refinedweb
166
59.4
#include <pqPipelineFilter.h> Definition at line 47 of file pqPipelineFilter.h. Returns the inputs ports on any proxy. Returns the required inputs ports on any proxy. This is generally same as getInputPorts() except if the property has a "hint" saying it's optional. Returns the number of input ports available on this filter. Returns the name of the input port at a given index. Returns the number of input proxies connected to given named input port. Returns the input proxies connected to the given named input port. Returns inputs connected to all input ports connections. Returns a map of input port name to the list of output ports that are set as the input to that port. Returns a pair (input, output port) at the given index on the given named input port. Get number of inputs. Definition at line 108 of file pqPipelineFilter.h. Get a list of all inputs. Definition at line 113 of file pqPipelineFilter.h. Get input at given index. Get first available input, any port, any index. Return NULL if none are available. "Replace input" is a hint given to the GUI to turn off input visibility when the filter is created. Returns if this proxy replaces input on creation. This checks the "Hints" for the proxy, if any. If a <Visibility> element is present with replace_input="0", then this method returns false, otherwise true. fired whenever an input connection changes. process some change in the input property for the proxy. Use this method to initialize the pqObject state using the underlying vtkSMProxy. This needs to be done only once, after the object has been created. Reimplemented from pqProxy. Called when a input property changes. portname is the name of the input port represented by the property.
https://kitware.github.io/paraview-docs/latest/cxx/classpqPipelineFilter.html
CC-MAIN-2022-05
refinedweb
292
69.89
This part of the "Mastering Eclipse" series takes a detailed look at Eclipse's Java editor. The editor is where developers spend a majority of their time, so understanding its advanced features can significantly improve your productivity. The Organize Imports command The Organize Imports command adds missing imports and organizes existing import declarations in your Java files. You can run this command in the current editor by using Ctrl+Shift+O. To apply the Organize Imports command to your whole project, right-click the project in the Project Explorer and select Source > Organize Imports. Suppose you used a class somewhere in your Java file, but you've forgotten to import it; Organize Imports can automatically import it for you. If the command is unsure about the class's location, a window opens with a list of options for you to choose from. For example, if you use the List class in your code, when you run the Organize Imports command, it may pop up a window asking you to choose between java.util.List and javax.swing.List because the command can't decide on its own. Organize Imports also breaks the commonly used .* style import declarations into individual imports. For example, suppose you have an import like import java.util.* in your file, and you use only the List class from that package. The Organize Imports command replaces the original import statement with import java.util.List. Pick out part of string Often, you need to concatenate a variable between two strings. Most of the time, these strings are part of a single statement, and it's easy to make the mistake of leaving out a space on either side of the strings. For example, you may end up with output like You have5seconds left, instead of You have 5 seconds left. Eclipse helps prevent you from falling into this trap: - Type your string as you would normally within your code: static String getMsg(int time) { return "You have 5 seconds left"; } - Select the portion of the string you want to replace with a variable — in this example, the numeral 5. - Press Ctrl+1 and select Pick out selected part of String. Figure 1. Select Pick out selected part of String The result is shown in Figure 2. Figure 2. Selected part of string is picked - Replace the string in the middle with your variable. Figure 3. Replace the string with your variable Now you can rest assured that you made no mistakes about the spaces. Automatically create locals You often need to call a method and assign its value to a new local variable. Eclipse makes this so easy that you'll never again assign locals the old way: - Type the call to the method: public void foo() { getMsg(3); } - Without moving your insertion marker, press Ctrl+1 and select Assign statement to a new local variable (see Figure 4). You can select Assign statement to a new field if you want to use a field instead of a local variable. Figure 4. Select Assign statement to a new local variable A new local variable of the same type as the method's return value is created for you. It's given an appropriate name, but you can change it if you'd like (see Figure 5). Press Enter to accept the name. Figure 5. You can change the variable's name Quick Outline Outline view is useful because it lets you easily jump to methods in your Java file. But this view takes up a lot of your precious on-screen real state. Quick Outline view provides all the functionality of Outline view without needing the view to occupy your screen. To activate Quick Outline view from inside your editor, press Ctrl+O. A pop-up window appears that shows an outline of your file. Figure 6. Pressing Ctrl+O brings up Quick Outline view You can navigate to any method by using your arrow keys. To jump to a method even more quickly, begin typing its name. The list begins to filter, showing you only methods that begin with the characters you're typing. Figure 7. Start typing and Outline view begins filtering Quick Open Type The Open Type window does for Package Explorer what Quick Outline does for Outline view. Press Ctrl+Shift+T from your editor. A window pops up, in which you can type the name of any class in your workspace (see Figure 8). Click OK, and that class opens instantly in the editor. No need to hunt through trees in Package Explorer to open the class you want. Figure 8. The Open Type window lets you instantly jump to any class in your workspace You can use wildcards when you type the class name to filter the list below the text box. For example, type *Exception to show all Exception classes. Breadcrumb bar The breadcrumb bar was introduced in Eclipse V3.4. It sits at the top of your editor window, just below the tabs, and provides the functionality of both the Package Explorer and Outline views (see Figure 9). If it isn't enabled, you can enable it by pressing Alt+Shift+B. Figure 9. The breadcrumb bar The breadcrumb bar points out the path of the current editor relative to the current workspace. Clicking one of the black arrows shows you the contents of the element, thus allowing you to browse your entire workspace from the bar. Figure 10. Breadcrumb bar lets you browse your workspace from the bar Quick Javadoc Are you trying to figure out what a method does? Eclipse can easily show you the Javadoc for any method. Just hover your cursor over the method and a Javadoc window appears. Figure 11. Hovering your cursor over any Java element shows related Javadoc -- in this case, the indexOf method But this functionality doesn't end there. Move your cursor inside the pop-up window, and the window becomes scrollable (see Figure 12). The buttons at the bottom let you open the Javadoc in an external window and go to the declaration of the element whose Javadoc you're viewing. Figure 12. Moving your cursor inside the pop-up turns it into a scrollable window Auto format You can use Eclipse's auto-format functionality to automatically format documents. Right-click a document in the Package Explorer and select Source > Format. You can even format your entire project by right-clicking the project instead of an individual file in Package Explorer. To configure how Eclipse formats your code: - Choose Window > Preferences. then browse to Java > Code Style > Formatter. Figure 13. Editing how Eclipse formats your documents - Create a new profile for formatting by clicking New and entering a name in the window that opens. - After you create the profile, click Edit to begin editing formatting preferences for that profile. - The Profile window that opens contains detailed settings for configuring the formatting of your source code (see Figure 14). You can configure everything from how much indentation is required for each element in the source code to how many blank lines appear between import groups. Figure 14. Eclipse lets you configure your formatting settings in detail - Click OK to close the Profile window. Click OK again to close the Preferences window. Note that the new formatting settings will apply the next time you format your source code. Save Actions Save actions are triggered when you save a document. They let you do things like format your code and organize imports automatically when you save your document. To configure save actions: - Choose Window > Preferences > Java > Editor > Save Actions to open the Preferences window. Figure 15. Configuring Save Actions in the Preferences window - Select the Perform the selected actions on save checkbox. - Select all the actions you want to be performed on save. Click Configure to see more actions. Figure 16. Clicking Configure displays more actions For example, you can select the Convert for loops to enhanced check box on the Code Style tab to convert all your forloops to Java 5-style enhanced loops every time you save your document. Save Actions can save you a lot of time. For example, you can type your code any way you want, without worrying about the formatting, and it will still be formatted perfectly automatically each time you save your document. Code folding Code folding lets you literally fold pieces of code so the editor doesn't get too cluttered. To fold a method, click the - icon on the left ruler. Figure 17. Clicking the - sign folds the code When you fold code, the - icon turns into a +, which you can click again to unfold the method. If you hover your cursor over the + sign when the method is folded, a pop-up window displays the text inside the method. Figure 18. Hovering your cursor over the + icon shows a preview of the code that has been folded Generate hashCode() and equals() Eclipse lets you automatically generate the hashCode() and equals() methods for your classes so you don't have to do it yourself. This way, you can avoid making errors while writing these methods. To generate the methods: - Choose Source > Generate hashCode() and equals(). - The window that opens asks you which fields you want to include when the hashCode()and equals()methods are called on your class. Figure 19. Select the fields on which to generate hashCode()and equals()methods - Select the fields you want and click OK. The equals()and hashcode()methods are generated for you. Overview ruler The overview ruler is embedded to the right of the editor window. It lets you instantly see any errors, warnings, or other markers that require your attention in the editor. If there are any errors in your editor, then the upper-right corner of the bar displays a red box. Figure 20. The red box in the overview ruler indicates one or more errors in the editor A yellow box, on the other hand, means there are warnings in the editor. Figure 21. Overview ruler indicating the presence of warnings in the editor Using the overview ruler, you can jump instantly to any error/warning in your editor. The ruler displays little yellow/red markings wherever an error/warning appears in your editor (see Figure 22). If you click the marking, the editor instantly jumps to the appropriate position in your code. Figure 22. The overview ruler showing two warnings and one TODO comment The overview ruler can also indicate other points of interest in your editor. For example, if you have a TODO comment, or if you perform a search, the related lines are marked in the overview ruler; clicking the markers takes you to the corresponding line. As the name suggests, the overview ruler gives you an overview of the lines of interest in your editor. You'll find it an invaluable companion as you write Java code. Conclusion This article has examined some of the advanced features of the Java editor in Eclipse. You've seen how to generate common pieces of code automatically. You also learned how to close Eclipse views and still use their functionality, thanks to shortcuts offered by Eclipse editor. The article also discussed other features of the Java editor that can significantly improve your productivity. Resources Learn - Start this series with "Mastering Eclipse V3.4, Part 1: The Eclipse IDE workbench." The series continues with "Mastering Eclipse V3.4, Part 2: The JDT." - Find more information in the Java Development User Guide in Eclipse Help. - Read the Eclipse IDE Pocket Guide. - Visit the official Eclipse FAQs. - Read Eclipse for Dummies. - Read Eclipse Distilled. -.
http://www.ibm.com/developerworks/opensource/library/os-eclipse-master3/index.html
CC-MAIN-2014-52
refinedweb
1,939
62.58
State. In charts that use C as the action language, you can call built-in MATLAB functions and access MATLAB workspace variables by using the ml namespace operator or the ml function. Because MATLAB functions are not available in a target environment, do not use the ml namespace operator and the ml function if you plan to build a code generation target. mlNamespace.matfunc(arg1, arg2,...) For example, the statement [a, b, c] = ml. passes the return values from the MATLAB function matfunc(x, y) matfunc. In these examples, x, y, and z are workspace variables and d1 and d2 are Stateflow data: a = ml.sin(ml.x) In this example, the MATLAB function sin evaluates the sine of x, which is then assigned to Stateflow data variable a. However, because x is a workspace variable, you must use the namespace operator to access it. Hence, ml.x is used instead of just x. a = ml.sin(d1) In this example, the MATLAB function sin evaluates the sine of d1, which is assigned to Stateflow data variable a. Because d1 is Stateflow data, you can access it directly. ml.x = d1*d2/ml.y The result of the expression is assigned to x. If x does not exist prior to simulation, it is automatically created in the MATLAB workspace. ml.v[5][6][7] = ml. matfunc(ml.x[1][3], ml.y[3], d1, d2, ' string') The workspace variables x and y are arrays. x[1][3] is the (1,3) element of the two-dimensional array variable x. y[3] is the third element of the one-dimensional array variable y. The last argument, ' string ', is a character vector. The return from the call to matfunc is assigned to element (5,6,7) of the workspace array, v. If v does not exist prior to simulation, it is automatically created in the MATLAB workspace. mlFunction. In these examples, x is a MATLAB workspace variable, and d1 and d2 are Stateflow data: a = ml('sin(x)') In this example, the ml function calls the MATLAB function sin to evaluate the sine of x in the MATLAB workspace. The result is then assigned to Stateflow data variable a. Because x is a workspace variable, and sin(x) is evaluated in the MATLAB workspace, you enter it directly in the argument ( evalString 'sin(x)'). a = ml('sin(%f)', d1) In this example, the MATLAB function sin evaluates the sine of d1 in the MATLAB workspace and assigns the result to Stateflow data variable a. Because d1 is Stateflow data, its value is inserted in the argument ( evalString 'sin(%f)') using the format expression %f. This means that if d1 = 1.5, the expression evaluated in the MATLAB workspace is sin(1.5). a = ml(' matfunc(%g, ''abcdefg'', x, %f)', d1, d2) In this example, the expression ' is the matfunc(%g, ''abcdefg'', x, %f)' shown in the preceding format statement. Stateflow data evalString d1 and d2 are inserted into that expression with the format specifiers %g and %f, respectively. ''abcdefg'' is a literal enclosed with two single pairs of quotation marks because it is part of the evaluation expression, which is already enclosed in single quotation marks. sfmat_44 = ml('rand(4)') In this example, a square 4-by-4 matrix of random numbers between 0 and 1 is returned and assigned to the Stateflow data sf_mat44. Stateflow data sf_mat44 must be defined as a 4-by-4 array before simulation. If its size is different, a size mismatch error is generated during run-time. mlExpressions For C charts, you can mix ml namespace operator and ml function expressions along with Stateflow data in larger expressions. The following example squares the sine and cosine of an angle in workspace variable X and adds them: during parsing of charts and during run time. Because the return values for ml expressions are not known until run time, Stateflow software must infer the size of their return values. See How Charts Infer the Return Size for ml Expressions. mlShould I Use? In most cases, the notation of the ml namespace operator is more straightforward. However, using the ml function call does offer a few advantages: Use the ml function to dynamically construct workspace variables. The following flow chart creates four new MATLAB matrices: The for loop creates four new matrix variables in the MATLAB workspace. The default transition initializes the Stateflow counter i to 0, while the transition segment between the top two junctions increments it by 1. If i is less than 5, the transition segment back to the top junction evaluates the ml function call ml('A%d = rand(%d)',i,i) for the current value of i. When i ml function with full MATLAB notation. You cannot use full MATLAB notation with the ml namespace operator, as the following example shows: ml.A = ml.magic(4) B = ml('A + A''') This example sets the workspace variable A to a magic 4-by-4 matrix using the ml namespace operator. Stateflow data B is then set to the addition of A and its transpose matrix, A', which produces a symmetric matrix. Because the ml namespace operator cannot evaluate the expression A', the ml function is used instead. However, you can call the MATLAB function transpose with the ml namespace operator in the following equivalent expression: B = ml.A + ml.transpose(ml.A) As another example, you cannot use arguments with cell arrays or subscript expressions involving colons with the ml namespace operator. However, these can be included in an ml function call. mlData. mlData Type These rules apply to Stateflow data of type ml: You can initialize ml data from the MATLAB workspace just like other data in the Stateflow hierarchy (see Initialize Data from the MATLAB Base Workspace). Any numerical scalar or array of ml data in the Stateflow hierarchy can participate in any kind of unary operation and any kind of binary operation with any other data in the hierarchy. If ml data participates in any numerical operation with other data, the size of the ml data must be inferred from the context in which it is used, just as return data from the ml namespace operator and ml function are. See How Charts Infer the Return Size for ml Expressions. You cannot define ml data with the scope Constant. This option is disabled in the Data properties dialog box and in the Model Explorer for Stateflow data of type ml. You can use ml data to build a simulation target but not to build an embeddable code generation target. If data of type ml contains is a Stateflow data of type ml, ws_num_array is a 2-by-2 MATLAB workspace array with numerical values, and ws_str_array*/ ml data cannot have a scope outside a C chart; that is, you cannot define the scope of ml data as Input from Simulink or Output to Simulink.. mlExpressions namespace operator or the ml function is a MATLAB workspace variable of any size and type (structure, cell array, character vector, and so on). An assignment in which the left-hand side is a data of type ml For example, in the expression m_x = ml., func() m_x is a Stateflow data of type ml. Input arguments of a MATLAB function For example, in the expression ml., func(m_x, ml.x, gfunc()) m_x is a Stateflow data of type ml, ml.x ml in its prototype statement If you replace the inputs in the preceding cases with non-MATLAB numeric Stateflow data, conversion to an ml type occurs.
https://au.mathworks.com/help/stateflow/ug/calling-built-in-matlab-functions-and-accessing-workspace-data.html
CC-MAIN-2020-16
refinedweb
1,260
60.85
Undefined reference to '_imp__ZN9QGLWidgetC2ERQ9QGLFormat...' Hi there, I just quit MS .NET and started with QT. I was implementing an example from QT's tutorial "hellogl" starting from the scratch. I got the error message shown above + 14 more of them, related to formats and widgets. I searched every possible place to find answer why I have got this error message but I could not find any answer. So here I am! What is causing this error? Any idea? I am very surprized that such a small code will create so many error messages. Thanks for all the suggestions and help. OS : Windows7 Regards - Olorin5800 have you added opengl module t your pro file ? I put this one in the header file : #include <QTOpenGL/QGLWidget> and the rest of the "Widget" code starts like this and foolows the example with a different name and namespace : class QtLogo; namespace VisualPresenters { class Canvas3D : public QGLWidget { Q_OBJECT public: Canvas3D(QWidget* parent = NULL); ~Canvas3D() Thanks for the response. Should I need to add more or am I missing something here? Regards. You are right! I have added QT += opengl to .pro file and it seems that this part of the problem is solved. Thank you! - Olorin5800 your welcome :D NorskQt, welcome to the qt forum! Please use the @ tag for the source code in your post. thanks. OK! Next time I will put @tag to my code snippets. Sorry! :o) First: Qt is not QT(QuickTime) Second: What do version of Qt you use? May be it was build without opengl support?
https://forum.qt.io/topic/2342/undefined-reference-to-_imp__zn9qglwidgetc2erq9qglformat
CC-MAIN-2018-05
refinedweb
257
84.68
Scout/NewAndNoteworthy/3.8 This page shows what you need to know about the new Eclipse Scout 3.8 release shipped with Eclipse Juno. Contents - 1 Release 3.8.0 - 1.1 New Runtime Features - 1.2 New SDK Features - 1.3 Bugfixes - 2 Release 3.8.1 - 3 Release 3.8.2 - 4 Migration Guidelines Release 3.8.0 New Runtime Features Scout Web UI support based on RAP With version 3.8 Scout supports building web applications in addition to the previously supported Swing and SWT desktop technologies. Two scenarios are supported: - Migrate existing Scout Desktop applications into the browser with minimal effort. - Build new Scout applications that simultaneously run in the browser and as rich applications on the desktop. This is possible because Eclipse Scout features a clean separation of the application model from the UI Layer (also see this wiki article). Benefits for the developer: The Scout developer builds the application only once. Everything can be done using existing Scout/Java/Eclipse development know how (no new framework to learn, no HTML, CSS or JavaScript to learn). Benefits to the end user: The end user of Scout applications experiences an identical look and feel for both the web and the desktop application. Outlook: The Web UI support is only the next step of the Eclipse Scout "Multi Frontend" strategy. In addition to business application on the desktop and in the web, we are also planning to support mobile devices in the near future. SVG Field as an additional UI Component The new SVG field enhances Eclipse Scout with the ability to display interactive diagrams and graphics that work on both the desktop and the web environment. Busy Handling Improvements Parts of the busy handling in the graphical ui layer was refactored in order to have a more responsive and intuitive human-computer interaction. Busy handling - as all scout parts - is split into the model part in package org.eclipse.scout.rt.client.busy and the GUI part in packages org.eclipse.scout.rt.ui.swing.ext.busy, org.eclipse.scout.rt.ui.swt.busy, org.eclipse.scout.rt.ui.rap.busy, ... Busy handling in scout is based on eclipse jobs. Whenever a sync ClientJob is running, the scout application is defined as being busy. The IBusyManagerServer supports for registering busy handlers to IClientSessions. Depending on how long jobs last, the IBusyHandler schedules a short running busy indicator or a long running busy indicator. The indicator may be blocking or cancellable or both, depending on the job being run. As a convenience a basic BusyJob can be subclassed do have basic handling. Default implementaions vary on devices: Swing shows wait cursor (for short operation) and blocks after that (long operation), showing the used a screen overlay to cancel. SWT without workbench uses BusyIndicator.showWhile to show busy state. It never shows a blocking state for long operations SWT Workbench uses BusyIndicator.showWhile to show busy state and activeWorkbenchWindow.run to block the workbench on long running operations. The developer may however choose if blocking should block all views or just the views of the affected (scout) application part. RAP/RWT RAP/RWT in the browser is different from rich client apps. On busy it shows a spinning wheel in the top section of the application, on blocking it decorates the affected views and blocks them. New NLS (i18n) concept: TextProviderServices Before version 3.8 Scout only supported internationalization and localization of applications using the Scout NLS properties files. This restriction has been removed by introducing TextProviderServices. This way the translated text retrieval is also aligned with the icon retrieval which is also managed using IconProviderServices. Using the new TextProviderServices developers can decide to store the translations in a custom container like a database or XML files. Furthermore using TextProviderServices it is very easy to overwrite any translated text in the application (also texts used in Scout itself) using the already well known service ranking. By default the existing properties files will be supported by a reference implementation of the TextProviderServices. Label Position Top Scout already provides a mechanism to control the position of the field's label. Until now it has been possible to position the label on the left side of the field (which is the default) or on the field itself. The property to control this behavior is called "LabelPosition" and has been extended for Eclipse Scout 3.8.0 to allow a positioning on top of the field. Introducing ISession In order to read session data like the userId you can use ServerSession.get().getUserId() or ClientSession.get().getUserId(). This works fine if you want to do this inside a server respectively client bundle. Due to the strict dependency rules it is not possible to access these session classes from the shared plugin, because it has no dependency to neither of them. Until now. Since the server and the client session share a lot of common attributes the ISession interface has been introduced, along with the ISessionService. If you now would like to access the userId from a shared plugin you can use following code: ISession session = SERVICES.getService(ISessionService.class).getCurrentSession(); System.out.println(session.getUserId()); But: If you can directly use the ClientSession.get() resp. ServerSession.get() you should still do so to avoid unnecessary osgi service calls. Enhancement of the Multi Frontend Support As a preparation for the future mobile support coming with 3.9.0, the multi frontend support has been enhanced. It's now possible to get information about the running frontend, on client and server side as well. This is very useful if you need to make some components dependent on a specific frontend, e.g. making fields invisible in the web client but not on the rich client. The information of the frontend is stored on the session and is called UserAgent. The UserAgent consists of a ui layer and a ui device type. With these two properties you can determine if the GUI of the current session is based on SWT, Swing or Rap and if the device is a desktop, tablet or mobile. To make these checks even more easy some utility functions have been created and are accessible with the UserAgentUtility. If you are interested in what user agents are really used, the scout session view has been extended to show this information, as you can see in the image. New SDK Features Support for Scout Web UI The SDK comes with some handy tools to support you in dealing with the new Web UI that comes with Scout 3.8. Create a RAP Web UI plugin when creating a new Scout Project When creating a new Scout Project you can now choose to also create a RAP web plugin (this feature is only available when using an Eclipse version 3.6 or higher). The SDK then also supports you by creating a RAP target definition. See the "Create a new project" HowTo for more information about the different options. Add a RAP Web UI plugin to existing Scout Projects If you already have a Scout Project that will be migrated to Scout 3.8 and you want to use the new Web UI in your project, you can add a new Scout RAP Web bundle using the corresponding wizard: Export web projects as WAR files In previous Scout releases there was the possibility to export a Scout Server plugin using the "Export as WAR file" wizard. This wizard has been replaced by a more powerful version that is also capable to export the RAP Web UI bundle into a WAR file so that you can deploy it easily to an application server. Optionally you now also have the possibility to export the entire application into a single EAR. See the "Deploy to Tomcat" tutorial for more information. JAX-WS Integration A typical scenario for Eclipse Scout applications in the enterprise environment is to communicate with other applications through web services. With version 3.8 Scout is moving from the previously supported Apache Axis framework to the more modern and active JAX-WS technology. See this post for a brief introduction to the scope of the JAX-WS integration. This new feature is supported in the Scout SDK with the following capabilities: - Support to create/maintain JAX-WS consumers. - Support to create/maintain JAX-WS producers. Check out the corresponding tutorial to learn more on how to use the new features. Reorganized Scout Properties View Some objects in the Scout Explorer provide a lot of properties and operations to choose from. In the past the list was without any logical order. E.g. username and password properties did not belong together but were ordered alphabetically in the whole list which made it sometimes harder to find the corresponding fields. Therefore we redesigned the Property View to help the developers to find the right properties and operations more easily. Group Operations and Properties Operations and Properties are now grouped in two levels: - Separation in methods that are used very often and methods that are used rarely: For some object types certain properties or operations are very common. E.g. for a StringField the maxlength property should always be set. That's why we have defined a section Properties holding the most common ones for each object type and a section Advanced Properties holding all other methods. By default the more important properties are expanded while the advanced sections are collapsed. The same also exists for Operations. If you change the collapsed state, the sections remember your changes as long as your IDE is running. - Operations and Properties are grouped into types like Appearance, Layout, Behavior or Data. This helps to jump faster to the desired methods and ensures methods that belong to the same topics are next to each others. New Layout for the Scout Perspective Because the Operations and Properties are now separated (see paragraph above) the Property View does no longer need so much space. This allowed us to reorganize the Scout Perspective. With the new layout developers have more space for the Java Editor where the business logic is implemented. See the Scout Perspective wiki article for a screenshot of the new perspective layout. The Property View can also adapt to different layouts if you want to customize the Scout Perspective. As more space gets available on the X axis, the Property View re-layouts to make use of the free room: Help Text for Operations and Properties For some Properties or Operations it may not be clear what they do and how/when to use them. To support the developer we improved the help texts that are shown when you hover with the mouse over an Operation or Property. - First of all the help texts themselves have been added and improved at various places. It is not complete yet and we will continue to improve this type of help and documentation. - Second the hover window showing the help is now capable to follow the links provided in the help. Feature Technology Checkboxes Scout offers various additional functionalities and features that are not all enabled by default after a project has been created. To easier add and remove such features new Technology checkboxes have been added. When selecting the project node in the Scout Explorer, the section on the image "Feature Technology Section" is shown (amongst others) in the Scout Object Properties View. When the selection of a technology checkbox is changed, a confirmation box is shown to the user. This box lists which resources that would be changed to apply the new selection. The preselected resources can be adapted to the needs of the project. If the dialog is confirmed, the selected resources are modified to add or remove the feature for the chosen resources. If a technology is added that needs to install some new features from the internet first, a license confirmation dialog is shown upfront. After confirmation the required files are downloaded from the corresponding udpatesites and automatically installed in the local Eclipse instance of the developer. Management of External Libraries Scout SDK now allows to easily include and manage external libraries. Developers have the possibility to create own library bundles as - independent bundle that can be used by any plugin - fragment bundle for a specific host (the library will then only be available to that single host plugin) - fragment bundle for system.bundle which then allows every bundle to use the new library NLS (i18n) Changes Bug 361818 and Bug 354265 The Scout SDK also supports the new TextProviderServices introduced with Scout 3.8 (see here). The support is restricted to the built in support for properties files but can be extended to custom implementations if necessary. The NLS Editor is now capable to also show contents of TextProviderServices. Furthermore the SDK includes support to create new and remove existing TextProviderServices. Along with the move to TextProviderServices also other improvements of the NLS SDK have been implemented: - The Translation Dialog can now handle multiline texts - When creating a new translation, the Translation Dialog offers a generated key based on the text entered - The Translation Dialog remembers its last size - If creating a new translation out of a wizard: The Translation dialog offers to choose in which TextProviderService the new text should be created - Direct edit in the table of the NLS Editor (also supporting multi line) - Support to overwrite texts using the Translation Dialog - and much more... Bugfixes The following list shows all bugs which have been fixed for this release. The list also contains all new enhancements. Release 3.8.1 New Runtime Features InjectFieldTo Annotation A new annotation InjectFieldTo was introduced. It allows adding a field to an existing form without changing it. A field may be added to a container inside the same form or a container in the super classes form fields. In the following example, the field SalaryField is added to the FirstGroupBox by injection. The order of the fields in FirstGroupBox is determined by the @Order annotation. In this example, SalaryField will appear after NameField: public class BaseForm { @Order(10) public class MainBox extends AbstractGroupBox { @Order(10) public class FirstGroupBox extends AbstractGroupBox { @Order(10) public class NameField extends AbstractStringField { } } } } public class ExtendedForm extends BaseForm { @Order(20) @InjectFieldTo(BaseForm.MainBox.FirstGroupBox.class) public class SalaryField extends AbstractDoubleField { } } The injected fields are currently not displayed in the Scout SDK. Better support for creating/overriding form data in search and other forms This new feature allows to specify how a form creates its form data. This is useful when using search forms that should automatically attach a FormData export to the SearchFilter. Or if a subclass of a SearchForm has an extended FormData and wants to just override that. Former (frequently used) code inside a form/searchform of the form: @Override protected void execResetSearchFilter(SearchFilter searchFilter) throws ProcessingException { super.execResetSearchFilter(getSearchFilter()); FooSearchFormData data = new FooSearchFormData(); exportFormData(data); getSearchFilter().setFormData(data); } can now be replaced by: @Override protected AbstractFormData execCreateFormData() throws ProcessingException { return new FooSearchFormData(); } New extension point to allow customized service initialization By default, a service of type org.eclipse.scout.service.AbstractService is initialized with properties in the config.ini file. If the scout application is running inside another RCP application, the config.ini file often cannot be accessed. Therefore,a new extension point serviceInitializerFactory has been added to org.eclipse.scout.service.services to allow the registration of a custom service initializer factory. The default service initialization behavior stays the same. Bugfixes The following list shows all bugs which have been fixed for this release. The list also contains all new enhancements. Release 3.8.2 New Runtime Features Introducing ClientJobContext / [RAP] Adding support accessing HTTP context properties in Scout model thread The ClientJobContext allows to define a context per ClientJob. This context will be passed to every "Sub-ClientJob" (= ClientJob which is started/scheduled by the current running one). The class ClientJobContextThreadLocal is used to access the current client job context, whereon the properties can be get and/or set. This new feature will be used in Eclipse Scout RAP to add support accessing HTTP context properties (like HTTP request parameters, cookies, header) in Scout model thread. Therefore the AbstractRwtEnvironment contains two new methods ( beforeHttpRequest() and afterHttpRequest()) which can be overridden to get notified before and after a HTTP request has been processed by the RAP UI thread..8
http://wiki.eclipse.org/index.php?title=Scout/NewAndNoteworthy/3.8&oldid=342932
CC-MAIN-2016-26
refinedweb
2,728
53.81
i have a class Bag that has local variables . . . . private int i=10; private int [] x; private int top_pos=0; class Bag has a get method for an array value, a set method for an array value, a toString override, etc. i want to make a class BagExt that EXTENDS the Bag class. BagExt will inherit all of Bag's methods, but will override one and maybe overload one (just trying to get familiar with how inheritance works). so i tried to do the following . . . public class BagExt extends Bag{ public BagExt (){ super(); } public void add (int val){ i += val; } public int show_i (){ return i; } but when i try to compile, i get an error that "i" has private access in Bag. so do i have to declare similar variables of my own? and how is it that the default constructor will work? . . . it uses the Bag private varialbe of "int [] x". how do i get this to work? thanks crq
http://forums.devx.com/printthread.php?t=140185&pp=15&page=1
CC-MAIN-2016-30
refinedweb
161
80.82
On Thu, Jul 05, 2012 at 02:43:42PM +0300, Andy Shevchenko wrote:> The issue is in plain array of the numbers that are assigned to the devices.> Somehow looks better to have real namespaces, or even hide irq number in the API> struct device, request_irq(), but keep reference between driver and PIC via some> object.> So, given solution just hides an issue, but doesn't resolve it fully> from my p.o.v.This is unrelated to what you're talking about. The devices concernedare mostly MFDs which use their own interrupts. Where other things needto use the interrupt numbers then legacy mappings should still be usedand IRQ domains have no effect at all on the situation.[unhandled content-type:application/pgp-signature]
https://lkml.org/lkml/2012/7/5/161
CC-MAIN-2019-43
refinedweb
124
60.95
This sounds like a Mahout problem, not a Lucene problem- there are some text analysis tools that might help you. mark harwood wrote: > >>What is the "best practices" formula for determining above average > correlations of adjacent terms > > I gave this some thought in > > I found the Jaccard cooefficient favoured rare words too strongly and > so went for a blend as shown below: > > > public float getScore() > { > float overallIntersectionPercent = coIncidenceDocCount > / (float) (termADocFreq + termBDocFreq); > float termBIntersectionPercent = coIncidenceDocCount > / (float) (termBDocFreq); > > //using just the termB intersection favours common words as > // coincidents eg "new" food > // return termBIntersectionPercent; > //using just the overall intersection favours rare words as > // coincidents eg "scezchuan" food > // return overallIntersectionPercent; > // so here we take an average of the two: > return (termBIntersectionPercent + overallIntersectionPercent) > / 2; > } > > > ------------------------------------------------------------------------ > *From:* Mark Bennett <mbennett@ideaeng.com> > *To:* dev@lucene.apache.org > *Sent:* Fri, 10 September, 2010 18:44:31 > *Subject:* Re: Relevancy, Phrase Boosting, Shingles and Long Tail Curves > > Thanks Mark H, > > Maybe I'll look at MLT (More Like This) again. I'll also check out zipf. > > It's claimed that Question and Answer wording is different enough for > generic text content that different techniques might be indicated. > From what I remember: > 1: Though nouns normally convey 60% of relevancy in general text, Q&A > content is skewed a bit more towards verbs. > 2: Questions may contain more noise words (though perhaps in useful > groupings) > 3: Vocabulary mismatch of Interrogative vs. declarative / narrative (Q > vs A) > 4: Vocabulary mismatch of novices vs experts (Q vs A) > > It was item 2 that I was hoping to capitalize on with NGrams / Shingles. > > Still waiting for the relevancy math nerds to chime in about the > log-log and IDF stuff ... ;-) > > I was thinking a bit more about the math involved here.... > > What is the "best practices" formula for determining above average > correlations of adjacent terms, beyond what random chance would give. > So you notice that "white" and "house" appear next to each other more > than what chance distribution would explain, so you decide it's an > important NGram. > > The "noise floor" isn't too bad for the typical shopping cart items > calculation. > You analyze the items present or not present in 1,000 shopping cart > receipts. > If grocery items were completely independent then "random" level > is just the odds of the 2 items multiplied together: > 1,000 shopping carts > 200 have cereal > 250 have milk > chance of > cereal = 200/1,000 = 20% > milk = 250/1,000 = 25% > IF independent then > P(cereal AND milk) = P(cereal) * P(milk) > 20% * 25% = 5% > So 50 carts likely to have both cereal and milk > And if MORE than 50 carts have cereal and milk, then it's > worth noting. > The classic example is diapers and beer, which is a bit apocryphal and > NOT expected, but I like the breakfast cereal and milk example better > because it IS expected. > > Now back to word-A appearing directly before word-B, and finding the > base level number of times you'd expect just from random chance. > > Although Lucene/Luke gives you total word instances and document > counts, what you'd really want is the number of possible N-Grams, > which is affected by document boundaries, so it gets a little weird. > > Some other differences between the word-A word-B calculation vs milk > and cereal: > 1: I want ordered pairs, "white" before "house" > 2: A document is NOT like a shopping cart in that I DO care how many > times "white" appears before "house", whereas in the shopping carts I > only cared about present or not present, so document count is less > helpful here. > > I'm sure some companies and PHD's have super secret formulas for this, > but I'd be content to just compare it to baseline random chance. > > Mark B > > -- > Mark Bennett / New Idea Engineering, Inc. / mbennett@ideaeng.com > <mailto:mbennett@ideaeng.com> > Direct: 408-733-0387 / Main: 866-IDEA-ENG / Cell: 408-829-6513 > > > On Fri, Sep 10, 2010 at 3:17 AM, mark harwood <markharw00d@yahoo.co.uk > <mailto:markharw00d@yahoo.co.uk>> wrote: > > Hi Mark > I've played with Shingles recently in some auto-categorisation > work where my starting assumption was that multi-word terms will > hold more information value than individual words and that phrase > queries on seperate terms will not give these term combos their > true reward (in terms of IDF) - or if they did compute the true > IDF, would require lots of disk IO to do this. Shingles present a > conveniently pre-aggregated score for these combos. > Looking at the results of MoreLikeThis queries based on a > shingling analyzers the results I saw generally seemed good but > did not formally bench mark this against non-shingled indexes. Not > everything was rosy in that I did see some tendency to over-reward > certain rare shingles (e.g. a shared mention of "New Years Eve > Party" pulled otherwise mostly unrelated news articles together). > This led me to look at using the links in resulting documents to > help identify clusters of on-topic and potentially off-topic > results to tune these discrepancies out but that's another topic. > BTW, the Luke tool has a "Zipf" plugin that you may find useful in > examining index term distributions in Lucene indexes.. > > Cheers > Mark > > ------------------------------------------------------------------------ > *From:* Mark Bennett <mbennett@ideaeng.com > <mailto:mbennett@ideaeng.com>> > *To:* java-dev@lucene.apache.org <mailto:java-dev@lucene.apache.org> > *Sent:* Fri, 10 September, 2010 1:42:11 > *Subject:* Relevancy, Phrase Boosting, Shingles and Long Tail Curves > > I want to boost the relevancy of some Question and Answer content. > I'm using stop words, Dismax, and I'm already a fan of Phrase > Boosting and have cranked that up a bit. But I'm considering using > long Shingles to make use of some of the normally stopped out > "junk words" in the content to help relevancy further. > > Reminder: "Shingles" are artificial tokens created by gluing > together adjacent words. > Input text: This is a sentence > Normal tokens: this, is, a, sentence (without removing stop > words) > 2+3 word shingles: this-is, is-a, a-sentence, this-is-a, > is-a-sentence > > A few questions on relevance and shingles: > > 1: How similar are the relevancy calculations compare between > Shingles and exact phrases? > > I've seen material saying that shingles can give better > performance than normal phrase searching, and I'm assuming this is > exact phrase (vs. allowing for phrase slop) > > But do the relevancy calculations for normal exact phrase and > Shingles wind up being *identical*, for the same documents and > searches? That would seem an unlikely coincidence, but possibly > it could have been engineered to intentionally behave that way. > > 2: What's the latest on Shingles and Dismax? > > The low front end low level tokenization in Dismax would seem to > be a problem, but does the new parser stuff help with this? > > 3: I'm thinking of a minimum 3 word shingle, does anybody have > > Eyeballing the 2 word shingles, they don't seem much better than > stop words. Obviously my shingle field bypasses stop words. > > But the 3 word shingles start to look more useful, expressing more > intent, such as "how do i", "do i need" and "it work with", etc. > > Has there been any Lucene/Solr studies specifically on shingle length? > > and finally... > > 4: Is it useful to examine your token occurrences against a > Power-Law log-log curve? > > So, with either single words, or shingles, you do a histogram, and > then plot the histogram in an X-Y graph, with both axis being > logarithmic. Then see if the resulting graph follows (or diverges) > from a straight line. This "Long Tail" / Pareto / powerlaw > mathematics were very popular a few years ago for looking at > histograms of DVD rentals and human activities, and prior to the > web, the power law and 80/20 rules has been observed in many other > situations, both man made and natural. > > Also of interest, when a distribution is expected to follow a > power line, but the actual data deviates from that theoretical > line, then this might indicate some other factors at work, or so > the theory goes. > > So if users' searches follow any type of histogram with a hidden > powerlaw line, then it makes sense to me that the source content > might also follow a similar distribution. Is the normal IDF > ranking inspired by that type of curve? > > And *if* word occurrences, in either searches or source documents, > were expected to follow a power law distribution, then possible > shingles would follow such a curve as well. > > Thinking that document text, like many other things in nature, > might follow such a curve, I used the Lucene index to generate > such a curve. And I did the same thing for 3 word tokens. The 2 > curves do have different slopes, but neither is very straight. > > So I was wondering if anybody else has looked at IDF curves > (actually non-inverted document frequency curves) or raw word > instance counts and power law graphs? I haven't found a smoking > gun in my online searches, but I'm thinking some of you would know > this. > > > -- > Mark Bennett / New Idea Engineering, Inc. / mbennett@ideaeng.com > <mailto:mbennett@ideaeng.com> > Direct: 408-733-0387 / Main: 866-IDEA-ENG / Cell: 408-829-6513 > > > --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@lucene.apache.org For additional commands, e-mail: dev-help@lucene.apache.org
http://mail-archives.apache.org/mod_mbox/lucene-dev/201009.mbox/%3C4C8BF36B.2020703@gmail.com%3E
CC-MAIN-2017-30
refinedweb
1,549
56.59
This is a C++ Program to find the area of ploygon using slicker algorithm.. Here is source code of the C++ Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below. #include <iostream> using namespace std; const int MAXPOLY = 200; double EPSILON = 0.000001; class Point { private: public: double x, y; }; class Polygon { private: public: Point p[MAXPOLY]; int n; Polygon() { for (int i = 0; i < MAXPOLY; i++) Point p[i];// = new Point(); } }; double area(Polygon p) { double total = 0; for (int i = 0; i < p.n; i++) { int j = (i + 1) % p.n; total += (p.p[i].x * p.p[j].y) - (p.p[j].x * p.p[i].y); } return total / 2; } int main(int argc, char **argv) { Polygon p; cout << "Enter the number of points in Polygon: "; cin >> p.n; cout << "Enter the coordinates of each point: <x> <y>"; for (int i = 0; i < p.n; i++) { cin >> p.p[i].x; cin >> p.p[i].y; } double a = area(p); if (a > 0) cout << "The Area of Polygon with " << (p.n) << " points using Slicker Algorithm is : " << a; else cout << "The Area of Polygon with " << p.n << " points using Slicker Algorithm is : " << (a * -1); } Output: $ g++ PloygonAreaSlickerAlgo.cpp $ a.out Enter the number of points in Polygon: 4 Enter the coordinates of each point: <x> <y> 1 1 1 6 6 6 6 1 The Area of Polygon with 4 points using Slicker Algorithm is : 25 Enter the number of points in Polygon: 5 Enter the coordinates of each point: <x> <y> 1 2 4 5 9 8 3 2 1 5 The Area of Polygon with 5points using Slicker Algorithm is : 6.0 ------------------ (program exited with code: 0) Press return to continue Sanfoundry Global Education & Learning Series – 1000 C++ Programs. Here’s the list of Best Reference Books in C++ Programming, Data Structures and Algorithms. « Prev Page - C++ Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
http://www.sanfoundry.com/cpp-program-implement-slicker-algorithm-avoids-triangulation-find-area-polygon/
CC-MAIN-2017-09
refinedweb
354
71.44
What is CDN? A Content Delivery Network (CDN) helps you deliver your content more quickly. You can serve any type of content that remains unchanged over a period of time, like images, videos, CSS, JavaScript, HTML files, PDFs, and more. A CDN is a group of servers that are spread across the world to deliver the content from the Edge servers. Edge servers are servers located closest to the place from where the request is being made. Depending on the request, edge servers may either return the content from its cache or they can fetch it from the Origin Server. The servers that serve the actual content are called Origin servers. In the above image, the Edge Servers are located around the world and the Origin Server is located in California, USA. When a request is made, the Edge Server located at Mumbai, India may contact the Origin Server if it's not able to serve the content. How CDN works? CDNs have four main parts: A Consumer, DNS, Edge Server & Origin Server. When the Consumer makes a request, it is at first accepted by its Internet Service Provider (ISP). The ISP will then hit the content provider's Authoritative DNS. An Authoritative DNS converts the DNS request to an IP request. When the Authoritative DNS is made, it returns the IP address of the closest Edge Server. The Edge Server will then check in its own cache to see if the requested content is available. If it is, then it returns the content. If the content is not available, it requests the content from the Origin Server and on retrieval caches it. Benefits of CDN Low Bandwidth Consumption Many web hosts have a limited bandwidth allocation per month. If you go beyond that you will be charged extra. With a CDN most of your bandwidth will be saved since the content will be served by the edge servers. Low Latency The Edge Servers cache the content. So anytime cached content is requested the latency is reduced drastically. This is because the request doesn't go all the way to the Origin Server. Security against DDoS Almost all the popular CDN's have the capability to protect your webserver against Distributed denial of service (DDos) attacks. Improves SEO Loading time is one of the factors that can affect your site's SEO rankings. If you are serving most of your content via CDN, the loading times are drastically reduced and can help improve your SEO. Deep Dive into Azure CDN Let's say you have created an Azure Storage Account and hosted a very simple site that displays Hello World as h1. Now that you know the benefits of CDNs, you want to serve your simple site over CDN. You will have an endpoint something like(where instead of demostorageaccountarjav it would be your storage account's name). Here are more details on how to setup a static website. Login to your Azure Portal and click on Create a resource from you dashboard. Search for CDN which will open the resource in the marketplace as below. This will open up a form to create a CDN profile. A CDN profile is a set of CDN endpoints. There is not much to fill in here except the name, resource group, and the pricing tier. Next, select the checkbox to create a CDN endpoint. An endpoint is where the Consumer will be requesting content. So if you have multiple sites you can create multiple endpoints as well. I have attached a screenshot for your reference on what values to put in. Since CDN is a global service the region selection will be disabled. You can now click on Create to generate the profile and endpoint. It will take a couple of minutes to create. After it is created and when you go to the home screen, you will have these 4 resources: As discussed earlier the CDN Profile is a group of Endpoints. To view the details click the Endpoint resource. You will see an overview with a link to the Endpoint hostname. When you open the endpoint hostname it might show "404 not found" initially. You might have to wait another 10-15 minutes before your actual site is visible. As discussed in the benefits section you can configure the Endpoint for security, caching, routing & a lot of other things. You can explore more concepts here. How to Access via SAS Token You may be wondering what if my resource is in a private container and can only be accessed via a Shared Access Signature (SAS) Token. Well you are in luck! The query strings are passed on as they are and since SAS is as a query string you are good. Go ahead and create a new storage account (with static website disabled). Add a new Endpoint in the CDN profile that points to the newly created storage account. For demo purposes I have created a container named site with private access level and uploaded a Blob named Photo.jpeg in a Storage Account with URL. You can of course get a SAS token from the Azure portal directly for testing, but that's not how you would usually do in real-world. For that find below a simple snippet to create SAS token in Node.js. const azureSasToken = require('azure-sas-token'); // default token validity is 7 days let sasToken = azureSasToken.createSharedAccessToken('https://<service namespace>.servicebus.windows.net/<topic name or queue>', '<signature key name>', '<signature hash>'); console.log(`sasToken: ${sasToken}`); // Specify your own validity in secs, two hours in this example sasToken = azureSasToken.createSharedAccessToken('https://<service namespace>.servicebus.windows.net/<topic name or queue>', '<signature key name>', '<signature hash>', 60 * 60 * 2); console.log(`sasToken: ${sasToken}`); We have used a simple npm package named azure-sas-token. Once the SAS is generated your URL will look something like: The above URL is pointing directly to the storage account. So go ahead and change the origin so that it uses the origin endpoint. When you visit this site you will now be able to view the protected resource via CDN. Conclusion In my opinion everyone should be using a Content Delivery Network. There are lots of other providers like Cloudflare, S3 etc. but Microsoft is one of the major players which is emerging with a wide variety of services. If you are an Azure fan like I am you should definitely give Azure CDN a try. For any feedback or questions you can get in touch with me. Check here for more tutorials like this. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/itnext/how-to-speed-up-your-website-with-azure-cdn-3e63
CC-MAIN-2021-21
refinedweb
1,098
73.68
crosstabs() Method: Compute Aggregated Metrics Across Categorical Columns - Nov 23 • 20 min read - Key Terms: crosstabs, python, pandas A crosstab computes aggregated metrics among two or more columns in a dataset that contains categorical values. Import Modules import pandas as pd import seaborn as sns Crosstabs with Tips Dataset Grouping By a Single Field for the Index and Column Let's compute a simple crosstab across the day and sex column. We want our returned index to be the unique values from day and our returned columns to be the unique values from sex. By default in pandas, the crosstab() computes an aggregated metric of a count (aka frequency). So, each of the values inside our table represent a count across the index and column. For example, males served 30 unique groups across all Thursdays in our dataset. pd.crosstab(index=df_tips['day'], columns=df_tips['sex']) One issue with this crosstab output is the column names are nonsensical. Just saying Male or Female isn't very specific. They should be renamed to be clearer. We can use the rename() method and set the argument columns to be a dictionary in which the keys are the current column names and the values are the respective new names to set. pd.crosstab(index=df_tips['day'], columns=df_tips['sex']).rename(columns={"Male": "count_meals_served_by_males", "Female": "count_meals_served_by_females"}) Also, in the output above, see where it says sex as the column name and day for the row name? We can modify those names using arguments in the crosstab() method. Let's set the colnames argument to gender since that's a more specific name than sex. pd.crosstab(index=df_tips['day'], columns=df_tips['sex'], colnames=['gender']).rename(columns={"Male": "count_meals_served_by_males", "Female": "count_meals_served_by_females"}) In this example, we passed in two columns from our DataFrame. However, one nice feature of crosstab() is that you don't need the data to be in a DataFrame. For the index and columns arguments, you can pass in two numpy arrays. Let's double check the logic from above makes sense. Let's use filtering in pandas to verify that there were 30 meals served by a male on Thursday. Our query below matches the 30 number we see above. len(df_tips.query("sex=='Male' and day=='Thur'")) 30 Alternatively, given the crosstab output above, you can present it in a different format that may be easier for further analysis. I won't dive into details of this operation, but in addition to the code above, you can chain the unstack() method and then the reset_index() method to pivot the DataFrame so each row is a unique combination of a value from sex and day with the appropriate count of meals served. pd.crosstab(index=df_tips['day'], columns=df_tips['sex'], colnames=['gender']).unstack().reset_index().rename(columns={0: "count_meals_served"}) For each row and column of this previous crosstab, we can modify an argument to get the totals. Set the argument margins to True to get these totals. By default, the returned output will have a column and row name of All. pd.crosstab(index=df_tips['day'], columns=df_tips['sex'], colnames=['gender'], margins=True).rename(columns={"Male": "count_meals_served_by_males", "Female": "count_meals_served_by_females"}) In the crosstab() method, we can also rename the All column. First, use all the same arguments from above. Then, set the argument margins_name to count_meals_served . pd.crosstab(index=df_tips['day'], columns=df_tips['sex'], colnames=['gender'], margins=True, margins_name="count_meals_served").rename(columns={"Male": "count_meals_served_by_males", "Female": "count_meals_served_by_females"}) For each cell value, we can calculate what percentage it is of the row's total. To do that, set the normalize argument to 'index' (since index applies to each row). pd.crosstab(index=df_tips['day'], columns=df_tips['sex'], colnames=['gender'], margins=True, margins_name="proportion_meals_served", normalize='index').rename(columns={"Male": "proportion_meals_served_by_males", "Female": "proportion_meals_served_by_females"}) For each cell value, we can also calculate what percentage it is of the column's total. To do that, set the normalize argument to 'columns'. pd.crosstab(index=df_tips['day'], columns=df_tips['sex'], colnames=['gender'], margins=True, margins_name="proportion_meals_served", normalize='columns').rename(columns={"Male": "proportion_meals_served_by_males", "Female": "proportion_meals_served_by_females"}) Given two categorical columns, the crosstab() method can additionally utilize a column with numerical values to perform an aggregate operation. That sentence may sound daunting - so let's walk through it with a simple example. We know there exists total_bill values in our datasets for males that served meals on Thursday. Below, I preview the first few total_bill values that meet this criteria. df_tips.query("sex=='Male' and day=='Thur'")['total_bill'].head() 77 27.20 78 22.76 79 17.29 80 19.44 81 16.66 Name: total_bill, dtype: float64 We may want to know the average bill size that meet the criteria above. So, given that series, we can calculate the mean and we arrive at a result of 18.71. df_tips.query("sex=='Male' and day=='Thur'")['total_bill'].mean() 18.714666666666666 Now, we can perform this same operation using the crosstab() method. Same as before, we want our returned index to be the unique values from day and our returned columns to be the unique values from sex. Additionally, we want the values inside the table to be from our total_bill column so we'll set the argument values to be df_tips['total_bill']. We also want to calculate the mean total bill for each combination of a day and gender so we'll set the aggfunc argument to 'mean'. pd.crosstab(index=df_tips['day'], columns=df_tips['sex'], values=df_tips['total_bill'], colnames=['gender'], aggfunc='mean').rename(columns={"Male": "mean_bill_size_meals_served_by_males", "Female": "mean_bill_size_meals_served_by_females"}) This crosstab calculation outputted the same 18.71 value as expected! We can pass in many other aggregate methods to the aggfunc method too such as mean and standard deviation. You can learn more about details of using crosstab() from the official pandas documentation page. Grouping By Multiple Fields for the Index and/or Columns We can also use the crosstabs() method to group by multiple pandas columns for the index or columns arguments. For example, we can find out for days of the week, for each gender, what was the count of meals they served for lunch or dinner. In pandas We want our returned index to be the unique values from day and our returned columns to be the unique values from all combinations of the sex (gender) and time (meal time) columns. To interpret a value from our table below, across all Thursdays in our dataset, females served 31 lunch meals. pd.crosstab(index=df_tips['day'], columns=[df_tips['sex'], df_tips['time']], colnames=['gender', 'meal']).rename(columns={"Lunch": "count_lunch_meals_served", "Dinner": "count_dinner_meals_served"}) We can verify the logic in a value with a separate query. I'm curious to see the count of meals on Thursday served by females during lunch time. Our result on this query is 31 which matches the value in the crosstab above! len(df_tips.query("day=='Thur' and sex=='Female' and time=='Lunch'")) 31 If you're familiar with the groupby() method in pandas, the code below performs a similar operation to the crosstab above, but the output format is a little different. df_tips.groupby(['day', 'sex'])['time'].count() day sex Thur Male 30 Female 32 Fri Male 10 Female 9 Sat Male 59 Female 28 Sun Male 58 Female 18 Name: time, dtype: int64 We can also group by multiple pandas columns in the index argument of the crosstabs() method. Below is a fairly complex operation. The code below helps us find out for every combination of day of the week, gender and meal type what was the count of meals served for the various group sizes (ex - party of two people versus party of three). In our output, the index includes unique values from the day and sex fields while columns include unique values from the time and size fields. To interpret a value from our table below, across all Thursdays in our dataset, males 24 lunch meals that contained a group of 2 people. pd.crosstab(index=[df_tips['day'], df_tips['sex']], columns=[df_tips['time'], df_tips['size']], colnames=['meal', 'party_people_size']).rename(columns={"Lunch": "count_lunch_meals_served", "Dinner": "count_dinner_meals_served"}) We can verify 24 lunch meals for a party of 2 were served by males on Thursdays with the query below too. len(df_tips.query("day=='Thur' and sex=='Male' and time=='Lunch' and size==2")) 24 Style Output While the above output is daunting to read with all the cells, there's a cool trick in Seaborn to make your DataFrame output appear as a heatmap. I added some code based off the example from the pandas documention for built-in styles. Now, we can more easily identify the large values as being dark orange colors in our visualization below. orange = sns.light_palette("orange", as_cmap=True) pd.crosstab(index=[df_tips['day'], df_tips['sex']], columns=[df_tips['time'], df_tips['size']], colnames=['meal', 'party_people_size']).rename(columns={"Lunch": "count_lunch_meals_served", "Dinner": "count_dinner_meals_served"}).style.background_gradient(cmap=orange)
https://dfrieds.com/data-analysis/crosstabs-python-pandas
CC-MAIN-2019-26
refinedweb
1,471
55.54
SYNOPSIS #include <stdlib.h> int mblen(const char *s, size_t n); DESCRIPTION If s is not a NULL pointer, the mblen() function inspects at most n bytes of the multibyte string starting at s and extracts the next com- plete multibyte character. It uses a static anonymous shift state only known char- acter, mblen() returns -1. -1. If s is a NULL pointer, the mblen() function resets the shift state, only known to this function, to the initial state, and returns non-zero if the encoding has nontrivial shift state, or zero if the encoding is stateless. RETURN VALUE. CONFORMING.23 of the Linux man-pages project. A description of the project, and information about reporting bugs, can
http://www.linux-directory.com/man3/mblen.shtml
crawl-003
refinedweb
118
60.85
Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask Namespace SQL Server 2008 The ExecuteSQLTask namespace contains the ExecuteSQLTask class that enables a package to run SQL statements. The task can be configured to use result sets, making the results of the SQL statement available to other objects in the package. To use a result set, map the result set to a variable, which can then be used by other objects in the package. The task can also be configured to run parameterized queries. To provide parameter values, map the variables that contain the parameter values to the columns in the query. Packages commonly use the functionality of the ExecuteSQLTask to perform actions on database objects, such as truncating tables, selecting rows in tables and views, or running stored procedures. Show:
http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dts.tasks.executesqltask(v=sql.100).aspx
CC-MAIN-2014-52
refinedweb
127
50.67
TTY is a toolbox for developing beautiful command line clients in Ruby with a fluid interface for gathering input, querying terminal properties and displaying information. MotivationMotivation. FeaturesFeatures - Jump-start development of your command line app the Unix way with scaffold provided by teletype. - Fully modular, choose out of many components to suit your needs or use any 3rd party ones. - All tty components are small packages that do one thing well. - Fully tested with major ruby interpreters. InstallationInstallation Add this line to your application's Gemfile to install all components: gem 'tty' or install a particular component: gem 'tty-*' And then execute: $ bundle Or install it yourself as: $ gem install tty ContentsContents - 1. Overview - 2. Bootstrapping - 3. Components - 4. Contributing 1. Overview1. Overview TTY provides you with commands and many components to get you onto the path of building awesome terminal applications in next to no time. To simply jump start a new command line application use teletype executable: $ teletype new app and then to add more commands: $ teletype add config Throughout the rest of this guide, I will assume a generated application called app and a newly created bare command config. 2. Bootstrapping2. Bootstrapping 2.1 new command Running teletype new [app-name] will bootstrap an entire project file structure based on the bundler gem command setup enhanced by additional files and folders related to command application development. For example, to create a new command line application called app do: $ folder provides Thor as an option parsing library by directly inheriting from it. And also by convention the start method is used to parse the command line arguments inside the app executable: App::CLI.start Run the new command with --help or -h flag to see all available options: $ teletype new --help $ teletype new -h Execute teletype to see all available commands. 2.1.1 --author, -a flag The teletype generator can inject name into documentation for you: $ teletype new app --author 'Piotr Murach' 2.1.2 --ext flag To specify that teletype should create a binary executable (as exe/GEM_NAME) in the generated project use the --ext flag. This binary will also be included in the GEM_NAME.gemspec manifest. This is disabled by default, to enable do: $ teletype new app --ext 2.1.3 --license, -l flag The teletype generator comes prepackaged with most popular open source licenses: agplv3, apache, bsd2, bsd3, gplv2, gplv3, lgplv3, mit, mplv2, custom. By default the mit license is used. To change that do: $ teletype new app --license bsd3 2.1.4 --test, -t flag The teletype comes configured to work with rspec and minitest frameworks which are the only two acceptable values. The GEM_NAME.gemspec will be configured and appropriate testing directory setup. By default the RSpec framework is used. $ teletype new app --test=minitest $ teletype new app -t=minitest 2.2 add command Once application has been initialized, you can create additional command by using teletype add [command-name] task: $ teletype add config $ teletype add create This will add create.rb and config.rb commands execute methods. Please note that command names should be provided as camelCase or snake_case. For example: $ teletype add addConfigCommand # => correct $ teletype add add_config_command # => correct $ teletype add add-config-command # => incorrect 2.2.1 --args flag You can specify that teletype should add a command with a variable number of arguments using the --args flag. The --args flag accepts space delimited variable names. To specify required argument use a string name, for an optional argument pass name = nil enclosed. 2.2.2 --desc flag Every generated command will have a default description 'Command description...', however whilst generating a command you can and should specify a custom description to provide more context with --desc flag: $ teletype add config --desc 'Set and get configuration options' For more in-depth usage see 2.5 Description. 2.2.3 --force flag If you wish to overwrite currently implemented command use --force flag: $ teletype add config --force 2.3 Working with Commands2.3 Working with Commands Running teletype add config a new command config will be added to commands folder creating the following files structure inside the lib folder: ▾ app/ ├── ▾ commands/ │ └── config.rb ├── ▾ templates/ │ └── ▸ config/ ├── cli.rb ├── command.rb └── version.rb The lib/app/cli.rb file will contain generated command entry which handles the case where the user asks for the config command help or invokes the actual command: module App class CLI < Thor desc 'config', 'Command description...' def config(*) if options[:help] invoke :help, ['config'] else require_relative 'commands/config' App::Commands::Config.new(options).execute end end end end And the lib/app/commands/config.rb will allow you to specify all the command logic. In the Config class which by convention matches the command name, the execute method provides a place to implement the command logic: module App module Commands class Config < App::Command def initialize(options) @options = options end def execute # Command logic goes here ... end end end end Notice that Config inherits from App::Cmd class which you have full access to. This class is meant to provide all the convenience methods to lay foundation for any command development. It will lazy load many tty components inside helper methods which you have access to by opening up the lib/app/command.rb file. For example in the lib/app/command.rb file, you have access to prompt helper for gathering user input: # The interactive prompt # # @see # # @api public def prompt(**options) require 'tty-prompt' TTY::Prompt.new(options) end or a command helper which you can change to suite your needs and pick only tty components that fit your case. 2.4 Arguments2.4 Arguments A command may accept a variable number of arguments. For example, if we wish to have a config command that accepts a location of configuration file, then we can run teletype add command passing --args flag: $ teletype add config --args file which will include the required file as an argument to the config method: module App class CLI < Thor desc 'config FILE', 'Set and get configuration options' def config(file) ... end end end Similarly, if we want to generate command with two required arguments, we run teletype add command with --args flag argument is an optional argument in the config command, then you need to enclose --args argument 2.5 Description2.5 Description Use the desc method call to describe your command when displayed in terminal. There are two arguments to this method. First, specifies the command name and the actual positional arguments it will accept. The second argument is an actual text description of what the command does. For example, given the command config generated in add command section, we can add description like so: module App class CLI < Thor desc 'config [FILE]', 'Set and get configuration options' def config(file = nil) ... end end end Running app executable will include the new description: Commands: app config [FILE] # Set and get configuration options To provide long form description of your command use long_desc method. module App class CLI < Thor desc 'config [FILE]', 'Set and get configuration options' long_desc <<-DESC You can query/set/replace/unset options with this command. The name is an optional key separated by a dot, and the value will be escaped. This command will fail with non-zero status upon error. DESC def config(file = nil) ... end end end Running app config --help will produce the following output: Usage: app config You can query/set/replace/unset options with this command. The name is an optional key separated by a dot, and the value will be escaped. This command will fail with non-zero status upon error. 2.6 Options and Flags2.6 Options and Flags Flags and options allow to customize how particular command is invoked and provide additional configuration. To specify individual flag or option use method_option before the command method. All the flags and options can be accessed inside method body via the options hash. option type for accepting more than one value and :banner to provide meaningful description of values: method_option :add, type: :array, banner: "name value", desc: "Adds a new line the config file. " The above option would be included in the config method like so: module App class CLI < Thor desc 'config [<file>]', 'Set and get configuration options' method_option :add, type: :array, banner: "name value", desc: "Adds a new line the config file. " def config(*) ... end end end Running app help config will output new option: Usage: app config [<file>] Options: [--add=name value] # Adds a new line the config file. You can also specify an option as a flag without an associated value. Let us assume you want to be able to open a configuration file in your system editor when running app config --edit or app config -e. This can be achieved by adding the following option: method_option :edit, type: :boolean, aliases: ['-e'], desc: "Opens an editor to modify the specified config file." And adding it to the config method: module App class CLI < Thor desc 'config [<file>]', 'Set and get configuration options' method_option :edit, type: :boolean, aliases: ['-e'], desc: "Opens an editor to modify the specified config file." def config(*) ... end end end Next, running app help config will produce: Usage: app config [<file>] Options: [--add=name value] # Adds a new line the config file. -e, [--edit], [--no-edit] # Opens an editor to modify the specified config file. You can use method_options as a shorthand for specifying multiple options at once. method_options %w(list -l) => :boolean, :system => :boolean, :local => :boolean Once all the command options and flags have been setup, you can access them via options hash in command file lib/app/commands/config.rb: module App module Commands class Config < App::Command def initialize(options) @options = options end def execute if options[:edit] editor.open('path/to/config/file') end end end end end 2.7 Global Flags2.7 Global Flags You can specify an option or a flag that is applicable to all commands and subcommands within a given class by using the class_option method. This method takes exactly the same parameters as method_option for an individual command. The options hash in a given command will always include a global level flag information. For example, if you want a global flag debug that is visible to all commands in your tool then you need to add it to your CLI class like so: module App class CLI < Thor class_option :debug, type: :boolean, default: false, desc: 'Run in debug mode' ... end end 2.8. Working with Subcommands2.8. Working with Subcommands If your tool grows in complexity you may want to add more refined behaviour for each individual command, a subcommand is a great choice to accomplish this. For example, git utility and its git remote command have various subcommands add, rename, remove, set-url, prune and so on that themselves accept many options and arguments. The teletype executable allows you to easily create new subcommands by issuing the same add command that is also used for generating commands. The only difference is that you need to provide a command name together with a subcommand name. For example, let's say we want the config with a set subcommand with a description and two positional arguments name and value: $ teletype add config set --desc 'Set configuration option' --args name value This will add set.rb command to the commands/config folder: will contain code that registers config namespace with our CLI root application: module App class CLI < Thor require_relative 'commands/config' register App::Commands::Config, 'config', 'config [SUBCOMMAND]', 'Set configuration option' end end The lib/app/commands/config.rb will contain code that handles dispatching subcommands to the Config instance: # will contain the actual set commandtype to crash. The reason why it is not possible to add subcommands to existing commands is that it is impossible for tty to distinguish between normal arguments to a command, and subcommands for that command. However, you may very well add multiple subcommands one after another. 3. Components3. Components The TTY allows you to mix & match any components you need to get your job done. The command line applications generated with teletype executable references all of the below components. 4. Contributing4. Contributing You can contribute by posting feature requests, evaluating the APIs or simply by hacking on TTY components: - Fork it - Create your feature branch ( git checkout -b my-new-feature) - Commit your changes ( git commit -am 'Add some feature') - Push to the branch ( git push origin my-new-feature) - Create new Pull Request.
https://reposhub.com/ruby/cli-builder/piotrmurach-tty.html
CC-MAIN-2020-45
refinedweb
2,082
51.78
MKNOD(3P) POSIX Programmer's Manual MKNOD(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. mknod, mknodat — make directory, special file, or regular file #include <sys/stat.h> int mknod(const char *path, mode_t mode, dev_t dev); int mknodat(int fd, const char *path, mode_t mode, dev_t dev); The mknod() function shall create a new file named by the pathname to which the argument path points. The file type for path is OR'ed into the mode argument, and the application shall select one of the following symbolic constants: The only portable use of mknod() is to create a FIFO-special file. If mode is not S_IFIFO or dev is not 0, the behavior of mknod() is unspecified. The permissions for the new file are OR'ed into the mode argument, and may be selected from any combination of the following symbolic constants: The user ID of the file shall be initialized to the effective user ID of the process. The group ID of the file shall be initialized to either the effective group ID of the process or the group ID of the parent directory. Implementations shall provide a way to initialize the file's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process. The owner, group, and other permission bits of mode shall be modified by the file mode creation mask of the process. The mknod() function shall clear each bit whose corresponding bit in the file mode creation mask of the process is set. If path names a symbolic link, mknod() shall fail and set errno to [EEXIST]. Upon successful completion, mknod() shall mark for update the −1 and set errno to indicate the error. If −1 is returned, the new file shall not be created. These functions shall fail if: names. Creating a FIFO Special File The following example shows how to create a FIFO special file named /home/cnd/mod_done, with read/write permissions for owner, and with read permissions for group and others. #include <sys/types.h> #include <sys/stat.h> dev_t dev; int status; ... status = mknod("/home/cnd/mod_done", S_IFIFO | S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH, dev); The mkfifo() function is preferred over this function for making FIFO special files. The POSIX.1‐1990 standard required that the group ID of a newly created file be set to the group ID of its parent directory or to the effective group ID of the creating process. FIPS 151‐2. The purpose of. None. chmod(3p), creat(3p), exec(1p), fstatat(3p), mkdir(3p), mkfifo(3p), open(3p), umask(3p) The Base Definitions volume of POSIX.1‐2008, sys_statKNOD(3P)
https://man7.org/linux/man-pages/man3/mknodat.3p.html
CC-MAIN-2020-50
refinedweb
492
51.48
qUncompress problem Hi, I get the strange error with qUncompress but I don't know what is problem with my configuration. Here is my code: #include <QCoreApplication> #include <QByteArray> #include <QFile> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QFile f("/user/XXXXXX/home/AgeRegression"); if (f.exists()) qDebug() << "File exists"; else qDebug() << "Missing file"; f.open(QIODevice::ReadOnly); QByteArray qb = f.readAll(); qb = qUncompress(qb); qDebug()<<"Successfully"; const char *qt_version = qVersion(); qDebug()<< QString(qt_version); return a.exec(); } The file AgeRegression you can download from here. And here is result: File exists qUncompress: Z_DATA_ERROR: Input data is corrupted Successfully "5.3.2" The interesting thing is the other people seems to don't have issues when they run it on MacOS or Ubuntu while mine is Fedora 19. Can someone see my problem and help me? Thank in advance. UPDATE: Now when I try with the file compressed by the file which was compressed by qCompress, I got the same issues.
https://forum.qt.io/topic/56096/quncompress-problem
CC-MAIN-2018-13
refinedweb
165
57.98
Present and Future ValuesEdit DiscountingEdit Net Present ValueEdit FormulaEdit Each cash inflow/outflow is discounted back to its present value (PV). Then they are summed. Therefore NPV is the sum of all terms , where - t - the time of the cash flow - i - the discount rate (the rate of return that could be earned on an investment in the financial markets with similar risk.) - the net cash flow (the amount of cash, inflow minus outflow) at time t (for educational purposes, is commonly placed to the left of the sum to emphasize its role as (minus the) investment. The discount rateEdit (WACC) as the discount factor. It reflects opportunity cost of investment, rather than the possibly lower cost of capital. A NPV amount obtained using variable discount rates (if they are known for the duration of the investment) better reflects the real situation than that calculated from a constant discount rate for the entire investment duration. Refer to the tutorial article written by Samuel Baker[2] for more detailed relationship between the NPV value and the discount rate. For some professional investors, their investment funds are committed to target a specified rate of return. In such cases, that rate of really difficult to do well. An alternative to using discount factor to adjust for risk is to explicitly correct the cash flows for the risk elements using NPV or a similar method, then discount at the firm's rate. What NPV MeansEdit NPV is an indicator of how much value an investment or project adds to the firm. With a particular project, if is a positive value, the project is in the status of discounted cash inflow in the time of t. If is a negative value, the project is in the status of discounted cash outflow in the timeVs in various situations. ExampleEdit A each81.52. Since the NPV is greater than zero, it would be better to invest in the project than to do nothing, and the corporation should invest in this project if there is no alternative with a higher NPV. More realistic problems would need to consider other factors, generally including the calculation of taxes, uneven cash flows, and salvage values as well as the availability of alternate investment opportunities. Common pitfallsEdit - If for example the foregoing: if some risk is incurred resulting in some losses, then a discount rate in the NPV will reduce the impact.. Alternative capital budgeting methodsEdit - while disregarding the absolute amount of money to be gained. - Modified Internal Rate of Return|Modified internal rate of return (MIRR): similar to IRR, but it makes explicit assumptions about the reinvestment of the cash flows. Sometimes it is called Growth Rate of Return. - Accounting rate of return (ARR): a ratio similar to IRR and MIRR ReferencesEdit - ↑ Lin, Grier C. I.; Nagalingam, Sev V. (2000). CIM justification and optimisation. London: Taylor & Francis. pp. 36. ISBN 0-7484-0858-4. - ↑ Baker, Samuel L. (2000). "Perils of the Internal Rate of Return".. Retrieved January 12, 2007.
http://en.m.wikibooks.org/wiki/Principles_of_Finance/Section_1/Chapter_2/Time_Value_of_Money/PV_and_NPV
CC-MAIN-2015-18
refinedweb
498
53.71
The performance model on the JVM is sometimes convoluted in commentaries about it, and as a result is not well understood. For various reasons, some code may not be as performant or as scalable as expected. Here, we provide a few examples. One of the reasons is that the compilation process for a JVM application is not the same as that of a statically compiled language (see [2]). The Java and Scala compilers convert source code into JVM bytecode and do very little optimization. On most modern JVMs, once the program bytecode is run, it is converted into machine code for the computer architecture on which it is being run. This is called the just-in-time compilation. The level of code optimization is, however, low with just-in-time compilation, since it has to be fast. To avoid recompiling, the so called HotSpot compiler only optimizes parts of the code which are executed frequently. What this means for the benchmark writer is that a program might have different performance each time it is run. Executing the same piece of code (e.g. a method) multiple times in the same JVM instance might give very different performance results depending on whether the particular code was optimized in between the runs. Additionally, measuring the execution time of some piece of code may include the time during which the JIT compiler itself was performing the optimization, thus giving inconsistent results. Another hidden execution that takes part on the JVM is the automatic memory management. Every once in a while, the execution of the program is stopped and a garbage collector is run. If the program being benchmarked allocates any heap memory at all (and most JVM programs do), the garbage collector will have to run, thus possibly distorting the measurement. To amortize the garbage collection effects, the measured program should run many times to trigger many garbage collections. One common cause of a performance deterioration is also boxing and unboxing that happens implicitly when passing a primitive type as an argument to a generic method. At runtime, primitive types are converted to objects which represent them, so that they could be passed to a method with a generic type parameter. This induces extra allocations and is slower, also producing additional garbage on the heap. Where parallel performance is concerned, one common issue is memory contention, as the programmer does not have explicit control about where the objects are allocated. In fact, due to GC effects, contention can occur at a later stage in the application lifetime after objects get moved around in memory. Such effects need to be taken into consideration when writing a benchmark. There are several approaches to avoid the above effects during measurement. First of all, the target microbenchmark must be executed enough times to make sure that the just-in-time compiler compiled it to machine code and that it was optimized. This is known as the warm-up phase. The microbenchmark itself should be run in a separate JVM instance to reduce noise coming from garbage collection of the objects allocated by different parts of the program or unrelated just-in-time compilation. It should be run using the server version of the HotSpot JVM, which does more aggressive optimizations. Finally, to reduce the chance of a garbage collection occurring in the middle of the benchmark, ideally a garbage collection cycle should occur prior to the run of the benchmark, postponing the next cycle as far as possible. The scala.testing.Benchmark trait is predefined in the Scala standard library and is designed with above in mind. Here is an example of benchmarking a map operation on a concurrent trie: import collection.parallel.mutable.ParTrieMap import collection.parallel.ForkJoinTaskSupport object Map extends testing.Benchmark { val length = sys.props("length").toInt val par = sys.props("par").toInt val partrie = ParTrieMap((0 until length) zip (0 until length): _*) partrie.tasksupport = new ForkJoinTaskSupport(new scala.concurrent.forkjoin.ForkJoinPool(par)) def run = { partrie map { kv => kv } } } The run method embodies the microbenchmark code which will be run repetitively and whose running time will be measured. The object Map above extends the scala.testing.Benchmark trait and parses system specified parameters par for the parallelism level and length for the number of elements in the trie. After compiling the program above, run it like this: java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=1 -Dlength=300000 Map 10 The server flag specifies that the server VM should be used. The cp specifies the classpath and includes classfiles in the current directory and the scala library jar. Arguments -Dpar and -Dlength are the parallelism level and the number of elements. Finally, 10 means that the benchmark should be run that many times within the same JVM. Running times obtained by setting the par to 1, 2, 4 and 8 on a quad-core i7 with hyperthreading: Map$ 126 57 56 57 54 54 54 53 53 53 Map$ 90 99 28 28 26 26 26 26 26 26 Map$ 201 17 17 16 15 15 16 14 18 15 Map$ 182 12 13 17 16 14 14 12 12 12 We can see above that the running time is higher during the initial runs, but is reduced after the code gets optimized. Further, we can see that the benefit of hyperthreading is not high in this example, as going from 4 to 8 threads results only in a minor performance improvement. This is a question commonly asked. The answer is somewhat involved. The size of the collection at which the parallelization pays of really depends on many factors. Some of them, but not all, include: ForkJoinPool, reverting to ThreadPoolExecutors, resulting in more overhead. ParArrayand ParTrieMaphave splitters that traverse the collection at different speeds, meaning there is more per-element work in just the traversal itself. ParVectoris a lot slower for transformer methods (like filter) than it is for accessor methods (like foreach) foreach, map, etc., contention can occur. Even in separation, it is not easy to reason about things above and give a precise answer to what the collection size should be. To roughly illustrate what the size should be, we give an example of a cheap side-effect-free parallel vector reduce (in this case, sum) operation performance on an i7 quad-core processor (not using hyperthreading) on JDK7: import collection.parallel.immutable.ParVector object Reduce extends testing.Benchmark { val length = sys.props("length").toInt val par = sys.props("par").toInt val parvector = ParVector((0 until length): _*) parvector.tasksupport = new collection.parallel.ForkJoinTaskSupport(new scala.concurrent.forkjoin.ForkJoinPool(par)) def run = { parvector reduce { (a, b) => a + b } } } object ReduceSeq extends testing.Benchmark { val length = sys.props("length").toInt val vector = collection.immutable.Vector((0 until length): _*) def run = { vector reduce { (a, b) => a + b } } } We first run the benchmark with 250000 elements and obtain the following results, for 1, 2 and 4 threads: java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=1 -Dlength=250000 Reduce 10 10 Reduce$ 54 24 18 18 18 19 19 18 19 19 java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=2 -Dlength=250000 Reduce 10 10 Reduce$ 60 19 17 13 13 13 13 14 12 13 java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=4 -Dlength=250000 Reduce 10 10 Reduce$ 62 17 15 14 13 11 11 11 11 9 We then decrease the number of elements down to 120000 and use 4 threads to compare the time to that of a sequential vector reduce: java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=4 -Dlength=120000 Reduce 10 10 Reduce$ 54 10 8 8 8 7 8 7 6 5 java -server -cp .:../../build/pack/lib/scala-library.jar -Dlength=120000 ReduceSeq 10 10 ReduceSeq$ 31 7 8 8 7 7 7 8 7 8 120000 elements seems to be the around the threshold in this case. As another example, we take the mutable.ParHashMap and the map method (a transformer method) and run the following benchmark in the same environment: import collection.parallel.mutable.ParHashMap object Map extends testing.Benchmark { val length = sys.props("length").toInt val par = sys.props("par").toInt val phm = ParHashMap((0 until length) zip (0 until length): _*) phm.tasksupport = new collection.parallel.ForkJoinTaskSupport(new scala.concurrent.forkjoin.ForkJoinPool(par)) def run = { phm map { kv => kv } } } object MapSeq extends testing.Benchmark { val length = sys.props("length").toInt val hm = collection.mutable.HashMap((0 until length) zip (0 until length): _*) def run = { hm map { kv => kv } } } For 120000 elements we get the following times when ranging the number of threads from 1 to 4: java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=1 -Dlength=120000 Map 10 10 Map$ 187 108 97 96 96 95 95 95 96 95 java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=2 -Dlength=120000 Map 10 10 Map$ 138 68 57 56 57 56 56 55 54 55 java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=4 -Dlength=120000 Map 10 10 Map$ 124 54 42 40 38 41 40 40 39 39 Now, if we reduce the number of elements to 15000 and compare that to the sequential hashmap: java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=1 -Dlength=15000 Map 10 10 Map$ 41 13 10 10 10 9 9 9 10 9 java -server -cp .:../../build/pack/lib/scala-library.jar -Dpar=2 -Dlength=15000 Map 10 10 Map$ 48 15 9 8 7 7 6 7 8 6 java -server -cp .:../../build/pack/lib/scala-library.jar -Dlength=15000 MapSeq 10 10 MapSeq$ 39 9 9 9 8 9 9 9 9 9 For this collection and this operation it makes sense to go parallel when there are above 15000 elements (in general, it is feasible to parallelize hashmaps and hashsets with fewer elements than would be required for arrays or vectors).
http://docs.scala-lang.org/overviews/parallel-collections/performance
CC-MAIN-2017-22
refinedweb
1,665
54.12
I wrote this script to teach myself on how to do RSA key generation (public key e and private key d), and how to encrypt and decrypt message mathematically. This tool will also be used as a refresher if I have forgotten how to calculate the RSA mathematics. This learning tool presents how the Euclidean algorithm is used to find the gcd of two values, and to use extended Euclidean algorithm to find private key d. Getting started, and introduction to RSA maths Choose p and q, and find phi(n) and n Get the public key e Given plaintext m, public key e, encrypt m The m has to be between 0 and n-1, so the choice of m cannot be greater than n = p.q. Generate private key d, use extended Euclidean algorithm Below is the instruction on how to find d with extended Euclidean algorithm. First construct a table of 7 columns, t1 and t2 will always be 0 and 1 respectively, see below instruction generated by the learning tool. First row. Next row. Next row, do not stop until r becomes 0. Next row, keep going… Next row, keep it up… Final row, because the next row, the remainder r column will become 0. The learning tool will draw the table and present in your browser, thanks to the plotly module, this table is to match your own hand written table to see if they are the same, if both the tabulated table and your hand written calculation are the same means you have got it right and you have grasped the algorithm. Decrypt the ciphertext since the private key d is generated. Another results, this time the d is a negative number The python codes: from math import sqrt from random import randrange from plotly.graph_objects import Figure, Table # phi(n) = (p - 1) * (q - 1) where p and q are distinct prime numbers. def phi(p, q): return (p - 1) * (q - 1) # Based on the excellent explanation on how to do # extended Euclidean Algorithm: def multiplicative_inverse(e, phi): q_list = list() r1_list = list() r2_list = list() remainder_list = list() t1_list = list() t2_list = list() t_list = list() # extended Euclidean Algorithm assumptions: # s1 = 1, s2 = 0 # t1 = 0, t2 = 1 print("To use extended Euclidean Algorithm draw a table with these columns " "starting from the left: q, r1, r2, r, t1, t2, t, total 7 columns...\r") t1, t2 = 0, 1 t1_list.append(t1) t2_list.append(t2) print(f"These are the assumptions, t1 = {t1} and t2 = {t2}.\r" f"Purpose of finding t2 is to get the multiplicative inverse of e mod phi(n) = {e} mod phi({phi}).\r") # re-arrange r1 and r2, r1 has to be greater than r2 if e < phi: r1 = phi r2 = e else: r1 = e r2 = phi r1_list.append(r1) r2_list.append(r2) print(f"Rearrange e and phi(n) where r1 must be greater than r2.\r" f"In this case r1 is {r1} and r2 is {r2}.\r") print("Calculation stops once r = 0.\r") print("To calculate t, use this formula: t = t1 - t2 x quotient.\n") while True: quotient = r1 // r2 print(f"Write the quotient of r1 / r2 = {quotient} under column q.\r") remainder = r1 % r2 print(f"Write the remainder of r1 / r2 = {remainder} under column r.\r") if remainder != 0: # left shift as long as remainder is not 0 t = t1 - t2 * quotient print(f"Use the formula t = t1 - t2 x q find t: t1={t1} - t2={t2} x q={quotient} = {t}, " f"write this under column t.\n") print("On next row...\r") r1 = r2 print(f"Shift the value of r2 ({r2}) to r1.\r") r2 = remainder print(f"Shift the value of r ({remainder}) to r2.\r") t1 = t2 print(f"Shift the value of t2 ({t2}) to t1.\r") t2 = t print(f"Shift the value of t ({t}) to t2.\r") t_list.append(t) r1_list.append(r1) r2_list.append(r2) t1_list.append(t1) t2_list.append(t2) remainder_list.append(remainder) q_list.append(quotient) else: # found the gcd and y which is also d - # private key of RSA print(f"On next row the column r will be 0, hence we have found the gcd and y.\r") gcd = r2 y = t2 print(f"The gcd({e}, {phi}) = {gcd}, multiplicative inverse of {e} mod {phi} = {y}.\n") break print("Check your browser for the extended Euclidean Algorithm calculation table.\n") fig = Figure(data=[Table(header=dict(values=['q', 'r1', 'r2', 'r', 't1', 't2', 't']), cells=dict(values=[[ql for ql in q_list], [r1l for r1l in r1_list], [r2l for r2l in r2_list], [remainderl for remainderl in remainder_list], [t1l for t1l in t1_list], [t2l for t2l in t2_list], [tl for tl in t_list]]))]) fig.show() # the variables are named explicitly according to lecture notes. if y < 0: print(f"y is negative number: {y}, make it positive by adding {phi} " f"until y becomes the first positive number.\r") while y < 0: y += phi print(f"The y is now: {y}.\n") return gcd, y def is_prime(num): # Reference: # # 1 is not a prime, of course anything less than 1 is not as well. if num <= 1: return False # 2 is a prime. elif num == 2: return True # all even numbers are not prime elif num % 2 == 0: return False else: r = sqrt(num) # 1, 2 and even numbers are validated. # start from 3. x = 3 # try all numbers while x <= r: # if a factor is found then it is not prime # prime is a number divisible by itself and 1 only. # if the number is made from another number it is composite. if num % x == 0: return False # skip to another odd number x += 2 return True # Euclidean Algorithm to find gcd. # gcd(a,b) = gcd(b, a mod b) def gcd(a, b): # gcd(a, b) = gcd(b, a mod b) while b != 0: remainder = a % b # left shift a = b b = remainder # found gcd, as remainder is 0. return a # e which is the public key of RSA, # must be between 0 and phi(n). def is_e_valid(e, phi): if gcd(e, phi) == 1: print(f"The public key e must be between 1 and {phi}, and gcd(e, phi(n)) = 1.\r") print(f"Validated that gcd({e}, {phi}) = 1.\n") return True else: return False # n = p.q, to find modulus n for RSA key generation def modulus(p, q): return p * q # RSA encryption is C = m^e mod n, # RSA decryption is P = C^d mod n. # d is a multiplicative inverse of e mod phi(n). # e.d = 1 mod phi(n). def rsa_crypto(text, key, mod, is_encrypt=1): result = text**key % mod if is_encrypt: print(f"To encrypt {text} use this formula: C = m^e mod n, " f"hence C = {text}^{key} mod {mod} = {result}.\r") else: print(f"To decrypt {text} use this formula: P = c^d mod n, " f"hence P = {text}^{key} mod {mod} = {result}.\r") return result def rsa_operation(start, stop, m): print("Randomly choose p, q and e, p and q are to calculate the modulus n, and e is the public key.\r") print("Publish n and e, but keep p, q and d secret.\r") print("The public key must be between 1 and phi(n), where phi(n) = (p-1).(q-1) " "and p and q are distinct prime numbers.\r") print("d is the private key which is the multiplicative inverse" " of e mod phi(n), e.d = 1 mod phi(n).\n") # Initialize p,q and e to 0. p, q, e = 0, 0, 0 # evaluate if p is a prime number. # evaluate if p and q are different (distinct prime numbers). while p == q: while not is_prime(p): p = randrange(start, stop) # evaluate if q is a prime number. while not is_prime(q): q = randrange(start, stop) n = modulus(p, q) # This is to ensure the message is less than n. # if the n is smaller than m then choose p and q again. if n < m: p = 0 q = 0 euler = phi(p, q) while not is_e_valid(e, euler): e = randrange(1, euler) print(f"Given p = {p} and q = {q} find phi(n) and n.\r") print(f"Formula to find phi(n) = (p-1).(q-1), where p and q are distinct prime numbers.\r") print(f"Hence phi(n) = ({p} - 1) x ({q} - 1) = {euler}.\r") print(f"Find n, where n = p.q, hence n = {p} x {q} = {n}.\n") print(f"Choose e, which is the public key, e must be between 1 and phi(n) = between 1 and {euler}.\r") print(f"Public key {e} is chosen, as it is between 1 and {euler}, " f"and gcd(e, phi(n)) = gcd({e}, {euler}) = 1.\n") print(f"Given the plaintext is m = {m} and e = {e}.\r") print(f"What is the ciphertext of {m}?\n") c = rsa_crypto(m, e, n) print(f"Ciphertext of {m}: {c}\n") print(f"To decrypt {c}, you need d, use extended Euclidean Algorithm to find d.\r") print(f"Use extended Euclidean Algorithm to find this gcd(e, phi(n)) = gcd({e}, phi({n})).\r") print("Finding d, which is the private key...\n") _, d = multiplicative_inverse(e, euler) print(f"d = {d} which is the private key is a multiplicative inverse of {e} (mod {euler}).\n") plaintext = rsa_crypto(c, d, n, is_encrypt=0) print(f"Hence m is {plaintext}, decrypted with private key d: {d}...\n") if __name__ == '__main__': # original message m. m = 10 start = 2 stop = 32 rsa_operation(start, stop, m) Online RSA calculator I was using this RSA calculator to validate the variables of my script.
https://cyruslab.net/2019/12/07/pythonrsa-mathematics-learning-tool/
CC-MAIN-2022-27
refinedweb
1,620
71.65
Thanks for the reply Stephan, So there are basically 2 options Advertising a) Add NameError to Undefs b) Make simpleTraverse raise AttributeError instead I am all for b) because an AttributeError it is, IMO Stefan On Sat, 12 Nov 2005, Stephan Richter wrote: > On Sunday 23 October 2005 03:12, Stefan H. Holek wrote: > > So, is there or would this qualify as a bug? There is a test that > > seems to point to some use with regard to namespaces, but I don't see > > how this wouldn't work just as well with AttributeError. > > I definitely think this is a bug. I guess the | operator should simply also > know how to deal with NameError. Stefan, it would be great if you could fix > this or at least file a bug report. > > Regards, > Stephan > -- > Stephan Richter > CBU Physics & Chemistry (B.S.) / Tufts Physics (Ph.D. student) > Web2k - Web Software Design, Development and Training > _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub:
https://www.mail-archive.com/zope3-dev@zope.org/msg02450.html
CC-MAIN-2017-04
refinedweb
162
71.14
Visual Basic Developer Center | VB Team Blog | How-Do-I Videos | Power Packs | Code Samples | VB Interviews I've mentioned before that you can use XML literals in VB 9 to do text merging so I figured it should be pretty easy to do some mail merging in Word the same way. Word 2007 (and Excel, etc) now uses a standard XML format called Office Open XML to describe documents so I thought this would be the perfect opportunity to try out how to do this with LINQ and XML literals in Visual Basic. What I wanted to do is take all the Customers in the Northwind database who had some orders shipping today and send them thank you letters. Of course, I had to create some new orders first since every order in Northwind was placed before the turn of the century! Anyway, to get started I created a new Word 2007 document with the letter text and some placeholder field names to indicate where I want the data: Then I just saved the Doc1.docx file to my project folder. If we rename this file with a .zip extension we can see that it's just a zip file with a bunch of XML documents inside it. This is how the Office Open XML works. Basically it's a zip package with a bunch of related XML files inside. You can read more about Office Open XML in Microsoft Office here. If we drill down through the zip file we'll see that the text we just typed is located in the \word\document.xml file. If I open this document.xml file in a text editor like notepad, copy all the text into the clipboard, and then paste it into a Visual Basic program it will be inferred as an XDocument object and we can see our text and placeholders in the XML (I collapsed a couple sections at the top and bottom for readability). So what we want to do in our mail merge program is write a query that creates this XDocument for all our customers that have shipping orders and then pops it back into a zip file that Word 2007 can open. There's a namespace called System.IO.Packaging that will help us extract and replace the document.xml with the XDocument we create. But first, let's create the query by connecting our Server Explorer to our Northwind database and then adding a new item to our project and selecting the "LINQ to SQL Classes" template. Then just drag-drop the Customers and Orders tables onto the designer. (I show how to do this in this video). What we want to end up with is a collection of XDocuments above, with our data merged into it. Instead of just creating a collection of XDocuments I also want to capture the CustomerID so that we can use it to create unique file names for our Word documents. So let's create a simple class called Letter that has two properties, CustomerID As String and Document As XDocument. Public Class Letter Private m_doc As XDocument Public Property Document() As XDocument Get Return m_doc End Get Set(ByVal value As XDocument) m_doc = value End Set End Property Private m_ID As String Public Property CustomerID() As String Get Return m_ID End Get Set(ByVal value As String) m_ID = value End Set End Property End Class Now we can write our query to create a collection of these classes. Dim db As New NorthwindDataContext Dim letters = _ From Order In db.Orders _ Where Order.OrderDate IsNot Nothing AndAlso _ Order.ShippedDate IsNot Nothing AndAlso _ Order.ShippedDate.Value.Date = Date.Today _ Let OrdDate = Order.OrderDate.Value.ToShortDateString _ Let ShipDate = Order.ShippedDate.Value.ToShortDateString _ Select New Letter With { _ .CustomerID = Order.Customer.CustomerID, _ .Document = <?xml version="1.0" encoding="UTF-8" standalone="yes"?> rest of doc omitted for clarity ...} We're selecting the CustomerID and the XML literal with our embedded expressions in place of the placeholder fields I created in the document. I omitted the rest of the XML literal in the query above for clarity. All we need to do is run through the literal and replace all the placeholder fields with embedded expressions from our query. For instance, here's a snapshot of the body of our letter : ...AA2EC><%= OrdDate %><><%= ShipDate %></w:t> </w:r>... Now that we have a collection of our Letter objects, we need to create the Word document by making a copy of our original document (which remember is just a .zip file) and replacing the \word\document.xml file in that package. You can also create packages from scratch but then you have to create a relationship file that describes the relation of all the files in the package and it can get tricky. It's easier to just make a copy of the original Word docx file in our case and just replace the part we modified. The key to writing the document back properly is getting the content type right when we call CreatePart on the Package object. The Package object lives in the System.IO.Packaging namespace.) For Each letter In letters Dim customerFile = letterDir & letter.CustomerID & ".docx" Console.WriteLine(String.Format("Creating letter {0}", letter.CustomerID)) My.Computer.FileSystem.CopyFile(sourceFile, customerFile, True) Using p As Package = Package.Open(customerFile) 'Delete the current document.xml file p.DeletePart(uri) 'Replace that part with our XDocument Dim replace As PackagePart = p.CreatePart(uri, contentType) Using sw As New StreamWriter(replace.GetStream()) letter.Document.Save(sw) sw.Close() End Using p.Close() End Using This creates a directory of our letters all nicely mail merged with the customer and order data that met our criteria in the Where clause of the letters query. If we open one of the documents we'll see the data properly merged into the letter. I've attached the complete example to this post. Have fun exploring the Office Open XML format because there's just so many things you can do with it especially combined with LINQ, XML literals and Visual Basic! Enjoy! If you would like to receive an email when updates are made to this post, please register here RSS Nice sample! Did you know you could've used ContentControls and custom XML? It would have saved you the trouble of recreating the whole document.xml part by just having to generate the custom XML data. But anyway, you've shown a great way to make use of the LINQ to XML features in VB9. I found this article to be very interesting back in february: Have a nice day! This is a great example, thank you for sharing it with us! This new open office XML format certainly opens up a lot of possibilities. Ooooh, a poyple background :) Pingback from Hi DMurillo, It really was no trouble at all to create the entire document, I just pasted it into the editor and plopped my embedded expressions into it, but I also like the approach of just stuffing plain old xml into the package too, that would have worked just fine for my scenario above. The thing I like better about generating the entire letter is that it gives you an easier (IMHO) way to completely change the text of the letter for each customer if you want. Thanks for the link, I'm just starting to dig into this stuff! Cheers, -B I'll be speaking at the Victoria Code Camp on January 26th so if you're in the area and you have nothing Hi Beth, Great as usual! How do we manage a document that has an image, simply replacing the document.xml does not make the image available. Casey Though I might use a customXML part and modify you code but .... 1. When I run the code below i always get "a corrupted file" message when I open the doc,in word, although I can see the changes have been made sucessfuly after pressing "continue" 2. Stepping thru the code I can see that the file is corrupted when the part is deleted, and the _rels folder and contents have also been deleted What to do ? Casey Code- Dim contentType = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml" Dim uri As New Uri("/customXml/item1.xml", UriKind.Relative) Using p As Package = Package.Open(customerFile) 'Delete the current customxml.xml file p.DeletePart(uri) 'Replace that part with our XDocument Dim replace As PackagePart = p.CreatePart(uri, contentType) Using sw As New StreamWriter(replace.GetStream()) ' sw.Flush() letter.Element.Save(sw) sw.Close() End Using p.Close() End Using Hi Casey, I've never tried it but I think you need to add the image to the media subfolder and then add it to the document.xml.rels file. Here's a good document to read: HTH, H Beth, As per the previous posts replacing the whole document.xml meant that images and formatting where lost. Using a custom xml part means a smaller chunk of xml to handle and the rest of the doc is undisturbed. Finally found some (simple) code that does the trick, courtesy pf Steve Hansen;- Casey. For Each letter In letters Dim customerFile = letterDir & letter.SupplierID & ".docx" 'Console.WriteLine(String.Format("Creating letter {0}", letter.SupplierID)) My.Computer.FileSystem.CopyFile(sourceFile, customerFile, True) Dim uri As Uri = New Uri("/customXml/item1.xml", UriKind.RelativeOrAbsolute) Dim doc As Package = Package.Open(customerFile) Dim part As PackagePart = doc.GetPart(uri) Dim outputStream As Stream = part.GetStream(FileMode.Create, FileAccess.ReadWrite) Dim sw As StreamWriter = New StreamWriter(outputStream) sw.Write(letter.Document.ToString) sw.Flush() sw.Close() doc.Close() Before I post about DevTeach Day 3 I thought I'd report back how the LINQ session I did yesterday evening. Great! I was looking for this capability to automate Word in VB for sometime now. This was very, very easy in VFP. hi Beth I tried this sample but I have problem. my microsoft office word font and allignment basic settings dont change. so I have to change these settings after word document written. do you have other examples inculing more tables in a dataset? Last month when I was in Redmond I mentioned to a colleague that I really liked the Open XML format that About a month ago the OpenXML SDK 1.0 (June 08 update) was released . The SDK provides strongly typed I've re-written this process to extract the document.xml file from the docx. The problem is, when I replace the docx field delimiters with the ASP.Net field delimiters, the xDocument escapes the < and >. I use the following function. The function works fine, but after it returns the xDocument show the < and > escaped. Any thoughts? Private Function FixDelimeter( _ ByRef xElems As IEnumerable(Of XElement) _ ) As Boolean Dim pXElem As XElement Try For Each pXElem In xElems pXElem.Value = Regex.Replace(pXElem.Value, "«", "<%= pDataRow(""") pXElem.Value = Regex.Replace(pXElem.Value, "»", """) %>") If pXElem.Elements.Count > 0 Then FixDelimeter(pXElem.Elements) End If Catch ex As Exception Throw Finally pXElem = Nothing End Try End Function Hi Joe, I think you are confusing scripting with XML Literals. XML literals are COMPILED into your application when it is built, you cannot evaluate them at runtime like this. You can however write a LINQ query to select the nodes that you want to replace. Thank for you example i am finding it very usefull for creating standard letters. How would you manage a blank or null values in a full customers address without leaving a blank line in an address Full Address Street Post Town Region Post Code Were the post town is missing avoide the address appearing like : But to appear like : thanks W
http://blogs.msdn.com/bethmassi/archive/2007/12/06/mail-merging-with-word-and-linq-to-xml-in-vb.aspx
crawl-002
refinedweb
1,968
64.51
😜 Yo! A couple of days, I was building a simple app that takes data from an API and displays them on the screen. A simple app though. Then I needed to add some height to my appBar. Well you might suggest ... toolbarHeight: 100.0, title: Text('Yo! Title here'), ... but what if I want to customize my title, add some color, and use the properties across other screens well I don't want to go through the ctrl c & ctrl v kinds of stuff. Here is what I did - Created a widget directory inside my lib folder - Created a new custom_appBar.dart file import 'package:flutter/material.dart'; class MyAppbar extends StatelessWidget with PreferredSizeWidget { @override final String title; final Size preferredSize; MyAppbar(this.title, {Key key}) : preferredSize = Size.fromHeight(100.0), super(key: key); @override Widget build(BuildContext context) { return AppBar( title: Text(title, style: TextStyle(color: Colors.white) ), backgroundColor: Colors.white38, ); } } My new MyAppbar class extend the statelessWidget. you also noticed I have with PreferredSizeWidget right? Yea! this is because the Scaffold takes in a PreferredSizeWidget and not the AppBar class directly. Then I set my constructor like so ... MyAppbar(this.title, {Key key}) : preferredSize = Size.fromHeight(100.0), super(key: key); ... Lastly, my build method returns the AppBar class and there I can now set my AppBar properties Now I can import and reuse my newly customized MyAppbar everywhere on my app ... appBar: MyAppbar('Title goes here!'), ... I also recommend checking this medium article too 👍 Top comments (0)
https://dev.to/oyelowotobiloba/creating-a-custom-appbar-mn9
CC-MAIN-2022-40
refinedweb
250
60.61
Data Lost on scene gameobject when create a prefabs This is a new issue left after #280 fixed , because the origin 280 issue already fixed, I think it's more proper to create a new issue for it. Version : 1.0.6.1 Beta - Prefab Modification Hotfix. Here is the steps: - Create a new Scene. - Create a new Script: public class TestOdin : SerializedMonoBehaviour { public DataBase data; } public abstract class DataBase { public GameObject go; } [Serializable] public class Data1 : DataBase { } - Create an empty GameObject1,add the Script "TestOdin" to it. - Create another empty GameObject2, assign it to the field "go" at GameObject1. - Drag GameObject1 to project window to create a prefab. - Click the GameObject1 at scene,the field "go" lost it's reference. Thanks for reporting this one. And sorry for the inconvenience on this issue. But we'll have to put it on hold for a bit until our prefab-modification guru comes back and saves the day, which he will in 2 months time. A quick workaround for you could be to simply make a clone of the object, before making a prefab and use that to assign the lost scenes references. To give a status update on this, I've had a look at it, and it's actually an edge case known to me, that is related to how Unity handles prefab creation - without ever telling us that it happens. I am not certain a fix for this is possible, but I will leave the issue around and dedicate some time to really give it a solid go before I determine whether or not a fix is possible. Thanks for your reply. well, it's sad to know that :( We make a Visual scripting system base on Odin and Abstract class(Glad to share to 'make with odin' in the future), and we use the system to build games. We can't use prefabs as we expected because of this issue, reassign the lost data always annoying. But I also understand the trouble you meet now, so... just let me know if you finally find out a solution. Good luck and thanks again..
https://bitbucket.org/sirenix/odin-inspector/issues/293/data-lost-on-scene-gameobject-when-create
CC-MAIN-2018-43
refinedweb
355
70.23
by Sir1Afifi via /r/csharp Month: June 2015 How to process text file concurrently? I am new to concurrent programming and I'm having a hard time wrapping my head around all the different options in C# (Rx, TPL, TPL Dataflow, Threads + Threadpools, etc.). Basically the problem I'm trying to solve is performing validation on a very large file line by line as quickly as possible. The file is […] Quick Tip : Display the file version of your application in C# Being a typical .Net Developer, how much should I work on my Azure skills? I have an MCSD Certification in Custom Web Applications and have been using C# for 7+ years. I am noticing a trend where more and more developers are being brought in to do DevOps work, which can range from build and release management tasks, to systems administration in Azure. I love to code, and don't […] Can’t find the database that EF created Comfortable with C++ but moving to C#, any good resources for those who already know the basics? How to securely store passwords and beat the hackers What are your thoughts on using an interface that is never explicitly used by client code? As I'm developing code, I'll write client code to work against interface ISomething. Maybe it's a dependency that needs to be injected, or maybe instantiation is complicated and I want to wrap it in a factory or something. Later after reconsidering the code I realize that my needs weren't as complex as I thought and […] Thoughts? Martin Fowler’s installment on collection pipelines vs. loops. [WPF] TreeView data binding – Accessing Object inside of a Property? I am trying to bind values from a list of objects to a TreeView, but can't seem to figure out how to bind past the first level. The Class is as follows: public class NodeObj : INotifyPropertyChanged { public int DBID { get; set; } public string sysName { get; set; } public List<ReleaseSites> ReleaseSites […]
http://howtocode.net/2015/06/page/2/
CC-MAIN-2018-39
refinedweb
331
59.74
Connect an ASP.NET application to Azure SQL Database There are various ways to connect to databases within the Azure SQL Database service from an application. For .NET apps, you can use the System.Data.SqlClient library. The web app for the university must fetch and display the data that you uploaded to your SQL database. In this unit, you will learn how to connect to a database from a web app and use the System.Data.SqlClient library to process data. System.Data.SqlClient library overview The System.Data.SqlClient library is a collection of types and methods that you can use to connect to a SQL Server database that's running on-premises or in the cloud on SQL Database. The library provides a generalized interface for retrieving and maintaining data. You can use the System.Data.SqlClient library to run SQL commands and transactional operations and to retrieve data. You can parameterize these operations to avoid problems that are associated with SQL-injection attacks. If an operation fails, the System.Data.SqlClient library provides error information through specialized exception and error classes. You handle these exceptions just like any other type of exception in a .NET application. The System.Data.SqlClient library is available in the System.Data.SqlClient NuGet package. Connect to a single database You use an SqlConnection object to create a database connection. You provide a connection string that specifies the name and location of the database, the credentials to use, and other connection-related parameters. A typical connection string to a single database looks like this: Server=tcp:myserver.database.windows.net,1433;Initial Catalog=mydatabase;Persist Security Info=False;User ID=myusername;Password=mypassword;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30; You can find the connection string for your single database on the Connection strings page for your database in the Azure portal. The following code example shows how to create an SqlConnection object: using System.Data.SqlClient; ... string connectionString = "Server=tcp:myserver.database.windows.net,..."; SqlConnection con = new SqlConnection(connectionString); The database connection isn't established until you open the connection. You typically open the connection immediately before you run an SQL command or query. con.Open(); Some databases only support a finite number of concurrent connections. So, after you finish running a command and retrieving any results, it's good practice to close the connection and release any resources that were held. con.Close(); Another common approach is to create the connection in a using statement. This strategy automatically closes the connection when the using statement completes. But you can also explicitly call the Close method. using (SqlConnection con = new SqlConnection(connectionString)) { // Open and Use the connection here con.Open(); ... } // Connection is now closed Define an SQL command or query Create an SqlCommand object to specify an SQL command or query to run. The following example shows an SQL DELETE statement that removes rows for a given customer from an Orders table. You can parameterize commands. This example uses a parameter that's named CustID for the CustomerID value. The line that sets the CommandType property of the SqlCommand object to Text indicates that the command is an SQL statement. You can also run a stored procedure rather than an SQL statement. In that case, you set the CommandType to StoredProcedure. SqlCommand deleteOrdersForCustomer = new SqlCommand("DELETE FROM Orders WHERE CustomerID = @custID", con); deleteOrdersForCustomer.CommandType = CommandType.Text; string customerID = <prompt the user for a customer to delete>; deleteOrdersForCustomer.Parameters.Add(new SqlParameter("custID", customerID)); The final parameter to the SqlCommand constructor in this example is the connection that's used to run the command. The next example shows a query that joins the Customers and Orders tables together to produce a list of customer names and their orders. SqlCommand queryCmd = new SqlCommand( @"SELECT c.FirstName, c.LastName, o.OrderID FROM Customers c JOIN Orders o ON c.CustomerID = o.CustomerID", con); queryCmd.CommandType = CommandType.Text; Run a command If your SqlCommand object references an SQL statement that doesn't return a result set, run the command by using the ExecuteNonQuery method. If the command succeeds, it returns the number of rows that are affected by the operation. The next example shows how to run the deleteOrdersForCustomer command that was shown earlier. int numDeleted = deleteOrdersForCustomer.ExecuteNonQuery(); If you expect the command to take a while to run, you can use the ExecuteNonQueryAsync method to perform the operation asynchronously. Execute a query and fetch data If your SqlCommand contains an SQL SELECT statement, you run it by using the ExecuteReader method. This method returns an SqlDataReader object that you can use to iterate through the results and process each row in turn. You retrieve the data from an SqlReader object by using the Read method. This method returns true if a row is found and false if there are no more rows left to read. After a row is read, the data for that row is available in the fields in the SqlReader object. Each field has the same name as the corresponding column in the original SELECT statement. However, the data in each field is retrieved as an untyped object, so you must convert it to the appropriate type before you can use it. The following code shows how to run the queryCmd command that we illustrated earlier to fetch the data one row at a time. SqlDataReader rdr = queryCmd.ExecuteReader(); // Read the data a row at a time while (rdr.Read()) { string firstName = rdr["FirstName"].ToString(); string lastName = rdr["LastName"].ToString(); int orderID = Convert.ToInt32(rdr["OrderID"]); // Process the data ... } Handle exceptions and errors Exceptions and errors can occur for various reasons when you're using a database. For example, you might try to access a table that no longer exists. You can catch SQL errors by using the SqlException type. An exception might be triggered by various events or problems in the database. An SqlException object has a property Errors that contains a collection of SqlError objects. These objects provide the details for each error. The following example shows how to catch an SqlException and process the errors that it contains. ... using (SqlConnection con = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand("DELETE FROM ...", con); try { con.Open(); command.ExecuteNonQuery(); } catch (SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { Console.WriteLine($"Index # {i} Error: {ex.Errors[i].ToString()}"); } } } Need help? See our troubleshooting guide or provide specific feedback by reporting an issue.
https://docs.microsoft.com/en-us/learn/modules/develop-app-that-queries-azure-sql/4-connect-aspnet-to-azure-sql
CC-MAIN-2021-43
refinedweb
1,076
50.23
[Solved] QML color TextArea Background Hi everyone. I am starting a new project with QML and I ran into this problem. In my application (running on the Desktop) I have several TextAreas. I am using them because of the built-in scroll functionality and I would like the application to look consistent. Most TextAreas are "readOnly: false", but I also need one TextArea that is "readOnly: true". I would like to visually distinguish this by changing the background color to gray when the user cannot edit the text. Edit: I am aware of the enabled attribute. Unfortunately setting "enabled: false" makes it impossible for the user to select text. It would be nice if the user could still select text, therefore I am using the readOnly attribute. So far I have tried using the backgroundVisible attribute together with a gray Rectangle behind the TextArea. This did not give any changes no matter what value backgroundVisible has. Maybe I am using it wrong/misunderstanding what the attribute does? Also I tried to set the opacity of the TextArea, but I cannot manage to set the opacity of the text separately. Is there a way? I have seen that there is a style attribute available. I am a bit reluctant to use it and not even sure how to use it. Would this be the way to go? Thank you very much for your help. As I know Qt 5.1 Qt Quick doesn't support change style for TextArea. But You can change background color in Qt 5.2 please follow this "link": Sample Qml: @TextArea { style: TextAreaStyle { backgroundColor: "#eee" } }@ Ok, very interesting. I guess I will have to consider using Qt 5.2 then instead of 5.1. Thanks a lot for the hint! Your welcome! Please add [Solved] to the title. It may help someone with similar issue. I was excited to get this working using Qt 5.2 BETA, but unfortunately, this does not seem to work for me. The following is the simple code snippet I am using under Qt 5.2. Any help would be much appreciated. import QtQuick 2.1 import QtQuick.Controls 1.1 import QtQuick.Controls.Styles 1.1 Rectangle { width: 800 height: 600 gradient: Gradient { GradientStop { position: 0.0; color: "lightsteelblue" } GradientStop { position: 1.0; color: "blue" } } TextArea { width: 100 height: 100 // This gives me error "TextAreaStyle" is not a type style: TextAreaStyle { backgroundColor: "#eee" } } } It is not included in beta! You need to wait for the next release... Ooops! It should work according to the documentation. It must be a bug. Can you report it? It's not, just check the git repository (it was added a few days AFTER beta) ahh, My mistake, :) There is another simpler way though. Just set the "backgroundVisible" property to false and place an image or a colored rectangle as the parent of the TextArea. That should work even in 5.2.
https://forum.qt.io/topic/33410/solved-qml-color-textarea-background
CC-MAIN-2018-13
refinedweb
487
77.64
1. Metal Sensor 6.5 Ultrasonic Sensor With Arduino 7. PWM 7.1 PWM Basics 7.2 Arduino's PWM Support 7.3 Controlling LED Intensity through PWM 8. Working With Relays 8.1 Relay Basics 8.2 Arduino with Relays 8.2.1 Relay Control Using Transistor 8.2.2 Relay Control using Optocoupler 9. Working With Motors 9.1 DC Motor Control using Transistors 9.2 Controlling Motors Through Relay 10. Wireless With IR Sensor 11. Conclusion Arduino is a great embedded platform for prototyping your hobby projects. It is really easy to learn, simple yet efficient and powerful. Arduino Boards are powered by Atmel family Microcontrollers. The board as several features which are so crucial to many hardware applications which includes Digital pins,Ability to drive low power motors, PWM, ability to connect to other devices using Serial Communication, onbard A/D converter which can directly read sensor values and many more. Even though the platform is claimed to be only for prototyping, I have personally used the board for many production projects and it works quite well in those works too. In an era of Internet Of Things where main focus of development in embedded system is being shifted entirely towards developing services for the devices. However understanding and learning the hardware capabilities of these devices, ways of controlling displays, indicators, buzzers, actuators, working with sensors also plays an important role. It helps once build a conceptual framework of the capabilities of such devices which makes it easy to integrate such boards over IoT. Even though Arduino has been around for some good time and has had gone through several changes, the core features remains same. There are many blogs and articles around that explains the working of Arduino with different hardwares, I found not a single web entry that provides an insight of the overall hardware features of the platform. Therefore for a non embedded developer( non Electronics developer), learning the hardware part becomes a real stiff learning curve. In this Tutorial I would try to provide an insight into overall hardware capabilities of Arduino with most common hardware required to develop real time projects with the platform. This tutorial is aimed at developers who are well versed with progrmming but are trying to start with embedded platform in general and Arduino in particular. Choice of Arduino is obvious because of it's simplicity which makes Arduino learning real simple. For most of the connections, I have preferred connecting the hardware with Pin connectors and bread boards so that those who are not comfortable with Soldering and PCBs can find it easy to follow. First download latest Arduino IDE from Arduini's Official Software Download Site. Windows user will be able to download an Installer. The installer has a FTDI usb driver along with the IDE itself. Prefer to install the USB driver. This is essential. Without USB driver your IDE can not communicate with the Arduino Device. Following is the Pin Description of the device that I am using. Figure 2.1: Arduino Diecimilia/Duemilanova with Pin Levels Once the software is installed, plug Arduino's USB cable to your laptop. You will see a notification in tray "installing driver". Once driver installation is successfull Open Device manager ( start->right click on Computer icon->Properties->Device manager). Figure 2.2: Device Manager After Arduino is Plugged in. In the Ports(Com and LPT) section you see USB serial port. In case of Arduino Uno R3, you will see Arduino Uno marker along the port. When you plug out the cable, you won't find the port anymore. So this is the port at which your Arduino device is connected. If you have connected your device for the first time, you will also notice that the LED near digital pin 13 is blinking. Most of the Arduino boards are preloaded with a blink program which blinks the LED connected to pin 13. Before starting with our coding, we need just couple of more steps to setup IDE with the board. Open the IDE. Tools->Boards select the board you are connecting as shown in figure below. Figure 2.3: Arduino Board Selection Once the board is selected, you need to set the correct serial port as you have figured out from figure 2.2 Figure 2.4: Selecting USB Serial Port in IDE Before we go into programming the boards we will learn some simple basics of Arduino C programming. Following is the basic structure of the Arduino program. An Arduino C program is also known as a sketch. void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } setup() is executed once ( when you reset the device, or restrat the device, or plug in the USB cable ). loop() setup() loop() runs continuesly. Main logic must be implemented inside loop. Arduino Duemilanova/Diecimilia/Uno R3 ( from here onwards will refer simply as Arduino) board has 14 Digital IP pins. Each pin can be program separately. A Pin can be in with OUTPUT mode or input mode which needs to be specified in setup using pinMode(PIN_NO,OUTPUT) or pinMode(PIN_NO,INPUT); pinMode(PIN_NO,OUTPUT) pinMode(PIN_NO,INPUT); Input mode is used when you connect a switch to a pin and want the pin to read the status. These digital pins in input mode can only recognize logic level input like 0 and 1. PIN_NO ranges from 0-13 depending upon the pin you are programming. you can write logical output in a pin in OUTPUT mode or can read the the value at the pin ( 1 or 0) usingdigitalWrite(PIN_NO,HIGH)/digitalWrite(PIN_NO,LOW) and int n=digitalRead(PIN_NO)respectively. digitalWrite(PIN_NO,HIGH)/digitalWrite(PIN_NO,LOW) int n=digitalRead(PIN_NO) Few pins in Digital ports are marked as PWM( like 10 and 11 in figure). They can be used to generate gate pulse of different duty cycle. PWm pin can be programmed to produce perfect square gate pulse of specific duty cycles using analogWrite(PIN_NO,byteValue) Where byteValue can be betweet 0 to 255 where 255 represts highest or 100% duty cycle. PWM pins can be used to control DC motors precise speed control or controlling intensity of electrical bulbs through MOSFETs/IGBTs and so on. analogWrite(PIN_NO,byteValue) Arduino has 6 analog read pins (0 to 5) opposite to the digital ports. These are input pins which are connected to 10 bit ADC. Sensors can be directly connected to these pins. Arduino can read the voltage at the pin with intvalue=analogRead(ANALOG_PIN_NO) value=analogRead(ANALOG_PIN_NO) The software comes with a Serial library, through which other programs can communicate with Arduino using Serial communication. Arduino IDE also comes with a Serial Monitor through which one can test the serial communication. For initializing serial communication, in the setup function one needs to initialize the serial communication object with Serial.begin(BAUD_RATE) Baud Rate varies in the multiples of 96200.Serial.print("msg"),Serial.println("msg"), Serial.write(someVariable) are common functions by means of which the board can write data on the serial port which can be read by any external program capable of communicating with the device over serial port. Serial.begin(BAUD_RATE) Serial.print("msg") Serial.println("msg") Serial.write(someVariable) int v=Serial.read() is used to read data from Serial port written by other programs on serial port. int v=Serial.read() delay(delayInMilli); is used to make the next instruction wait for delayinMilli period of time which is specified in milliseconds. delay(delayInMilli); Most of the basic hardware Input and output can be performed using above commands. I request you to please go through My Arduino Getting Started Tutorial more more information about Arduino C programming and Serial Communication basics. An embedded system may need to drive several loads like motors, trigger relays, provide powers for sensors and so on. Therefore understanding how much power the device draws and how much power it is capable to provide to provide to other peripheral hardware unit is very important aspect of embedded system. In this section we will learn about power management of Arduino. Arduino's operating voltage is 5v as with most of the embedded system devices and boards. It can be powered up either through a USB or through an External power source. Arduino board has a voltage regulator that can produce 5v regulated supply to the board. External power source's voltage is regulated through this. As with any voltage regulator, the unit needs higher voltage input to produce 5v output. Hence when Arduino is to be powered by external voltage source like battery, it has to be a 9v power supply. Figure 3.1 Shows different ways to power up Arduino board. Figure 3.1: Different ways of Powering Up Arduino You can use a 9v Adapter to convert AC to 9V DC directly and give input to Arduino through it's power jack. If you want the device to be completely battery driven, you can use a Connector for 9V battery and can put that in power port. Arduino also provides two pins by label Vin and Gnd which just preceeds the analog ports. You can connect your 9V battery with Arduino using these two pins with the help of battery connecting wires. However you have a Jumper in the board just near the USB plug which needs to be set to USB if you are using USB to power up Arduino or in Vin if you are using external power. Jumper is shown in figure 3.2. Figure:3.2 Jumper Setting for Power Selection When you look at Arduino board straight as in figure 3.1, you can see a set of pins grouped togather which are RST, 3V, 5V, GND, GND, Vin. I call the pins togather as Power Port. The 5v and 3v pins are sometimes also referred to as VCC pins as they are source to other devices. For example if you want to connect a sensor with Arduino ( form example LM 35), it needs 5 v to operate. This voltage is provided by 5v pin. Devices like ZigBee operates at 3V. Such devices can be powered up by 3v VCC pin. Current drawing capability of Vcc pins are 200mA. Arduino also has 14 digital IO pins. When provided with HIGH logic level, these pins produces 5v output. However current drawing capability of digital IO pins are as low as 40mA. Due to very low current drawing capability these pins can not drive any load. Even LED is difficult to drive with this current. Hence digital pins can be used to control other devices only through a switching electronic device like an Optocoupler ( MCT2E) or a transistor (Digital Switching of Devices will be explained later). It is important to note that digital pins suopports reading voltage just like controlling devices. When a digital switch is connected to digital I/O pins whose's logic level needs to be read by the pins, the pin is said to be acting like a Sink. Care should be taken such that sum of current being sinked to the device through all I/O pins must not exceed 100mA. hence it is always advisable to connect a switch output to digital pin with current limiting resistor. The maximum current that can be supplied to any pins is about 40mA. So if you connect a 5v-1A power supply to any of the analog pins, even though the voltage is within the range, over current will literally fry your microcontroller. Therefore when you work with Arduino, ample care must be taken to understand the voltage and current specification of the devices and limit input current whenever you use any pins ( analog/digital) as Sink by connecting the source through appropriate current limiting resistor. From the above discussion we derive following important points: 1) Arduino 5v, 3v Vcc pins can be used directly to drive low current loads( like LED, LCD, 5V DC motors, Sensors) 2) Arduino digital pins are not sufficient to drive even low current loads 3) Arduino digital pins can be used to provide 5V switching voltage to digital switches. Higher current rating devices can be switched by Arduino using a coupler like Optocoupler or Transistor. 4) Arduino pins as Sink has very low current specifications. Therefore high current source must not be connected to any of the pins configured as sink. Use current limiting resistor with the pins as Sink. With this knowledge we are literally ready to move ahead with our Arduino development. Often in your DIY projects you need indicators. Say for instance when you build a fire alarm system, you sensor may monitor heat and light intensity and when the value exceeds threshold value, you want it to trigger an alarm. You may also want to indicate that a specific device is active through a LED. LEDs and Buzzers are most common indicators that are part of almost all DIY projects. Because of the ease of use, cost effectiveness, hardware developers are fond of these two components. Switches plays an important role for triggering an external event for the device. For example you want a motor to start: press a switch, let the board read the event and turn the motor on. You want to turn on a light by pressing a switch: use simple switches. So indicators and switches are most basic, common and most widely used components with any hardware projects. They are cheap, they are efficient and they are effective. Hence in this section we will discuss about using using LEDs and Switches with Arduino. Light Emitting Diode or LED's are most common indicators for any electronic devices from an adapter to laptop. It makes it visible for the user that certain part of the system is functioning well. LEDs are available in different colors and current specification. Current specification of LEDs varies from 30mA to several amperes. Because LEDs draws current, it is also treated as current load. LEDs can operate between 1.2V to about 24v depending upon it's specification. Arduino board has a built in LED which can be controlled by Pin 13 of Digital pins. In order to control any device through Arduino digital IO pins, we must configure the pin as OUTPUT pin and make it high using digitalWrite(13,HIGH). digitalWrite(13,HIGH). Simple Sketch for blinking can be found in Arduino example: File->Examples->Basics->Blink. For continuity of the discussion, I am simply dumping the code here. } This will make your LED associated with pin 13 switching on and off in turns in every 1 sec. Turned on state of the LED can be seen in figure 4.1. Figure 4.1: LED Connected to Pin 13 The Onboard LED is fine, it needs no circuit connections. But what about connecting an external LED and controlling it with digital pins. As digital pins may not provide enough current for LED, we need the LED to be drawing current from a source which can supply enough supply. So we will connect the Anode of the LED ( the longer leg) with Vcc 5v of Arduino. But if we connect the cathod ( smaller leg) directly to ground, firstly the we can not control the LED as we can not control Vcc pin. So we connect LED's cathod to Emittor of an NPN transistor ( I have used BC 548, you can use any other transistor of NPN type). Transistor's collector is grounded. Though there is no resistor with LED in 4.2 a), I advise you to connect the LED with BC548 with a 100Ohm resistor. It limits the current and prevents the LED being fried up. Transistor's base is connected to any of Arduino's digital i/o pin ( say pin 12) through a bais resistor R2(100/470 ohm). When the pin is HIGH, transistor gets base voltage which completes transistor circuit and LED is grounded through the transistor. When the pin is LOW, transistor does not get forward bais voltage so is turned off. Thus LED's ground pin is not connected to LED. Hence it is turned off. You can actually take a 3 pin connector, put the transistor in it and connect with it's wires. You can also make the connection in breadboard if you so wish! You can now use the code listing of 4.1 to perform the experiement. Just change Pin 13 to pin 12. Alternatively you can also add pin 12 as digital output pin and control external LED with on board LED. 4.2 b) Shows glowing of LED. C) Thransistor BC 548/547 Pin Out Figure 4.2: Connecting External LED With Arduino For your convenience, I have also put up an independent image showing exactly this in 4.3. Figure 4.3: Closer Look At The Connection Just like LED, Buzzer is also an output component. There are many different types of buzzer out of which Pizeo electric buzzers are most common. But unlike LEDs buzzer's current requirement is very low. It can operate in current as low as 10mA. Therefore we can connect the buzzer directly with a digital pin and Arduino's ground. You can connect the buzzer with Pin 8 ( Try to avoid a pin which is marked as PWM) and done. Use the code listing of 4.1 to turn on and off the buzzer in alternative seconds. Do not forget to change the pin number to the buzzer pin you have connected the buzzer with. Buzzer will either come with two wires or two pins. If the buzzer has two pins, the longer leg is anode and must be connected to the digital pin and the shorter leg is cathod which must be connected to ground. If the buzzer has wires ( as in figure 4.4) then RED wire is positive and blue/black wire is ground. Figure 4.4 Shows the Buzzer Connection with Arduino. Figure 4.4 Arduino With Buzzer Needless to say that there are several Switches available. The one we would experiement with is a Push button or Push Switch. It remains on till you push the button and becomes off when you leave it. You would switch on a LED with push button click. Push switches have four legs, which provides two pair f switching poles. Figure 4.5 b) shows how the pins are paired. So while switchin a single device with a switch ( which we generally will do), select either pair A with B or C with D. Note A , C and B,D are interchangable. Circuit diagram of the Switch with LED is shown in Figure 4.5 A). LED is given positive voltage through Arduino 5v through a resistor. The cathod is connected to one pole of the switch and another pole of the same pair is connected to ground. So when switch is pushed, LED's circuit is complete and it glows. When switch is released, LED's circuit is broken and it is turned off. We do not need any coding for this experiement. The result can be seen from figure 4.6. C) Physical Connection 4.5 Switch With Arduino 4.6 Result of Switch Experiement LCD's are most common output devices for embedded system. From Beverage Vending machine to handheld ticket printer to hotel billing system, you see the display with many embedded system. There are several displays which are commonly used. Most common displays are: LCD Displays, Graphic Displays, Seven Segment Displays and many more. Duel Line LCD displays are most common device that is used with embedded system. That is because embedded system functionalities are generally restricted. So 2 Line display is sufficient to display most of the things. Here I am going to show you how to work with display in Arduino. LCD is a 16 pin device which operates at 5V. Arduino's 5V Vcc is sufficient to power LCDs. However LCDs don't come with pin headers which makes it difficult to work without Soldering. However we have a way out for every such problem. Look at figure 5.1 c). This is a standard Multi pin Connector. 8-Multi pin Connectors are available in themarket for about $.5-$1. You can get two 8-pin connectors and put the male pins in the LCD and the respective female socket's pre soldered wires go to Arduino pin. LCD's needs two VCCs: One for lighting up front characters and another one is for backlight which is optional. Figure 5.1 A) Shows the Connection Table. LCD pins 11,12,13,14 are the data pins which should be connected to Arduino's digital I/Os. RW' should be grounded for enabling the write operation. Enable and RS are two control pins. Therefore from Arduino, we just need to control 6 pins. VO controls the brightness. You might want to vary it depending upon environment light. So connect it with a 10K variable resistor called pot to ground. POT's first and last pin must be connected to 5 v and ground respectively. The middle one goes to VO pin of LCD. (Click on the Image to see Full Size Image) C) Multi Pin Connector Figure 5.1: Connecting LCD With Arduino Once connection is done, we can take the help of LiquidCrystal library of Arduino to print in the LCD. #include <LiquidCrystal.h> LiquidCrystal lcd(12,11,5,4,3,2); //create the lcd variable void setup() { pinMode(13,OUTPUT); digitalWrite(13,HIGH); lcd.clear(); //clear the LCD during setup lcd.begin(16,2); //define the columns (16) and rows (2) } void loop() { lcd.print("Codeproject.com"); lcd.setCursor(0,1); lcd.print("Rupam, Gulbarga"); //print... delay(2000); lcd.clear(); //clear LCD, since we are still on 2nd line... lcd.home(); //set the cursor the top left } LiquidCrystal lcd(12,11,5,4,3,2); is most important here. lcd is a variable of LiquidCrystal class which is initialized with (RS,ENABLE,D4,D3,D2,D1). Where all all the values are respective Arduino Pin Numbers and not LCD pin numbers. LiquidCrystal lcd(12,11,5,4,3,2); lcd LiquidCrystal (RS,ENABLE,D4,D3,D2,D1) lcd.begin(NO_OF_CHARACTERS,NO_OF_LINES) initialize the lcd for printing NO_OF_LINES and NO_OF_CHARACTERS par line. lcd.home() takes the cursor to first character of first line. lcd.print() can print characters starting from a position where the cursor is currently in. lcd.begin(NO_OF_CHARACTERS,NO_OF_LINES) NO_OF_LINES NO_OF_CHARACTERS lcd.home() lcd.print() lcd.clear() clears all data from LCD. lcd.setCursor(CHARACTER_NO,LINE_NUMBER) takes the cursor to particular LINE_NUMBER and CHARECTER_NO of that specific Line. lcd.clear() lcd.setCursor(CHARACTER_NO,LINE_NUMBER) LINE_NUMBER CHARECTER_NO Figure 5.2 Shows the output of above listing with Circuit diagram specified in 5.2 A). You are free to change the pins. But do not forget to change lcd initialization accordingly. Figure 5.2: Physical World Connection And Output Sensors are small electronic devices that can convert physical parameters to electrical parameters. There are wide range of sensors for measuring environment parameters like Humidity, Temperature, Moisture, Co2 and many more. Figure 6.1 Shows different sensors that might be used with Arduino. Sensors generally have a operating voltage and current range. Most of the common sensors operates at input 5v and requires medium range current. Which means that sensors can be supplied with voltage directly from Arduino's 5V Vcc pin. Sensors produces electrical output which is in the range of operating voltage. Arduino can read this voltage through it's Analog pins and there are 6 analog pins grouped togather as right most port at the bottom. The operating voltage range of these pins are 5V and operating current is about 100mA. One of the important thing you must know is that if you do not connect any sensors to any of the analog pins, the pins would still not read zero as expected. That is because they tend to pick up environmental charge.Thus in open state, reading the pins will return random low voltage. As operating voltage is 5v, most of the sensors works with 5v. However as electrical parameters are analog ( continues) in nature, so is the sensor output. But Microcontrollers care capable of processing only digital data. Therefore Arduino provides a on board A/D ( Analog to Digital Converter) of 10 bits. A/D converter works with the logic of sampling and quantization. It samples the signal with number of bits equal to A/D bits. Then quantize the input signal to nearest sample value. You can read this Wiki on A/D converter for a better understanding of the concept. The meaning is that Max voltage i.e. 5V can be represented by 2^10 i.e. 1024. So if the value returned by say analogRead(5) is x, then actual voltage = Sensor output Voltage=x*5/1024 Further output voltage of sensor will be associated with some value of physical parameters. For example temperature sensor LM35 which we will shortly see produces output voltage in the range of 0-1.1V for temperature from 0-92'C respectively. Thus 1.1/92 ( or about .1v) represents 1 unit of temperature. This is also called sensor precision. As sensors output voltage or current according to the physical parameter it is monitoring, they are also called sources and Arduino ( or any other device reading the sensor data) is called a sink. When many sensors are connected through wireless technique and many sinks are network togather with a common objective ( for instance measuring average temperature of an area) it is called Wireless Sensor Network or WSN. Figure 6.1: Different Sensors I have already provided the details about temperature and light sensor in my Live Weather Station with Arduino's tutorial. However I am writing this particular article for absolute beginners. Therefore this and next subsection will be based on the concepts presented in the aforementioned tutorial. There will be no change in the connections. However we will differ in code. In this particular tutorial I will not be using ArdOS the way I did it in the previous tutorial. We will begin with configuring our hardware and testing it first. We would follow it by integrating the setup with Internet f Things. We will begin with Temperature sensor LM 35. This is possibly one of the cheapest and effective sensors to kick start with your Arduino DIY. It is a three pin sensor which operates between 0-5V range and used for measuing temperature in the range of 0-92'c. If you are a hardware beginner and just starting to learn your hardware then it is always a good idea to study the data sheet of the components before working with them. It gives you electrical and logical understanding essential for working with those devices. You can download LM35 Datasheet from here. LM35 has three pins, which are to be connected to Ground, Vcc and Analog pin of Arduino. You can provide it power directly from Arduino 5V pin and connect the output pin to any of the analog pins. I have connected it to pin 5. See figure 2.1 to understand the circuit. Figure 6.2: LM 35 Connection With Arduino You might wonder how to connect those three pins to Arduino.Plenty of tutorial will suggest you to use bread board. So you can either use bread board or use three pin connector. I prefer short three pin connector as shown in figure 2.2. So you insert the LM35 pins into the three slots of the connector and insert the wires into respective Arduino slots. Figure 6.3: Connecting LM 35 using 3-Pin Connector Now before we code LM 35, a little understanding of Concept isn important. LM35 Converts temperature to voltage of range 1V. That means When Temperature is about 90'c, output voltage of LM35 will be about 1V. Now how Arduino reads this temperature? As you have noticed the output voltage of LM35 is connected with Arduino's Analog pin 5, Arduino will read the analog voltage which will be converted to digital value through internal 10 bit ADC. 10Bit ADC means that Arduino reads 1024 (2^10) when voltage is 5 volt. But as output of LM35 will never exceed 1V, 4Vs or about 10% of the precision is lost. This can be overcome simply by changing the reference voltage from 5V to 1.1V. This can be achived using following simple code. analogReference(INTERNAL);. Therefore, Temperature value= Value_Read_By_Pin_5/9.31 with 1.1 reference voltage. Let us write a simple program to probe the temperature once in every Second. Here goes our code for the same: float tempC; int reading; int tempPin = 0; void setup() { analogReference(INTERNAL); Serial.begin(9600); } void loop() { reading = analogRead(tempPin); tempC = reading / 9.31; Serial.print("Temp= "); Serial.print(tempC); Serial.println(" 'C"); delay(1000); } Bellow is the screenshot of the LM35 roperation. You can observe increase of the Temperature when I bring an Incense stick near to the sensor. Figure 6.4: LM 35 Serial Output LDR stands for Light Dependent resistor. As light increases on the surface of LDR, it's resistance increases, resulting in low voltage accross it. As Light reduces, resistance also reduces resulting in high voltage output accross it. Therefore if we connect LDR as one of the resistors in a voltage divider circuit, then voltage accross divider will vary as we vary light intensity. Figure 2.4 shows the Arduino connectivity of the LDR as well as the principle of voltage divider circuit. Figure 6.5: LDR Sensor Circuit Diagram As R2=1K/4.7k constant, Vout will decrease if R1 decreases which is when light intensity is low and Vout increase when R1 is high which is when light is higher. Therefore the logic in Arduino should follow the principle that analog pin value is directly proportional to light intensity value. We can represent the Light intensity as percentage of maximum intensity as follows: Light_Intensity_In_Percentage= (Analog_Value)*100/1024 Let us see the sketch to to test Light Intensity variation detection in terms of Percentage using the LDR circuit. float light; int reading; int lightPin = 5; void setup() { Serial.begin(9600); } void loop() { reading = analogRead(lightPin); light = (float)reading*100/1024.0; Serial.print("Light = "); Serial.print(light); Serial.println(" %"); Serial.println(reading); delay(1000); } The output can be seen in figure 6.6. Figure 6.6: LDR Sensor Result Metal sensors are inductive sensors. Which means that it induces current when metal is brought nearer to it. Here we will see the working principle of ID18-3008NA metal sensors which also acts like a switch. Therefore these sensors are also referred to as Proximity Switch. You can get yourself a metal sensor for about $3.5. Here 18 stands for maximum operating voltage, N stands for NPN type. You also have PNP type switch available. Recall in Section 4.1.2 we have already seen the functionality of a NPN switch. Figure 6.7 A and B shows the proximity sensor. Figure 6.7: Arduino With Metal Proximity Sensor Metal proximity sensor will have three color wires: Blue should be grounded, brwon is +vcc which should be given to Arduino +5v Vcc. When you take metal nearer to the Sensor, it induces more current which results in higher voltage. So you can print the voltage coming from analog pin in Serial port and then make a threshold to determine if metal is detected or not. Here is the simple Code listing for metal sensor which I have connected to Analog Pin 3. float metal; int reading; int metalPin = 3; void setup() { Serial.begin(9600); } void loop() { reading = analogRead(metalPin); metal = (float)reading*100/1024.0; Serial.print("Metal in Proximity = "); Serial.print(metal); Serial.println(" %"); if(reading>250) Serial.println("Metal Detected"); delay(1000); } Generally Iron/Copper or metal with good magnetic properties will induce more than 1V when brought nearer to the metal sensor.( You need not touch the surface. It can start detecting from a distance of about 3CM. Few months back I had done a cool model called Automated Mining. You can check out this Video to understand in detail as how metal sensor works: Metal Sensor Application Video Ultrasound is a technique of measuring distance from objects/obstacles. It contains a transmitter and a receiver. Transmitter transmits a short Ultrasound pulse periodically. If there is an object in front, the pulse hit the object can comes back. Receiver then measures the round trip time and can estimate the distance based on the round trip time. The reason for covering Ultrasonic sensor is a) It is one of the most commonly used sensors with DIY robots and b) It works on the principle of measuring pulse round trip time rather than voltage at an analog pin. Also Ultrasonic works with pulses. Therefore detecting the pulse needs PWM pin. So Ultrasonic sensor's output is connected to a PWM pin rather than an analog Pin. Figure 6.8 Gives the circuit diagram of Ultrasonic sensor. All you have to do is connect Vcc and Gnd of Ultrasonic device to that of Arduino. Trigger is connected to any non PWM pin and Echo is connected to any of the PWM pin. Figure 6.8: Ultrasonic Sensor Circuit Diagram In order to accurately calculate round trip pulse timing, we need a library called NewPing. Download NewPing from Google Code. Add the library by Selecting the Zip file through Sketch->Import Library-> Add Library In your Arduino IDE. 200-300cm. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. void setup() { pinMode(13,OUTPUT); Serial.begin(19200); // Open serial monitor at 115200 baud to see ping results. } void loop() { delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings. unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS). Serial.print("Ping: "); unsigned int dist=uS / US_ROUNDTRIP_CM; if(dist<5 && dist>0) { digitalWrite(13,HIGH); } else { digitalWrite(13,LOW); } Serial.print(dist); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo) Serial.println("cm"); } NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); will initialize an Object of NewPing with Echo, Trigger pin and maximum distance the pulse is expected to travel. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); NewPing Echo, Trigger sonar.Ping() will genrate a pulse and measure the time when it reads back the same pulse after the pulse is hit an object. If no object is in front, pulse never gets back and it returns 0. sonar.Ping() Distance is calculated by dividing the time with unit time taken for pulse to travel 1CM distance. We print the distance with Serial Command and glow the LED high when the Object comes about 5CM distance from the sensor. Pulse Width Modulation or PWM is one of the most important techniques for Speed and Intensity control of the devices. Every electronic and electrical load like bulbs, LEDs, Motors depends upon the current flow through them. Current can be controlled by changing the amplitude of voltage. Of of the ways to do it is using variable resistors or pots. But the fact is Pot can not be controlled by microcontrollers. Hence controlling the current flow through devices is really difficult. Current can be controlled by another means. Rather than changing the voltage amplitude, amount of time voltage is applied to load can be controlled. PWM is the principle of controlling current through loads by controlling the period for which voltage is supplied to it ( commonly known as duty cycle). As the name suggests, pulse width modulation is all about varying the ON period of the pulse. Consider the following code snippet float freq=1000;//1kHz double T; int onDelayUs,offDelayUs; float dutyCycle=10;// in percentage void setup() { pinMode(13, OUTPUT); T=1*1000000/freq;// T in microsecond onDelayUs=T*dutyCycle/100; // on delay in microsecond offDelayUs=T*(100-dutyCycle)/100;// Off delay in Microsecond } void loop() { digitalWrite(13, HIGH); delayMicroseconds(onDelayUs); // Approximately 10% duty cycle @ 1KHz digitalWrite(13, LOW); delayMicroseconds(offDelayUs); } The above code is very simple which turns pin 13 LED HIGH for every onDelayUs period after every offDelayUs period. So basically you are producing a pulse at pin 13 for specific duty cycle. Figure 7.2 Shows the waveform for various duty cycles. Now when you connect circuit of section 4.1.2 and provide connect transistor's base with a resistor to pin 13, Transistor will be switching on only for the period onDelayUs, load current will start increasing, then transistor will be off, stopping the voltage to the load which results in reduction in the load current. But before load current becomes 0, again transistor will be ON, increasing the current. Thus current can be varied depending upon how much time transistor is on which in turn depends upon the duty cycle. However this techniques has few drawback. First is that switching time of digital I/O pins are very slow, so we do not get exact square pulse. Secondly such pins are effected by interrupt. Hence in order to work with the above listing, one must also disable all interrupts for Arduino. This method also introduces jitter to the load because of above faults. To overcome this problem of using digital IO pins to produce PWM, Arduino offers a great PWM support through ATMEGX microcontroller's internal timers. See figure 7.1 A). Several Arduino pins among digital IO pins like pin 11 can provide PWM support. PWM signal of particular duty cycle can be produced through any of these pins by using analogWrite(pin, value); command. Yes, you read it write. We use analogWrite() for digital pins for producing PWM signal as PWM is a continues signal ( on and off togather). analogWrite() expects the value field to be between 0-255. Where 255 represents 100% duty cycle. A Desired duty cycle value can be calculated simply by Analog_Write_Value=100.0*dutyCycle/256.0; The output frequency is the 16MHz system clock frequency, divided by the prescaler value (64). Figure 7.1 A, B shows the circuit diagram and physical connection respectively for testing intensity control of LED through PWM. Here pin 11 PWM pin is used to produce PWM. Figure 7.1 Controlling Light Intensity With PWM Figure 7.2 PWM Waveform Here is the Simple Listing to test the circuit. int ledPin = 11; // LED connected to digital pin 9 void setup() { // nothing happens in setup // No need to use pinMode(11,OUTPUT) as we will be using PWM } int fadeValue=255; void loop() { // fade in from Max to min in increments of 5 points: analogWrite(ledPin, fadeValue); fadeValue=fadeValue-5; if(fadeValue<0) fadeValue=255; delay(500); } The above listing keeps on dimming LED in every 500mS from brightest of off state and repeats the operation. Figure 7.3 Shows the output of the above listing and circuit. Figure 7.3: Changing LED Intensity using PWM We have so far seen controlling the intensity of digital devices which more or less operates at low voltage/current range. What if we want to operate in high current range? What if we want our Arduino to control switching of an Electrical Bulb? What if we want Arduino to control polarity of motor? Surely in such cases load can not be grounded through a transistor as current rating of the transistor is low and current direction can not be reversed. The most common, effective and widely used solutions are relays. These are beast of a component. If you are to become a proficient hardware programmer, you absolutely have to master the art of understanding and working with relays. Relays are Electro-Mechanical switches which can select between different input lines through a connector by attracting or repelling it through magnetic property of a coil electromagnet. I would encourage you to read this wiki entry for Relays. As you see there are several types of relays which are mainly categorized into SPST( Single Pole, Single throw), SPDT ( Single Pole, Double Throw), DPDT ( Double pole double throw). Throw refers to as input lines and pole refers to as output. So SPDT relay can select any of the two input as it's output. Figure 8.1 B shows a typical SPDT relay. This has 5 pins. The center top pin is the pole pin or output. The bottom two pins are the input lines which relay select. One of the input is connected when relay is off and is called Normally Connected 9 NC) the other is selected when relay is activated called Normally Off or NO. Top left and right pins are +Vcc and gnd pins respectively. +Vcc voltage depends upon relay's operating voltage. Different specification relays are available: 5V,6V,9V,12V,18V, and 24v Relays are common SPDT relay types. Note here that this voltage is the voltage for switching on relay. NO and NC voltages can be several order higher or even AC voltages. Figure 8.1 Shows a typical SPDT relay, it's pin out, and internal schematic. Figure 8.1: Relay Connection Principle, Schematic and Pinout Lowest voltage relay i.e. 5V relay needs about 200mA current at 5V. So it is quite easy for us to know that the digital pins can not drive the relay directly. Then? Well, we need to treat the relay itself as a load. Now our problem is solved. We can connect relay's Vs with +Vcc and Gnd to Collector of a NPN transistor like BC548. When we supply base current to transistor through one of the digital pins, transistor completes relay's ground circuit through it's emittor as show in figure 8.3. However Transistors are generally effected by reverse current. As relay's switching mechanism depends upon magnatism in a coil, when it drives a load, chances of load current inducing back EMF is higher. Therefore, in working with transistor, relays have a flyback diade connected accross it whose role is to ground reverse emf. Another drawback of transistor driven relay circuit is, when you work with PCB's if a transistor is burnt due to over current, it is quite a task to replace it from the PCB with another transistor. Hence we use another mechanism. We couple the relay's Vs with Vcc with a chip called Optocupler. One of the cheap and most available optocoupler is MCT2E. Inside the chip, Optocupoler has a photo transmitter in the input side which can operate at a very low current and therefore can be triggered directly by an Arduino Digital pin. At the output side the chip has a photo transistor which gets base current soon as internal photo diade starts emitting light. The transistor is of NPN type. Therefore soon as it is switched on, it can produce the same voltage applied to it's collector at pin 6 to pin 4. As there is no connection between input and output side, this chip is not affected by any reverse current. This concept is also called optical isolation. Datasheet of MCT2E says that it is capable of an opto-isolation of about 1800v. So optocoupler's pin 1 is connected to Arduino's digital pin, it's pin 5 is connected to +Vcc of Relay( for a 12V relay, pin 5 is connected to 12V source and 9V relay, it is connected to 9v). Pin 4 which is the output pin of the optocoupler is connected with the VS pin of relay. Ground of Relay, Optocoupler ( pin 2), the voltage source ( +Vcc) and Arduino are made common. This is very very important while working with any hardware project. If you forget to connect the grounds of all these devices togather, then your relay will not trigger. Figure 8.2: Relay With Load Connection with Arduino Figure 8.3: Connecting Relay With Transistor If you are unwilling to work with independent setup of relays, you can also purchase 5V Relay break out boards, which you might get for about $3. But tell you the fact, if you mount your own relay units, it would cost you about $.5 :) Figure 8.4 Shows a typical 5V relay break out board. With three pin connectors which are input Vcc, Sig,Gnd respectively. Here Sig is Vs. Output side consists of three female slot pins with screw support. NO and NC are pins where input voltage will be provided and Pole is the output. The realy also has an inbuilt LED that goes high when relay is active. As relay is 5V, we need to connect Vcc with Arduino Vcc, Gnd with Arduino Ground and Sig with any of the digital i/o pins. At this moment, we want to test the switching of relay. So no need to connect Pole, NO and NC. Figure 8.4: 5V Relay Breakout Board Use the Blink Code of Section 4.1.1 to test the Relay switching. You will see relay is switching on and off at every second, with a sweet "click" sound, glowing and turning off the associated LED. See as pin 13 is going HIGH, relay is also switched on. Figure 8.5: Relay Output with Blinking Sketch Motors and Actuators are most important devices if you want to build your own robot. DC motors are important category of motors. Several types of DC motors are used in DIY project, for example Brushless DC motors, Geared Motors and so on. This wiki article on DC motor is a wonderful articel to get started with motors. In this article we are concerned with controlling DC motor. You can get yourself a 6V/9V/12V motor. You can also get one out from your old CD/DVD drives. Motors are also load and therefore can be switched the same way that of Relays/LEDs. Just like relays motors are prone to inducing back emf. Therefore we must connect a flyback diode accross the motor just like relays. Figure 8.1 Shows the circuit of a typical motor switching. Vcc depends upon motors voltage rating. If you want to control the speed of the motor, you can connect transistor to PWM pin and use the listing of PWM section to control it's speed. Else if the purpose is to only switch it on and off, use connect transistor base with a normal digital io pin like pin 13 and use the listing of 4.1.2 to check switching on and off of motors at every second. Figure 9.1: Controlling DC Motor With Arduino Using Transistor Figure 9.2: DC Motor Speed Control With PWM Remember that Relay switching time is multifold times slower than that of digital circuit's switching. Therefore relays can not be used for speed control of the motors. They are mainly used for switching On and Off of Motors. One of the advantage of relay is that you can provide +Vcc, -Vcc to NC and NO of a relay whose output can be connected to another relay's NO. Now by controling both the relays you can actually rotate the motor in either direction. Connecting motor with relay is simple and does not require any diode accross the motor as that is taken care by flyback diode accross relay. Figure 9.3 Shows the circuit diagram of 5V relay whose actual connection is shown in figure 9.4. I have used a 9V battery as Vcc. You can also use 9V/12V adapters. Figure 9.3: Circuit Diagram of Motor Switching Using Relay Figure 9.4: Physical Connection of Motor Switching With Relay You can test the circuit with the same blinking Listing of 4.1.2 Arduino is a fantastic solution for virtually anything you want to do with hardware. Wireless is no exception. Bluetooth modules are now available for Arduino which works nicely. You can use RF with Arduino. But one of the coolest support is that of IR. Though IR( Infrared) is actually a sensor and should have covered in Sensor category, but as it is most widely used for remote controlling devices, I would be covering this as a separate topic under wireless. IR receivers are available from different vendors and unlike other sensors, do not have any standard pin out. You can order an IR sensor for under $1. However make sure that you know the pin out of the sensor you order. It is very important as I personally have seen IR sensors of all sorts and pin out. However most common IR sensors would looking like figure 10.1 with Gnd, Vcc and O/P pin. O/P must be connected with any of PWM pin. IR also works like that of Ultrasonic sensor. The receiver can detect IR pulses modulated at 38KHz. You can use any home remote control ( TV/ AC) to generate signal. Figure 10.1: Arduino With IR Receiver Decoding the signal requires a special library. Download IRemote Library from GitHub. Add the library to your Arduino IDE. The library comes with a cool IRcvDemo, Save it as a different name and upload the sketch to Arduino. I have added a little more tweek to the code. You can turn on and off of pin 13 LED with the code #include <IRremote.h> int RECV_PIN = 11; IRrecv irrecv(RECV_PIN); decode_results results; void setup() { Serial.begin(9600); pinMode(13,OUTPUT); digitalWrite(13,LOW); irrecv.enableIRIn(); // Start the receiver } void loop() { if (irrecv.decode(&results)) { Serial.println(results.value, HEX); switch(results.value) { case 0x1111: digitalWrite(13,HIGH); Serial.println("LED ON"); break; case 0x2222: digitalWrite(13,LOW); Serial.println("LED OFF"); break; } irrecv.resume(); // Receive the next value } } This has just one problem. Every remote/company follow a different IR protocol. In other words, the hex value associated with button press will be different. So what you can do is test your IR, read the code of any two bottons and replace 0x1111 and 0x2222 with that code. SerialMonitor's dump is shown in figure 10.2 and the actual result is shown in figure 10.3. Figure 10.2: SerialMonitor screenshot of Working With IR Receiver Figure 10.3: LED on and Off through IR Receiver Observe the sign in remote and green LED on baord! You can see that the LED is turned on and off by alternative press of the ON/OFF button. There are so many hardware components and devices that plays an important role in DIY/Production embedded projects. There are so many sensors and motors that no tutorial in the world can cover all of them in a single tutorial. However there are some basic stuff that a DIY guy must know. Some basics of Voltage and current, some basic sensors and actuators. Some ways of displays. I have tried to cover most important, low cost hardware that are necessory for DIY projects. I have listed independent codes. I have focussed mainly on Hardware part in this tutorial. You can also check out my ArdOS tutorial where I have provided detail description of Working with ArdOS with Arduino. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Quote:You have spent a lot of time with this article Quote:you've done an excellent job. Quote:I wonder if you've already done an article on Arduino to drive a servo motor. General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/845211/Stage-Complete-Beginners-Guide-For-Arduino-Hardwar?fid=1874668&df=90&mpp=25&prof=True&sort=Position&view=Normal&spc=Relaxed
CC-MAIN-2019-09
refinedweb
8,631
65.42
Dynamically loading C++ components Working on an app that is loading "sub-applications" from a server gathering QML sources to be executed. It does this for security isolation reasons, as the sub-apps are 3rd party. The sources contain the JavaScript application logic which calls host app's API out of the QML. The logic complexity and amount of data the sub-app could potentially face is expected to increase which would obviously lower the overall performance and increase memory consumption. I'm wondering whether it's possible to dynamically load logic components written in C++ besides the QML of the sub-app for increased performance? The app is cross platform by the way. - jsulm Qt Champions 2018 last edited by @romsharkov Sounds like plug-in: @jsulm said in Dynamically loading C++ components: @romsharkov Sounds like plug-in: Can we store a plugin written in C++ on the server and pass it over to the client QtQuick app (which previously didn't know anything about this plugin) to be run in the context of that certain sub-app? @romsharkov The client app would have to support the plugin in some fashion to do that. It doesn't necessarily need to know about it but it would have to support loading it. So you would need to publish some sort of API or documentation on interfaces into the plugin system for the 3rd party app developers to use. - A Former User last edited by A Former User Qt plugins are just shared objects / dynamic-link libraries with a convenience API. Don't know what exactly you're doing there, but allowing your host application to be linked against 3rd party shared objects might undermine your security concept. @Wieland said in Dynamically loading C++ components: Qt plugins are just shared objects / dynamic-link libraries with a convenience API. Don't know what exactly you're doing there, but allowing your host application to be linked against 3rd party shared objects might undermine your security concept. Well, I actually want to put business logic (because JavaScript is kinda slow thus not suited for every kind of problem) into a C++ component that is bundled together with the QML presentation layer. The QML together with the C++ business logic component are fetched from the application server and executed in an isolated context in the host QtQuick application. So the C++ plugin is made available for this particular QML context only. Is this actually possible and secure? @romsharkov It's definitely possible, and it's as secure as you make it. The security will rely on how secure your "isolated context" is. If that is a good "chroot jail" type of scenario then it should be pretty secure. But of course 3rd party apps can do anything they want so malicious coders could find a way depending on how good your "jail" security is. I created a test application as a QML plugin, but I'm trying to figure out how to make the QPluginLoader load the main.qml file that is part of that plugin declaring the application UI into the predefined viewport object, any suggestions? I'm loading the plugin application this way: appsDir.setPath("R:\\workspace\\build-testapp_plug-Desktop_Qt_5_8_0_MSVC2015_64bit-Debug\\debug"); root = engine->rootObjects().first(); viewport = root->findChild<QObject*>("viewport"); if(viewport == nullptr) { qDebug() << "no viewport component"; throw; } QPluginLoader* loader(new QPluginLoader(appsDir.absoluteFilePath("testapp_plug"))); QObject* app(loader->instance()); if(app == nullptr) { qDebug() << "no app plugin instance: " << loader->errorString(); throw; } app->setProperty("parent", QVariant::fromValue<QObject*>(viewport)); may not be fully understanding what the problem is though. And I'm making assumptions you are loading from a resource. Is there a particular problem or error that you are encountering? @ambershark said in Dynamically loading C++ components: believe that if I refer to qrc:/main.qml I will get the host-application's main.qml and not the plugin's main.qml and that's the problem.. the plugin is just another application that's dynamically embedded into the host application Is the qrc of the plugin compiled right into the plugin itself? Can I somehow retrieve the plugin's main.qml to load it as a component into the viewport object? Or should I do it another way? - jsulm Qt Champions 2018 last edited by @romsharkov Do you have to call it main.qml? @jsulm said in Dynamically loading C++ components: @romsharkov Do you have to call it main.qml? not really, but it should be incapsulated I guess? I mean what if I have multiple application plugins that have similar qml file names, this is very likely... they should all somehow be bound to their plugin's scope @romsharkov Oh I see you are just confused on loading resources outside of your main application resources. Here check out these docs: That should explain everything, especially the section on loading resources from a library which is all a plugin really is. I think I finally made it... I ended up defining a plugin interface for 3rd party applications to be compatible with the host app. The interface requires the application to provide a list of all widgets (those are basically UI windows) virtual QVector<adapter::Widget> widgets() const = 0; and also the app is required to implement the QML getter, which returns the QML source code for one of the provided widgets on demand: virtual QByteArray widget(int widgetId) const = 0; The QML sources are placed in a qrc resource file and so compiled right into the application or plugin library if you will, the getter implementation looks like this: QByteArray App_Plugin::widget(int widgetId) const { QFile src; switch(widgetId) { case Widget::BROWSER: src.setFileName(":/widgets/browser.qml"); break; case Widget::PLAYER: src.setFileName(":/widgets/player.qml"); break; } src.open(QIODevice::ReadOnly); return src.readAll(); } When loading the application a new context is created and a widget's QML source code is retrieved to be displayed in the viewport component of the host client application. //load application QPluginLoader* loader(new QPluginLoader(_appsDir.absoluteFilePath(appPlugName))); QObject* app(loader->instance()); if(app == nullptr) { //failed loading application throw; } auto appInterface = qobject_cast<adapter::AppInterface*>(app); if (appInterface == nullptr) { //application doesn't implement the required adapter interface throw; } //remember plugin loader for this application, we might want to unload it later _loaders.insert(name, loader); //here I can eventually create a separate engine for this application //to set api providers such as the NetworkAccessManager //to limit and monitor the applications capabilities //for obvious security sandboxing reasons. //create isolated application context QQmlContext* appContext(new QQmlContext(_engine)); QQmlComponent appComponent(_engine); //load a widget (QML application UI window) into the viewport //in this case just 0, which defines the "browser widget" for testing purposes appComponent.setData(appInterface->widget(0), QUrl()); QObject* obj(appComponent.create(appContext)); obj->setProperty("parent", QVariant::fromValue<QObject*>(_viewport)); I'll be experimenting with this basement, we'll see how it does. P.S. It's like a web-browser, but cooler in the sense that it uses QML instead of HTML and allows the app's frontend to be written/optimized in C++ rather than just JavaScript. This post is deleted! Currently there are 2 major problems that I seem not to be able to solve on my own without your help: 1. Using internal types inside the 3rd party application Requirement: A third party QML app that is loaded into the client QtQuick application must be able to define it's own, unexported C++ defined QML Types. Those types shall only be visible to the certain app and not any other app as apps should be isolated. Problem: When I subclass the QQmlExtensionPlugin for the app's plugin library I override the virtual registerTypes method which is stated to define the types the plugin library carries, but's it's actually never called in the loading code I described above. Trying to import the plugin's types in one of the apps QML files the host app crashes with the error: :3 module "com.company.app" is not installed\n: import com.company.app 1.0 When I try to register the types manually like this: auto plugInterface = qobject_cast<QQmlExtensionPlugin*>(app); plugInterface->registerTypes("com.company.app"); it stops crashing, but the properties of the types are undefined, so this doesn't work either.. 2. Using internal QML files inside the 3rd party application Requirement: A third party QML app that is loaded into the client QtQuick application must be able to use it's own, unexported QML types defined in the QML files located in the qrc resources of the plugin library. Other applications should not be able to recognize those QML types. Problem: Those qml files are not recognized returning the error: :11 MyType is not a type\n @romsharkov For #1 I'm not sure. It's not something I've ever dealt with. I just started learning Qml a few weeks ago. I've used C++ Qt for 14 years or so but never touched Qml until recently. For #2: This is weird.. If you have your qml files in your qrc it should be able to detect them. Once thing I noticed is when you form the url to load the "main" qml page it needs to be something like qrc:///my.qml. I noticed if I didn't do the URL like that it couldn't find my components. You can also use aliases in the qrc which can help it find the component. You'll probably need some googling or additional help on this though. I'm just not good enough with Qml yet to be much help on these problems. I guess QML extension plugins are not quite the solution I was looking for cause... all plugins do is they provide types like a library (yep, now I got the "a plugin is just a library really") but seems like they cannot provide isolated environments... Basically what I'm trying to implement here looks just like a regular web browser with the only exception that it loads a dynamic library containing QML and C++ stuff instead of HTML/CSS/JS, but the apps are really just web-pages and they must be executed inside an isolated sandbox. The problem seems to be that extension libraries are not meant to provide QML types for just a particular context (sandbox), instead it defines the types globally, like if a web-app would define it's own types for the entire browser including all other web-apps and tabs which is, of course, preposterous and wrong. One solution I just thought of is running each application in it's own QQmlEngine instance. Methods like QQmlEngine::importPlugin give me new hope, if it does what I assume it would do then isolation is possible through separate engines and each engine would have it's own types and state. I will try this and report back, but what I already fear is that the memory footprint of such an engine instance is significant (as I assume it runs a whole JavaScript engine + other stuff) and that running multiple applications at the same time might cause significant memory over-consumption. - ganeshkbhat last edited by @romsharkov This is fantastic. I would love to see the result of the work. I was trying to attempt something like this but never thought it would be possible. Can you put the both server and actual project files in github as an example. This is a nicest approach I saw since some time. @romsharkov Yea you can check into the engine path, but the problem here is that Qml/Qt are full languages. It is hard to sandbox them. Basically you would have to write something to interpret the Qml like a web browser interprets the HTML. Then you could sandbox it. But really this would only be to a degree. Look at web browsers they have security holes all the time that allow viruses and other bad stuff through. The problem with plugins and libraries is you are allowing someone to run code on a system. It's hard to lock that down as I mentioned earlier. Maybe look into the chroot jail that posix OSes do. That may put you on the right track. But even then as hard as it is, you can still bypass a chrooted jail. Sandboxing is incredibly tough to pull off. But it is doable. If it's something you really want to do then keep at it, you'll get there. :) @ganeshkbhat Allowing to load and run 3rd C++ inside your main applications's process is very dangerous and we have not found any easy way to sandbox C++ so far, only just have a few ideas worth trying. I've described this issue here in a little more detail.
https://forum.qt.io/topic/76729/dynamically-loading-c-components/13
CC-MAIN-2019-43
refinedweb
2,129
53
My poor, sweet daughter is teething--four molars. Ouch. She had a hard time sleeping last night. I sleep very lightly as it is, so I also had a hard time sleeping. One the old ticker starts to ticking, I can't stop it, and I usually have to get up and do something. Now, if I Iie there, I tend to have a million amazingly wonderful ideas escape from my brain. As soon as the body goes vertical, though, they all go away. A shame. So anyway, at least I had some time for hacking. I didn't get to the configuration, but I did a lot of clean up that I wanted to get done. I do remember one thing from when I was lying down and thinking. I thought a lot about how I would want to code around the fact that we as an industry choose to conflate semantic chunking (i.e. namespaces) and versioning into one thing, namespaces. Sometimes that makes sense, because the new version is semantically distinct enough, but for nominal uses of Soap and WS-Addressing, the namespace differences are just annoying. System.Xml.Serialization will let you get away with a lot. System.Xml.XPath... not so much. What I would really like to be able to do is to say "Please consider these two namespaces, urn:a and urn:b to be synonomous, and pretend that they are the latter," and I think that could be relatively easy to do with a custom xml reader, but I haven't done anything about it yet. Maybe soon.
https://integralpath.blogs.com/thinkingoutloud/2005/01/texmex_17_wsmet.html
CC-MAIN-2019-13
refinedweb
266
79.7
Solution for Programmming Exercise 8.5 This page contains a sample solution to one of the exercises from Introduction to Programming Using Java.: I wrote my solution as a subclass, SimpleGrapher, of JPanel that represents the main panel of the program. The class includes a main() routine that makes it possible to run the class as a stand-alone application; main() just opens a window and sets its content pane to be a SimpleGrapher. To make it possible to run the program as an applet, I added a static nested class of JApplet to SimpleGrapher, but this is not required by the exercise. My solution uses a nested class, GraphPanel, for displaying the graph. This class is defined as a subclass of JPanel. It has an instance variable, func, of type Expr that represents the function to be drawn. If there is no function, then func is null. This is true when the applet is first started and when the user's input has been found to be illegal. The paintComponent() method checks the value of func to decide what to draw. If func is null, then the paint method simply draws a message on the panel stating that no function is available. Otherwise, it draws a pair of axes and the graph of the function. The interesting work in class GraphPanel is done in the drawFunction() method, which is called by the paintComponent() method. This function draws the graph of the function for -5 <= x <= 5. This interval on the x axis is divided into 300 subintervals. Since the length of the interval is 10, the length of each subinterval is given by dx, where dx is 10.0/300. The x values for the points that I want to plot are given by -5, -5+dx, -5+2*dx, and so on. Each x-value is obtained by adding dx to the previous value. For each x value, the y-value of the point on the graph is computed as func.value(x). As the points on the graph are computed, line segments are drawn to connect pairs of points (unless the y-value of either point is undefined). An algorithm for the drawFunction() method is: Let dx = 10.0 / 300; Let x = -5 // Get the first point Let y = func.value(x); for i = 1 to 300: Let prevx = x // Save the previous point Let prevy = y Let x = x + dx // Get the next point Let y = func.value(y) if neither y nor prevy is Double.NaN: draw a line segment from (prevx,prevy) to (x,y) The method for drawing the line segment uses the conversion from real coordinates to integer pixel coordinates that is given in the exercise. By the way, more general conversion formulas can be given in the case where x extends from xmin to xmax and y extends from ymin to ymax. The general formulas are: a = (int)( (x - xmin) / (xmax - xmin) * width ); b = (int)( (ymax - y) / (ymax - ymin) * height ); The formulas for a and b are of slightly different form to reflect the fact that a increases from 0 to width as x increases from xmin to xmax, while b decreases from height to 0 as y increases from ymin to ymax. You could improve the applet by adding text input boxes where the user can enter values for xmin, xmax, ymin, and ymax. In the main applet class, the init() method lays out the components in the content pane of the applet with a BorderLayout that has a vertical gap, to allow some space between the graph and the components that are above it and below it. The "North" component is a JLabel that is used to display messages to the user. The "South" component holds a JTextField where the user enters the definition of the function. Since I wanted to add a label, "f(x) = ", next to the text field, I created a sub-panel to hold both the label and the text field, and I put the sub-panel in the "South" position of the main panel. Finally, the "Center" component of the main panel is the GraphPanel where the graph is drawn. A listener for ActionEvents is registered with the JTextField. When the user presses return in the JTextField, the listener's actionPerformed() method will be called. The actionPerformed() method just has to get the user's input string from the JTextField. It tries to use this string to construct an object of type Expr. The constructor throws an IllegalArgumentException if the string contains an error, so the constructor is called in a try statement that can catch and handle the error. If an error occurs, then the error message in the exception object is displayed in the JLabel at the top of the applet, and the graph is cleared. If no error occurs, the graph is set to display the user's function, and the JLabel is set to display the generic message, "Enter a function and press return." The code for all this is: Expr function; // The user's function. try { String def = functionInput.getText(); function = new Expr(def); graph.setFunction(function); message.setText(" Enter a function and press return."); } catch (IllegalArgumentException e) { graph.clearFunction(); message.setText(e.getMessage()); } (After viewing my applet for the first time, I was dissatisfied with the appearance of the label at the top of the applet. There was no space between the text of the label and the gray background of the component. I decided to fix this by adding an EmptyBorder to the label to allow more space around the text where the white background of the label shows through. I also added borders around the main panel and around the subpanel that contains the text field. Borders were covered in Subsection 6.7.2) import java.awt.*; import java.awt.event.*; import javax.swing.*; /* The SimpleGrapher program can draw graphs of functions input by the user. The user enters the definition of the function in a text input box. When the user presses return, the function is graphed. (Unless the definition contains an error. In that case, an error message is displayed.) The graph is drawn on a canvas which represents the region of the (x,y)-plane given by -5 <= x <= 5 and -5 <= y <= 5. Any part of the graph that lies outside this region is not shown. The graph is drawn by plotting 301 points and joining them with lines. This does not handle discontinuous functions properly. This program requires the class Expr, which is defined in by a separate file, Expr.java. That file contains a full description of the syntax of legal function definitions. This class can be run as a main program. It has a static subclass, SimpleGrapherApplet, which can be used to run the same program as an applet. */ public class SimpleGrapher extends JPanel { //-- Support for running this class as a stand-alone application and as an applet -- public static void main(String[] args) { // Open a window that shows a SimpleGrapher panel. JFrame window = new JFrame("SimpleGrapher"); window.setContentPane( new SimpleGrapher() ); window.setLocation(50,50); window.setSize(500,540); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } public static class SimpleGrapherApplet extends JApplet { public void init() { setContentPane( new SimpleGrapher() ); } } //--------------------------------------------------------------------------------- private GraphPanel graph; // The JPanel that will display the graph. // The nested class, Graph, is defined below. private JTextField functionInput; // A text input box where the user enters // the definition of the function. private JLabel message; // A label for displaying messages to the user, // including error messages when the function // definition is illegal. public SimpleGrapher() { // Initialize the panel by creating and laying out the components // and setting up an action listener for the text field. setBackground(Color.GRAY); setLayout(new BorderLayout(3,3)); setBorder(BorderFactory.createLineBorder(Color.GRAY,3)); graph = new GraphPanel(); add(graph, BorderLayout.CENTER); message = new JLabel(" Enter a function and press return"); message.setBackground(Color.WHITE); message.setForeground(Color.RED); message.setOpaque(true); message.setBorder( BorderFactory.createEmptyBorder(5,0,5,0) ); add(message, BorderLayout.NORTH); functionInput = new JTextField(); JPanel subpanel = new JPanel(); subpanel.setLayout(new BorderLayout()); subpanel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3)); subpanel.add(new JLabel("f(x) = "), BorderLayout.WEST); subpanel.add(functionInput, BorderLayout.CENTER); add(subpanel, BorderLayout.SOUTH); functionInput.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // Get the user's function definition from the box and use it // to create a new object of type Expr. Tell the GraphPanel to // graph this function. If the definition is illegal, an // IllegalArgumentException is thrown by the Expr constructor. // If this happens, the graph is cleared and an error message // is displayed in the message label. Expr function; // The user's function. try { String def = functionInput.getText(); function = new Expr(def); graph.setFunction(function); message.setText(" Enter a function and press return."); } catch (IllegalArgumentException e) { graph.clearFunction(); message.setText(e.getMessage()); } functionInput.selectAll(); functionInput.requestFocus(); // Let's user start typing in input box. } }); } // end constructor // -------------------------- Nested class ---------------------------- private static class GraphPanel extends JPanel { // A object of this class can display the graph of a function // on the region of the (x,y)-plane given by -5 <= x <= 5 and // -5 <= y <= 5. The graph is drawn very simply, by plotting // 301 points and connecting them with line segments. Expr func; // The definition of the function that is to be graphed. // If the value is null, no graph is drawn. GraphPanel() { // Constructor. setBackground(Color.WHITE); func = null; } public void setFunction(Expr exp) { // Set the canvas to graph the function whose definition is // given by the function exp. func = exp; repaint(); } public void clearFunction() { // Set the canvas to draw no graph at all. func = null; repaint(); } public void paintComponent(Graphics g) { // Draw the graph of the function or, if func is null, // display a message that there is no function to be graphed. super.paintComponent(g); // Fill with background color, white. if (func == null) { g.drawString("No function is available.", 20, 30); } else { g.drawString("y = " + func, 5, 15); drawAxes(g); drawFunction(g); } } void drawAxes(Graphics g) { // Draw horizontal and vertical axes in the middle of the // canvas. A 5-pixel border is left at the ends of the axes. int width = getWidth(); int height = getHeight(); g.setColor(Color.BLUE); g.drawLine(5, height/2, width-5, height/2); g.drawLine(width/2, 5, width/2, height-5); } void drawFunction(Graphics g) { // Draw the graph of the function defined by the instance // variable func. Just plot 301 points with lines // between them. double x, y; // A point on the graph. y is f(x). double prevx, prevy; // The previous point on the graph. double dx; // Difference between the x-values of consecutive // points on the graph. dx = 10.0 / 300; g.setColor(Color.RED); /* Compute the first point. */ x = -5; y = func.value(x); /* Compute each of the other 300 points, and draw a line segment between each consecutive pair of points. Note that if the function is undefined at one of the points in a pair, then the line segment is not drawn. */ for (int i = 1; i <= 300; i++) { prevx = x; // Save the coords of the previous point. prevy = y; x += dx; // Get the coords of the next point. y = func.value(x); if ( (! Double.isNaN(y)) && (! Double.isNaN(prevy)) ) { // Draw a line segment between the two points. putLine(g, prevx, prevy, x, y); } } // end for } // end drawFunction() void putLine(Graphics g, double x1, double y1, double x2, double y2) { // Draw a line segment from the point (x1,y1) to (x2,y2). // These real values must be scaled to get the integer // coordinates of the corresponding pixels. int a1, b1; // Pixel coordinates corresponding to (x1,y1). int a2, b2; // Pixel coordinates corresponding to (x2,y2). int width = getWidth(); // Width of the canvas. int height = getHeight(); // Height of the canvas. a1 = (int)( (x1 + 5) / 10 * width ); b1 = (int)( (5 - y1) / 10 * height ); a2 = (int)( (x2 + 5) / 10 * width ); b2 = (int)( (5 - y2) / 10 * height ); if (Math.abs(y1) < 30000 && Math.abs(y2) < 30000) { // Only draw lines for reasonable y-values. // This should not be necessary, I think, // but I got a problem when y was very large.) g.drawLine(a1,b1,a2,b2); } } // end putLine() } // end nested class GraphPanel } // end class SimpleGrapher
http://math.hws.edu/javanotes/c8/ex5-ans.html
crawl-001
refinedweb
2,034
57.16
python 3.2 PyOS_ascii_strtod Bug Description I am on fedora 15 and just installed python3, python3-devel the version in python 3.2 also downloaded ephem 3.7.3.4 and installed using python3 setup.py install. After going into python3 import math, ephem and get error [pstan@logarithm f15-doc]$ python3 Python 3.2 (r32:88445, Feb 21 2011, 21:11:06) [GCC 4.6.0 20110212 (Red Hat 4.6.0-0.7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import math, ephem Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/ import ephem._libastro as _libastro ImportError: /usr/lib64/ >>> I see that in python 3.2 it is deprecated I was looking through the libastro source and I find occurences of PyOS_ascii_strtod in only two files. format.c and misc.c I replaced it with PyOS_string_ python3 setup.py install Now when I run in the python3 shell import ephem there is no immediate error but my scripts fail with an value error . So no progress made on my part but still hoping that ephem will soon run in python3. The PyOS_ascii_strtod() call is often returning complete nonsense. After six hours of wrestling with this bug, I have removed the call to PyOS_ascii_strtod() and replaced it with an entirely self-contained routine for parsing floats, and the program STILL crashes on me and goes haywire. Unless I have made some terrible blunder between the working code branch that powers the Python 2 version and the branch that powers Python 3, there must be some difference between the Python versions that exposes or exercises some terrible and obscure bug in my code (or XEphem's). I am not sure what to try next, as I have no guess as to where the problem lies — with my malloc() and free()? With a stray pointer somewhere? With function lifetimes and pointers to variables on the stack? In other news, I have started experimenting with writing a pure-Python implementation of the logic inside of libastro. If all goes well, I might be able to switch to shipping only Python. Then, people who need speed could use PyPy; while normal people would still get at least reasonable performance, but with an error like this one — an obscure, hours-long wade into machine code behavior — never possible again. :) Meanwhile, let me know if you have any ideas. This one has me stumped! Running "python3.2 -m unittest ephem.tests. I appreciate your efforts and for your reply. It seems that I have miscommunicated something. Having used pyephem (albeit naively) before python3, I was curious when you made the announcement for the new source. Up until python3.2 the source code would compile. So my first notice of a problem was with python3.2. The error states that PyOS_ascii_strtod is deprecated and looking through the online doc for python3.2 the function should be replaced by PyOS_string_ grepped your source and replaced the function. compiled pyephem in python3.2 and opening python3, I was able to import the module. Mr Rhodes, I am not a programmer, and I barely get the python code you developed. So if I am going over ground you already covered, please forgive me. perhaps the earlier version of the function has problems hence deprecated When I try to run some input to the modified pyephem, I get a value error which leads me to think that I just need to pass the function something it understands. which apparently I dont. If I can figure out the PyOS_string_ some code to run, I'll let you know if I do patrick I have tried the newest version in the repo and did the same replacement (by adding a define in setup.py actually) along with some other tweak (wrong version number in setup.py etc.) and managed to get it compiled. AFAIK there is a `ValueError: cannot convert string to float` when I first trying to do sth with a ephem.Date but it will be fine afterwards!!!! >>> d = ephem.Date( >>> str(d) ValueError: could not convert string to float: >>> str(d) '1970/1/1 00:00:00' I'm trying to dirty hack this problem by catching all unexpected exceptions and try again and it (kind of) works for now. Hope to see a out of box working version for py3k. thx I have finally solved the problem by making a several-hour search for an alternative strtod implementation we could use, and finally finding one here: http:// I have just released a new version of the "ephem" package that includes this change: http:// At long last, this should get PyEphem working again for people whose Python 3 version is recent enough that it has deprecated and removed the essential string-to-float function we were using! Please try it out and let me know it if works. If not, then please open a bug on GitHub, where I am now hosting the project: https:/ Thanks, everyone, for letting me know about this problem, even though it took me on a long journey to get it fixed—I guess I should not have left the obvious solution, of abandoning libc and Python's library entirely, as my last option! I have been testing the python3 ephem code although somewhat delayed from the announcement of the fix. Fedora python versions as of f15 (I am now on f17) are problematic for either python2 or python3 as both python versions have deprecated PyOS_ascii_strtod The python version on my f17 system is python3 -V 3.2.3 I am using a compiled version of xephem to compare the output version 3.7.6-rc4 My interest in using pyephem is for celestial navigation and related math problems Initial testing looks good It has obviously been too long since I have touched the Python 3 version of PyEphem! I will try to look at this by the first week of May.
https://bugs.launchpad.net/pyephem/+bug/770334
CC-MAIN-2015-22
refinedweb
998
71.04
RationalWiki:Saloon bar/Archive354 Contents - 1 You won't be seeing much of me for the time being - 2 Cosmos New Worlds - 3 Small Men on the Wrong side of History - 4 Duolingo should give me a job - 5 Media Bias Chart - 6 Bernie Sanders dropping out - 7 UV wands and Covid 19 - 8 COVID-19 denialists are officially the new HIV/AIDS denialists - 9 Prostitution should be legal - 10 Forgive the youtube link - 11 I have to wonder: how many people are fed up with the Stay In Place order? - 12 bobvids on The Quartering - 13 101 pseudo-evidences - 14 ContraPoints video from January - 15 Newest addition to RationalWiki (That I kinda need a little help with) - 16 Illusions - 17 thank you... - 18 WHO vs Trump - 19 The probability of 0 isnt impossibility - 20 About Sanders - 21 The Lansing, Michigan Protests aka "Operation: Gridlock" is in full swing - 22 Don't Be Like Belarus, Folks - 23 COVID-19 and Eugenics, let's take this one slow - 24 Anyone Familiar with "Swiss Propaganda Research"? - 25 vitamin d and lockdowns - 26 Fuck fox news - 27 Some depressing news... - 28 Would pseudo-academic accrediting agencies be missional? - 29 Hungary - 30 HSUS You won't be seeing much of me for the time being[edit] The laptop I've been using since 2011 has finally died. Until I get a new one, I'm not going to be very active here at all. I'm writing this at work, now that I've finished teaching for the day.. My hottible boss is around and making me feel uncomfortable. I want to sod off as soon as I can. See you all later. Spud (talk) 11:32, 10 April 2020 (UTC) - Take it easy duderino. (p.s. in case you really need the equipment...my previous several laptops were all castaways from my friends installing Lubuntu (light ubuntu though I'm sure you knew that) and for the really crappy oldest one I installed Porteus (super ultra light weight....fastest system I'd ever used). I never ever had a problem finding someone wanting to get rid of an older laptop. Don't be a stranger to long-eroo. ShabiDOO 12:41, 10 April 2020 (UTC) - I'd suggest vanilla Slackware over Porteus and especially Lubuntu, since Slackware has better native WM support than Porteus and is much lighter than Lubuntu. Though Spud might have unfixable hardware problems, so it might not be possible to fix it with a mere Linux install.) @ 15:35, 10 April 2020 (UTC) is this really about a broken laptop, or are you really going to prison? 19:13, 11 April 2020 (UTC) - I've never done anything that would warrant sending me to prison. The problem really is a broken laptop. But it looks like I'll get given a second hand one soon. So fear not! Spud (talk) 11:06, 13 April 2020 (UTC) - And you call that living? ikanreed 🐐Bleat at me 13:16, 13 April 2020 (UTC) - I realize now that that could be taken wrong. I meant the not doing crimes is not living. Having a second hand laptop is pretty reasonable. ikanreed 🐐Bleat at me 15:17, 13 April 2020 (UTC) Cosmos New Worlds[edit] I found the 2014 Cosmos reboot (A spacetime oddesy) okay, beautiful cinematography and animation and some nice humanist stories though I'd have to say I didn't really learn much except a few unknown remarkable lives. I've been watching Cosmos: Possible Worlds (2020) and have to say I'm really impressed so far. Has anyone seen the first few episodes. Any comments? ShabiDOO 12:41, 10 April 2020 (UTC) - Didn't even know they were doing more. ikanreed 🐐Bleat at me 16:48, 10 April 2020 (UTC) Small Men on the Wrong side of History[edit] The above subject is the title of a book by conservative journalist, Ed West. The "small men" refers to conservatives. This is a channel where right-wing or conservative writers are interviewed. The thumb-nail description is "The Decline and Fall, and unlikely Return of conservatism." The title of the video is, "Ed West: Why Conservatives have lost almost every Political Argument since 1945." I think it is refreshingly detached from a polarized sort of POV. The video is only 32 minutes.Ariel31459 (talk) 17:11, 10 April 2020 (UTC) Duolingo should give me a job[edit] I can come up with strange sentences with what little Esperanto vocabulary I know. Example: "La bebo manĝas lia porko kaj katoĵn". Me being crazy would make me an excellent candidate for a job --Rationalzombie94 (talk) 18:48, 10 April 2020 (UTC) - I assume you need an accusative in both places: La bebo manĝas lian porkon kaj katoĵn. Smerdis of Tlön, wekʷōm teḱsos. 13:44, 11 April 2020 (UTC) Media Bias Chart[edit] I think it's okay, but I really don't think Fox News should be on the same level as MSNBC, it's ridiculously rotten. Buzzfeed is also too high. Wonder where rawstory is, should be pretty low on this list. БaбyЛuigiOнФire🚓(T|C) 19:59, 10 April 2020 (UTC) - What's Daily Mail doing in that spot? --It's-a me, LeftyGreenMario!(Mod) 20:05, 10 April 2020 (UTC) - MSNBC is pretty damn bad, like all 24 hours news services are, filled to the brim with constant opinion-as-entertainment. ikanreed 🐐Bleat at me 03:26, 11 April 2020 (UTC) - Fox News is primarily problematic because of the talking heads who spread disinformation. If the chart is based on just the news part of Fox News, its probably technically accurate. The problem is that the Fox business model is to swamp the news with hours and hours of the far-more-lucrative disinformation. Bongolian (talk) 04:04, 11 April 2020 (UTC) - You can find links to the reviews of individual sources here and you are correct. Assuming "quality" and "reliability" are the same metric, Fox News mostly gets dinged by their talking heads (on a 0-64 scale, one analysis of Tucker Carlson gets 9.75, one of Hannity gets 14.25) where anchors like Chris Wallace score in the 40s and most of the articles are okayish (if biased). For MSNBC, it's the same, though not all of their talking heads do badly on the quality department (Rachel Maddow and Morning Joe do decently), Al Sharpton (especially), Chris Matthews, and Lawrence O'Donnell get dinged. It still seems that individually there's more crap at Fox News from the individual tables so I'm not sure why they are rated equally. MSNBC though isn't that great overall, in my opinion no American cable news network is these days. 72.184.174.199 (talk) 17:17, 11 April 2020 (UTC) - I have come to learn in my life experience that no news source is free from bias. Honestly every major news source is just as bad as every other one. Whenever I read news on a given topic, whether it be the coronavirus or a presidential campaign, honestly the best thing to do is to read as many sources as you can and just decide what you think is true. There is no one news source, and chances are there never will be, that succeeds in putting all possible bias aside and running like a perfect logical/fact machine. Chances are everything I just said has already been said by someone else (even on this website probably), but that's honestly what I've learned from experience. Aaronmichael5 15:52 11 April 2020 (UTC) - You were with me until the "every major news source is JUST as bad as every other one". I'm sorry to say that this only works in the most narrow sense. I'd take the CBC over any American network when covering the American election. They're from a different country, their coverage will not affect their own bottom line, they are government protected and funded with a mandate to at least attempt to tone down the bias. And even within America I'd take NPR over fox news or MSNBC, both heavily biased in America's two party system. I'm with you when it comes to stories reported all by news sources within the same country which affect national narratives and the universal interests of its citizenry (that mostly dealing with international stories where power struggles are hypersimplified). But thats a pretty small portion of news in general. It's one thing to say that all major news sources do a fairly bad job at educating their readers, its another thing to say they are equally bad when it comes to bias in general. That's utterly false. Bias can and has been demonstrated to be more present or pernicious in some sources than others. There are no truly reliable news sources. But some are awfully unreliable on subjects spanning politics, the economy, society, crime, culture etc. ShabiDOO 16:21, 11 April 2020 (UTC) - "honestly the best thing to do is to read as many sources as you can and just decide what you think is true" - Ideally you should be consuming all news sources as many as you can, BUT there's a whole "subscribe to us to unlock the article" begging from all those sites that's completely counterproductive to this. I guess this is on a tangent, but I think it's worth pointing out that this system makes it more annoying than it should to try to figure things out. --It's-a me, LeftyGreenMario!(Mod) 23:02, 11 April 2020 (UTC) Bernie Sanders dropping out[edit] UV wands and Covid 19[edit] UV wands are claimed to kill all sorts of nasty things like this. But I'm a little sceptical. Anybody got any ideas? — Unsigned, by: Bob_M / talk / contribs - Short wave ultraviolet is ionizing radiation that really messes up nucleic acids and anything that relies on them, and viruses in particular don’t have room for radiation shielding. It’s super effective against microbes on otherwise clean nonporous surfaces or dispersed in air or water with a clear line of sight to the UV lamp. But it’s not effective against anything shielded by opaque material like dirt or the outer layers of a porous material. Germicidal UV is also dangerous to multicellular life, particularly to eyes, and it can break down many polymers and damage items being cleaned. As such, it can be useful, but only situationally. Great for sanitizing air, clear water, and nonporous inorganic surfaces, but incapable of sanitizing porous or dirty things - A proper UVC lamp like the kind used in HVAC or water systems is very good at what it does, but it will cause radiation burns very quickly (nearly instantly to unshielded eyes), and they’re not in a form factor as convenient as the one you linked. If the product details there are accurate, that would be marginally effective. If all the output light is focused evenly, it could deliver a germicidal dose of ultraviolet to about one and a half square inches per second. A few caveats: the listed wavelength is on the border of UVB and UVC, so it may be less effective than the somewhat shorter wavelengths preferred for germicidal use, though with viruses being more fragile than bacteria, that may not matter. Also, it just recommends against looking directly into the light. A germicidal light would be dangerous to eyes even in reflection, and should only be used openly like that while wearing something like polycarbonate goggles with tight, opaque seals at the edges, and clothing that doesn’t leave skin exposed. - TL;DR: Bleach, soap, and heat are probably more practical for most home use applications where you might use a UV light. 192․168․1․42 (talk) 11:47, 11 April 2020 (UTC) - OK. Thanks. That's really interesting. From the confident tone of your response would I be right in assuming that you have some special competence in this area?Bob"Life is short and (insert adjective)" 12:33, 11 April 2020 (UTC) - Bob M - 'various scientists' have said soap and water etc are effective: can you give a more authoritative source for your UV lamp than 'item appearing on a well-known selling platform'? Anna Livia (talk) 16:24, 11 April 2020 (UTC) - I was not suggesting for one moment it was an authoritative source. I gave it as an example, said was skeptical and I asked for information.Bob"Life is short and (insert adjective)" 17:55, 11 April 2020 (UTC) As a 'bad syllogism' - This is a UV wand - Wands are used in magic - Therefore this is magical thinking. Is this totally wrong? Anna Livia (talk) 16:27, 11 April 2020 (UTC) - We got a UV sterilizer a couple months before the outbreak to help sterilize baby bottle stuff. As such I've looked into the research on this question somewhat already. UV light of this sort requires like 40 minutes of direct exposure to deactivate common viruses to conventionally sterile levels. And this is a plugged in AC device that approximates the UV intensity of sunlight from all 6 sides of a cube. I would suspect waving a wand over something for the duration of at most a minute or two would do next to nothing. Don't still have the papers I read about it on hand though. So... that syllogism might be questionable, but so is using UV wands to decontaminate. ikanreed 🐐Bleat at me 19:12, 11 April 2020 (UTC) - Is it better as a summary of 'flawed logic' than as a syllogism? And is this the direct ancestor of the UV wand? Anna Livia (talk) 22:29, 11 April 2020 (UTC) - @Bob_M: I investigated the matter a few months ago while considering what measures to take in the upcoming pandemic, and I was already familiar with the risks of UV light from experience welding (germicidal lamps and welding arcs have comparable UV output). I eventually got an HVAC light and made a heated internally-reflective enclosure for sanitizing packaged items and other things that I don’t want to chemically treat but where I’m not concerned about polymer degradation. - @Anna Livia: Sometimes the form factor of a wand is useful for an application. Metal detectors and Geiger counters are often wands, for example. Violet rays produce their light via corona discharge. This can produce some UVC, but it’s generally not enough to matter. Low-end UV lights like the one Bob_M linked use ultraviolet diodes. Better UV lights like this use mercury vapor discharge tubes. Corona discharge can efficiently generate ozone, though, so it has its own use in sanitary applications. - @ikanreed: Germicidal effects from UVC (or other ionizing radiation) depend on the applied dose. In addition to time, this also depends on the power of the light and how it is applied to the surface to be sanitized. 2 millijoules per square centimeter (which is what I used to calculate the 1.5 square inches per second figure) is a standard figure for what it takes, though the mechanism is more a logarithmic reduction as dosage gets higher than outright complete sterilization as in an autoclave. Even a dinky wand like the one Bob_M linked applies UV light far more effectively than sunlight when used correctly (virtually no UVC makes it through the atmosphere, and UVB is much less effective at killing microbes), and the bulb I linked has about a thousand times the UVC output of the wand. Unshielded close-proximity exposure to a proper HVAC lamp will kill nearly all microbes (or scorch corneas) in less than a second. 192․168․1․42 (talk) 00:12, 12 April 2020 (UTC) - All very interesting. When you look on the net (or at least when I look on the net) I find: sites selling professional equipment with complex specifications which isn't of much interest to the home user; sites selling home user stuff which claim they are fantastic; and non-experts expressing mild skepticism. - Which all suggests to me that this would be a fine subject for an RW article which might turn out to be quite popular as I'm sure that many people are asking themselves the same question. - I would be happy to create the stub - but I lack the knowledge required to do more it.Bob"Life is short and (insert adjective)" 06:48, 12 April 2020 (UTC) I was referring to the use of wands in this particular context - rather than the 'technical and practical' uses. If a UV wand article is created - mention should be made of UV banknote checkers (probably cheaper than the woo-wands), being 'actually existing technology' and the Victorian 'violet-ray and electric shock machines' (see example on [1]). Anna Livia (talk) 16:46, 12 April 2020 (UTC) COVID-19 denialists are officially the new HIV/AIDS denialists[edit] With the way they are insisting that the number of deaths is overinflated, I think it's safe to say that COVID-19 denialists are just as bad as HIV/AIDS denialists. To bear this out, I've seen too many posts on social media where they claim that people who die from other "underlying causes" (e.g. heart attacks) who were infected with the novel coronavirus are ordered to be counted as deaths by coronavirus. G Man (talk) 19:13, 11 April 2020 (UTC) - Those people deserve to punch themselves in the face repeatedly until the pandemic blows over. БaбyЛuigiOнФire🚓(T|C) 08:01, 12 April 2020 (UTC) - I do not feel it is as yet a fair comparison. there is so much about covid we just wont know for sure about till over, or at east being going on for a hell of a lot longer than mere weeks. death counts, death rates, infection rates, numbers of infected - these are things that we have to view for the time being as being provisional. there are many variables that that will effect the accuracy, and there is likely much variance between locales. testing for example is necessary for an accurate infection rate and we know there have been huge problems in getting that done. I read somewhere daily death counts are almost certainly higher than reported on the day when they are still rising, and almost certainly lower than reported when it is falling. something to do with when and how deaths are reported and collated. the claim of underlying causes and not covid being the cause of some of the deaths attributed may well have some truth to it. but we cannot know for certain if it is, or how significant an effect it might be having. and of course its likely be different in different regions. - when it comes to denialism of covid, much that could be labelled as such is simply down to a mixture of factors. uncertainty would a be one such factor. uncertainty of not yet knowing about so many things about the virus itself - the science stuff, uncertainty about our differing responses, their effectiveness, how long they will be necessary, and the impact on our lives, our jobs, our finances. and of course the uncertainty of how we would react to infection - wold it be mild? severe? will you die? will some of your loved ones die? there is nothing really to hold on to. nothing concrete to ground us and build our coping strategies. it all just feeds a sense of fear, of dread and anxiety about our health, our finances, our futures and ways of life. misinformation reigns with rampant speculation. claims are made then disproven later, some have a plausible logic but we just are not sure yet. some are simply wishful thinking. they are not lies as such, just we don't have all the facts. we want something certain some thing concrete. that would be progress, something to build on. even better if it means this upheaval can end. that's what most of the denialism has been. its been grasping at straws. hoping against hope this can all go away. even governments can fall prey to this, as in early on with the slow responses or possibly wrong tactics, and then as it drags on with consequences ever more catastrophic. most of us wont have the agency of governments, our wrong actions wont doom millions to bankruptcy or death. we likely have little agency at all. in lockdowns, with nothing to do or to distract us. nothing to do but watch it all play out and brood. - some denialism has been genuinely despicable. where it is not just from making wrong choices early on, or a reluctance or difficulty comprehending the significance of events or the severity or scale and where risks lay. this has been unprecendented and things moved so quickly. no time to see how things go, while a wrong or rash decision would hurt us and set us back. where its been dispicible is when as the tragedy escalated, some continued ignore what was happening. where misinformation was not mistaken assumptions but bare faced lies. where its purpose has been to cover backs and deflect blame rather than inform or correct early errors. to take credit for things not done, to sow dissent, to attack, to blame, to scapegoat, to sideline and discredit, not just perceived enemies but anyone and anything for doing their jobs or giving accurate and useful information. we know who these people are. its hampered any sense of a coordinated message or plan. it has us competing with each for vital supplies instead of pulling together. its always been bad since before the virus, now its costing lives and does not bode well for futures that require consensus, compromise, shared values, and alliances made for a common good. its a world that was already under assault, but now seems will spiral ever faster away to a world of petty squabbles and all against each other. - hiv/aids denialism is a little different. I cant really speak for the early days of the disease. it may well have had similarities. but in the developed world, has not been a disease that has impacted us all equally, in a way that covid has or is doing right now. there have no lockdowns. no sense of all being in this together, or all needing to do our bit. certainly in the developing world, Africa especially might have been or is like that, but in the developing world its only really impacted certain communities and continues to do so. communities that have and continue to face prejudice. and the responses and effects are different in different communities. in gay communities for example its been apocalyptic. things like testing, when we were eventually able to have since become commonplace. done regularly. its what you do. in black communities, I still see periodic drives to try and get people to test. there are issues that some communities didn't or don't have, that need to be addressed in other ways. im not equipped to go into much of that, I know though that in America hiv infection is a hell of a lot higher in black communities than any where else, in white gay communities its like we can start to believe it could almost be irradicated entirely. in gay black communities though its a far more bleak outlook. no one in the developed need die from aids any more. medication and prep have been nothing short of a miracle. but if you are gay and black in the us, infection rates and death speak to a disgusting injustice. hiv also is a feature amongst drug users, though i'm not sure how much we can speak of communities in that group. the commonality of prejudice amongst these groups, of varying degrees, means that for many it could be ignored. it was ignored. and even today for its an abstract threat where the actual likelihood of encountering is low enough its not a concern for most people. so denialism that arose has character of victim blaming. that the people who get it are dirty, living immoral lives, they brought it on themselves. some denialism sees it not as a disease at all, but the result of poor lifestyle choices specific acts like anal sex, associated with some at risk groups, as inherently deadly in itself that has been labelled hiv. other denialism is centred around effective treatment. from early on when what are proven treatments now, were in there infancy had problems with dosage that lead to peoples death. your friends were dying, your lovers were dying, you were dying, and too many people had died. drs just killed you quicker. you'd consider anything and you cant trust anymore the drs who you would normally listen to so don't heed their warnings on dangerous or ineffective treatment. and the usual quack cures, divine retribution and dastardly cia programs are all present. - the real difference with hiv/aids denialism and the covid variety is time. hiv has been going for years. much progress has been made, in all areas social and scientific. medication has gone along way to remove stigmas surrounding it, infection isn't, or least shouldn't be, a death sentence. its not life altering, barely an inconvenience. its been going long enough that the uncertainty surrounding everything covid, that we more easily spot the charlatans and the bigots and we don't quite have the existential dread hanging over us that might make us make rash judgements or bury our heads in the sand. and we can more clearly see what kind of denials stuck, where they came from and motivations. its just easier all round to deal with and it feels like we got it licked. covid is all uncertainty and theres only a few short weeks to base assessments on. we wont know for sure about any of it till the fog has lifted, its run its course and we can do the post mortem on our whole experience. until then we all grasping aqt straws and condemning people for actions that may seem indefensible to us but are simply bewildered and frightened people desperately seeking something to hold onto. AMassiveGay (talk) 09:43, 12 April 2020 (UTC) - jesus Christ, I seem to be incapable of short and to point answers anymore. they start out that way then I just go on and on. I cannot even tell if I am even remotely coherent. sorry.AMassiveGay (talk) 09:49, 12 April 2020 (UTC) - From what I remember of the late 1980s scene (can't remember before that very well), HIV denialism in America was strongly aligned with the conservative / evangelical nutjob sect, and was (like it always is) often used to sell "alternative" treatments. Kind of like COVID-19 denialism. So in that sense, nothing has changed. However, I remember the pace of progress on HIV being a *lot* slower than what's happening with COVID-19 today (reading up on some HIV history seems to confirm this, it took a decade for a lot of the information to come together, where we know a heck of a lot about this virus in roughly 4 months). I also remember a *lot* more hem-hawing and holier-than-thou bullshittery since in America as you say this first affected marginalized groups (first homosexuals, than IV drug users as you mentioned) -- what that meant is that, even for those who knew it was a virus, way too many (right up to the top of the Reagan administration in the early 1980s, according to what I'm reading) dismissed it as a "gay plague" and wanted nothing to do with it other than preach how you will burn in hell or something. Even in the early 1990s -- ten years after the disease became first known to the American public, roughly -- I remember hysterics on both how the disease could be transmitted ("you can get AIDS from toilet seats!" type bullshittery), and "gay plague" type demonization. There are a few American idiots linking COVID-19 to "homosexual 'sexual' events" but such is even stupider than usual since it's obvious to anyone with an IQ over a doorknob that anyone can get this disease. Rather, a lot of the denialism is more of the "oh this is just the flu / lockdowns are for pansies" type of bullshittery, which, if it weren't for the collateral damage, I'd just say "let 'em crash!" Airplane style and be done with it. 72.184.174.199 (talk) 16:56, 12 April 2020 (UTC) - there also far right groups trying link muslims to covid. this isn't denialism its outright prejudice. AMassiveGay (talk) 13:21, 14 April 2020 (UTC) - Those very frequently go hand in hand. ikanreed 🐐Bleat at me 13:28, 14 April 2020 (UTC) Prostitution should be legal[edit] If two (or more) consenting adults are allowed to have a one night stand it is legal as long as money is not exchanged.......yet if money is exchanged sleeping with someone is wrong? If adults give consent to the exchange of money and sex, so freaking what? Why send people to jail over screwing around as long as it is consensual? --Rationalzombie94 (talk) 22:53, 11 April 2020 (UTC) I agree but it's called 'sex work', cis scum. 2600:1004:B093:3F34:695C:FE20:86E4:FA96 (talk) 23:23, 11 April 2020 (UTC) - @2600:1004:B093:3F34:695C:FE20:86E4:FA96 Go fuck yourself IP address. VerminWiki (talk) 23:27, 11 April 2020 (UTC) - Why the random flame toward cis people? --It's-a me, LeftyGreenMario!(Mod) 01:03, 12 April 2020 (UTC) - It's a meme referencing the loonier parts of social media politics. 2600:1004:B093:3F34:695C:FE20:86E4:FA96's statement there is tongue in cheek. As for the topic, a further consideration is that it becomes legal again if it's filmed. 192․168․1․42 (talk) 01:35, 12 April 2020 (UTC) - Prostitution should be legalized so it grants protections to sex workers. БaбyЛuigiOнФire🚓(T|C) 03:06, 12 April 2020 (UTC) May I ask how prostitution would be legalized in practical effect?-Flandres (talk) 03:38, 12 April 2020 (UTC) - Clarify what you mean by that. — Oxyaena Harass 07:57, 12 April 2020 (UTC) - I was referring to getting support amidst congresspeople and the white house, and eventually the court system. Of course this would mater a lot less if this became a "let the states decide thing" but while that avoids an ugly fight on the federal level you might lose it does mean you are allowing some states to not do it, which on a issue of extending rights to sex workers might be seen as a unsatisfactory middle ground half measure that allows abuse to continue.-Flandres (talk) 08:14, 12 April 2020 (UTC) - I don't know, how did Nevada manage to do it, out of all states in the union? БaбyЛuigiOнФire🚓(T|C) 08:25, 12 April 2020 (UTC) - Technically sex work is only legal in individual counties of Nevada rather than the entire state. In those cases it has been legal since the late 19th and early 20th centuries mostly because it boosts the local economy, so it suggests any movement to legalize sex work would have to focus on taxing it at least as much as the human rights of the people involved.-Flandres (talk) 08:34, 12 April 2020 (UTC) - Only the counties with populations under 700,000 can allow it, which makes it illegal in Clark County (where Las Vegas is), which is where virtually the whole state lives. Of course as with the rest of the country it's in reality de facto legal for well-off people who just go to "escorts"; law enforcement only bothers going after "streetwalking" and the low-budget brothel operations ("massage parlors" and the like). --47.146.63.87 (talk) 17:55, 12 April 2020 (UTC) - It's legal in several European and South American countries (as well as a few other scattered countries across the world), the laws vary considerably. Even in America (which is more prohibitionist) it's possible for a wink-wink-nudge-nudge brothel to operate even in more conservative times of old (like the notorious "Chicken Ranch" in Texas if you are "connected with the right people". 72.184.174.199 (talk) 21:10, 12 April 2020 (UTC) - It's not the sex that's the problem in prostitution. It's the power dynamic. "Consent" gets real fuzzy when "or starve to death" is part of the question. Albeit a rational person will recognize other fucked up sexual dynamics exist and are not illegal. ikanreed 🐐Bleat at me 03:49, 12 April 2020 (UTC) - Like, don't go around busting everyone who does engage in it for starters. Legalization would also grant legal protections for sex workers so people can't just fuck them up and abuse them without legal consequences. БaбyЛuigiOнФire🚓(T|C) 03:49, 12 April 2020 (UTC) - The absolute priority and focus should be 1) vigorously fighting human trafficking and forced sex work 2) protection of voluntary sex workers (and non-criminalization obviously). Some crime agencies take these a little more seriously than others and are better funded and given man hours and expertise. Few are. The root of all problems lies in inadequate policing of forced sex work. ShabiDOO 06:40, 12 April 2020 (UTC) - While I generally agree with the premise, a short drive through the Bronx at night (if you're leaving a Yankee game you do not want to be stuck on some of the highway traffic getting out, it's either that or the delightful neighborhoods around it) sure does make it hard to justify. Though it really should be legal, there's no way as a man I could bring myself to get involved in that "trade" or encourage anyone to do the same; I'll stay single my whole life before I have any part of that world, thank you. Though it'll never happen, I'd be perfectly happy in a world without this; there's no one I have a better relationship with because he/she is regularly fucking someone, but there sure are a whole lot of people I have a worse relationship because of the same (though I'm straight I generally soured on the idea young, sometimes wish I was religious because I'd probably make a good Jesuit). But since it won't, like pornography it seems to be a rather effective way for people to ease tension that they'd otherwise express via violence, so if it's a choice between them I'll take the former. The Blade of the Northern Lights (話して下さい) 07:34, 12 April 2020 (UTC) - Sometimes I think I'm lucky to simply not care if I ever get laid, as an asexual myself. *shrug* БaбyЛuigiOнФire🚓(T|C) 07:36, 12 April 2020 (UTC) - I can admit to taking after one of the not-so-subtle messages of The Heart is a Lonely Hunter, that almost no one who plays the relationship game (be it romance or even friendship) learns a goddamn thing. No matter what scenario, I don't think so highly of myself as to imagine I'd emerge as the one out of 5. The Blade of the Northern Lights (話して下さい) 07:41, 12 April 2020 (UTC) - I hve visions of the job centre with prostitution all above board. 'so madam, what have you been doing this week in your efforts to find work? you might need to start broadening your work search in these adverse conditions or it might affect your benefits. have you considered going on the game? you can work from home and would be considered self employed, so thered be some tax breaks. we are running a short on course on hand jobs and fellatio, i'll sign you up. will look good on the cv. what are your views on getting pissed on? its just a thought. you have to specialise these days. AMassiveGay (talk) 10:08, 12 April 2020 (UTC) we have a page on prostitution that covers a lot the ground covered here. that page though I would consider dogshit and I would not recommend it. AMassiveGay (talk) 09:55, 12 April 2020 (UTC) As an adjoiner to the original post, prostitution is not merely consenting adults + money. there is the question how the additional of money changes the power dynamics of such an encounter, and issues surrounding poverty, substance abuse and desperation, issues of physical and mental health, and issues concerning all this effects issue of coercion and consent for what is often a profoundly invasive act. such a profession can takes psychological toll, especially if circumstance, financial or otherwise, has pushed someone into it. it is not the same as consenting adults nor as is sometimes argued 'just another job' (our own page once compared it flipping burgers - a frankly disgusting notion). there are also moral arguments and what it means for a society as whole as a whole that condones payment for possession of anothers body. what does it say it about the people selling and the people buying? simply saying prostitution should be legal is not enough without knowing what that means. these issues absolutely have to be addressed and in a way that addresses what it means for those working as prostitutes, not for the supposed benefits of those seeking their services. I believe it should be legal in some form, merely to better provide sex workers with rights and legal protections and allow for better access to physical and mental healthcare and benefits, and the grey areas of escorting must be clarified in any legalisation. legislation is not a magic bullet. it will not fix all the issues surrounding prostitution. any rationale for making it legal that talks of empowerment or ignores or downplays what is an inherently risky profession that can be and often is to an overwhelming degree something forced upon people by others and/or circumstance is stillborn and fundamentally sick. AMassiveGay (talk) 14:40, 14 April 2020 (UTC) - Circumstances are important and nuance is required. Am also pro-legalisation on account of prostitutes in Australia/Europe having better protection and healthcare. 86.14.252.201 (talk) 18:23, 15 April 2020 (UTC) - The demand for street prostitution is not the demand for sex. The demand for street prostitution is the demand for CHEAP, FREQUENT sex. A john that pays $20 for a blowjob from a drug addict 4 times a week isn't going to suddenly pay out $200 each time or reduce his frequency simply because the sex worker is now certified by the State of Illinois that she's organic fair-trade gluten free. Nor are the women (and men) in prostitution going to charge $20 if they are able to pass inspection. The only way to serve this clientele is with drug addictions, human trafficking, and worse. Legalization, regulation, inspections, etc, aren't going to be able to do squat to help the people at the bottom. CoryUsar (talk) 20:57, 15 April 2020 (UTC) Forgive the youtube link[edit] Yes... I know it's unforgiveable but considering the huge amount of time people have available it's a video worth watching. It's about 95% correct, leaves a lot out (how much can you really cover in this short time) and has a couple flaws, most especially in rule 0 at the end but I'd say, for a brief representation of how power structures work (how the world always has and does work) it does a pretty great job at explaining things. Watch this video. Think about it for a day before kneejerk reactions, watch it again a few days later if you have the time and give your thoughts. Again, forgive this rare unforgiveable posting of a youtube video. ShabiDOO 10:01, 12 April 2020 (UTC) - Eh. It's fine. I don't like the authoritative factual statement style for explaining a singular theory of power, though. Social dynamics as fact makes my skin crawl. ikanreed 🐐Bleat at me 13:07, 13 April 2020 (UTC) - I think that those "rulers" would be better off playing with a Rubik's Cube in their office than fighting wars and supressing freedom. I know a thing or two about using Rubik's Cubes. After all...— Jeh2ow Damn son! 16:40, 13 April 2020 (UTC) - Yeah indeed he does talk with a lot of authority for a video that doesn't come with any references or sources. What I like about the video is how quickly and concisely it summarizes what a lot of political science, political philosophy etc has said for a long time and what a lot of people are very unaware of. Where power/political decision making actually comes from and that the "court" never disappeared even when democracy came along. I wish he had used a different metaphor than "key" cause i think its more confusing than having any explanatory power. What you'd replace that with...I don't know. Maybe it would have been better if it was narrated by Machiavelli. ShabiDOO 08:47, 16 April 2020 (UTC) I have to wonder: how many people are fed up with the Stay In Place order?[edit] There is actually a group on Facebook called "Michiganders Against Excessive Quarantine". They are fed up with business closures, park closures and highly restricted shopping. Honestly I cannot blame them. Even with the order the virus is still spreading like wildfire. Seems that the Stay In Place order is irrelevant to the spread unless I am missing something. --Rationalzombie94 (talk) 16:48, 13 April 2020 (UTC) - The group is a collection of self-centred assholes who care more about their boredom and the illusion of freedom over the lives of others. I would call it collective scum-bucket thinking. Read up on "flattening the curve". If you go out and meet people or do unnecessary activity outside enough...you will be responsible for people dying. Third degree murder? Is your personal inconvenience, paranoia of government overreach and the illusion of freedom worth murdering people? Zheesh we are entering week 6 of a strict lock down in Spain, the daily body count is high and yet it still clearly helps, its widely supported and few pity the assholes who get 600€ fines for minor infractions. Its better than going to jail for manslaughter (as they are implementing in Russia). If we had done this earlier it wouldn't have been as horrid as it is now. Consider yourselves lucky enough that you have time to do it. Be grateful you have a Govenor who gives shit. ShabiDOO 17:18, 13 April 2020 (UTC) - Yeah, this thing would be much, much worse if we weren't social distancing. The people complaining are selfish. Chef Moosolini’s Ristorante ItalianoMake a Reservation 17:44, 13 April 2020 (UTC) - no one is happy with stay at home orders or lockdowns or whatever you want to call them. it doesn't trump necessity though. - I don't think it is fair to characterise everyone who are not on board with lockdowns as necessarily selfish arseholes. granted there are a lot of such arseholes but the financial repercussions of this thing are going to be huge for most of us, if not feeling them already. that said more should probably be done (if it isn't already) to help with the financial burden of people not being able to work. im guessing some places are better than others. - it is also the case that people would likely be more accepting of them if, like in the us, the official response from your government wasnt still even now absolute dogshit, and at local level responses have varied wildly. if trump was leading my country's response to this thing, I'd either shitting my pants while boarding up the front door less any germs break in, or just be running round the streets shouting 'its flu you pussies'. - lockdowns are an extreme response for an extreme situation. the us government needs to, and needed to far earlier to explain the severity and the need for what is necessarily. all the shit that boris has gotten, most of it deserved, I just look at the news to see how it goes across the pond. its quite calmly to see how much worse it could have been. - anyhow, ive been on the dole for bit. its not really been whole lot different to usual for me. AMassiveGay (talk) 18:17, 13 April 2020 (UTC) - The virus has been a pretty big deal for my family, so not being in a job any more is a pretty big deal for the aftereffects of the stay in home order. That being said, the Facebook group isn't concerned about the loss of the availability of jobs, the loss of demand for the job to function, and the amount of people who are filed for unemployment but rather inconveniences, and to me, it just sounds like they reek of privilege when they complain about highly restrictive shopping. Yes, I do get it that humans are social animals and can get cabin fever as a result of being cooped up indoors all the time, but the way of coping with the loss of social activity is compounded by the internet nowadays. I would have been sympathetic to the group's cause if the stuff they were complaining about were actual, serious consequences as a result of the best solution against the virus rather than "derp I can't buy whatever garbage I like anymore". БaбyЛuigiOнФire🚓(T|C) 18:44, 13 April 2020 (UTC) - If you Google "Michigan covid 19 cases" it brings up a handy graph. Seems like there's a downward trend in new cases that's repeated in a few other states like New York. It might be a "spike" in the data of course but one can cautiously hope that this is a sign that the lockdown is working. 72.184.174.199 (talk) 18:47, 13 April 2020 (UTC) - I looked up my state, California. We're still getting a lot of new cases but I think we peaked, hopefully. БaбyЛuigiOнФire🚓(T|C) 18:53, 13 April 2020 (UTC) - Kansas cases are still going up pretty quickly. Chef Moosolini’s Ristorante ItalianoMake a Reservation 19:29, 13 April 2020 (UTC) - Also, I can't emphasize this enough, but thank goodness Kansas elected a Democratic governor. I mean, holy shit. Chef Moosolini’s Ristorante ItalianoMake a Reservation 19:31, 13 April 2020 (UTC) - From my understanding the main reason people are angry is how highly inconsistent the Stay At Home order is. You are able to buy lottery tickets yet you cannot buy gardening supplies. You can buy recreational weed yet you cannot buy entertainment such as video games nor DVD's. Pretty long list of inconsistencies that is frustrating. Because of it there is a protest planned in Lansing, Michigan soon (Lansing is the State capital). Have a feeling that this protest will not end well. --Rationalzombie94 (talk) 19:38, 13 April 2020 (UTC) - @ being unable to buy video games and DVDs: Thank god for piracy. Yeah, but it's not something I'd still protest over, even though it IS stupid that you're able to buy a fucking gamble thing while you can't garden. БaбyЛuigiOнФire🚓(T|C) 19:41, 13 April 2020 (UTC) - Yeah, I hate the lottery in general. Chef Moosolini’s Ristorante ItalianoMake a Reservation 19:44, 13 April 2020 (UTC) - At least the protests have not reached the scale of what is going on in Brazil. The quarantine along with the horrible mismanagement of the situation by a President worse than Trump has drew large protest crowds- Some sort of compromise must be made to prevent the spread of infection while lessening the economic damage. Once the situation blows over there will probably be a spike in the number of homeless people and or people needing government assistance. --Rationalzombie94 (talk) 20:33, 13 April 2020 (UTC) - Well, that opportunity was lost when Dearest Leader completely botched our response to this. Side note to the fact everything we're doing seems totally ineffective, that because you don't see the results quickly. There's a serious lag time on restriction being put in place verse restriction actually appearing to work biased off testing, due to how pisspoor the testing is in the USA. It's going to look totally ineffective for at least a week or two, longer if the measures were limited or poorly enforced. Further the fairly targeted nature of our testing means we'll see a decent number of positive cases against negatives, since anyone who is tested is generally tested for a reason, and not randomly. Additionally, someone ignoring the restrictions could completely fuck the thing up. To see that in practice, look at South Korea's Patient 31 (This is what worries me with states like Arkansas doing nothing and Florida half-assing it.) It sucks, I won't fight you there, but it's the reality of the situation now. There are no good options for us at this point, aside from just having to wait.--NavigatorBR (Talk) - 02:07, 14 April 2020 (UTC) - The governor of my state is really dropping the ball with inconsistencies and excessive overreach. Can you honestly blame people for being pissed? --Rationalzombie94 (talk) 16:07, 14 April 2020 (UTC) - No...they are being pissy "freedom" babies. People who don't have the slightest clue what actual inconvenience means. I can understand their frustration (the world is) and wishing it would be over. But I cannot for a second commend their selfish bitch-fest. Grow up, be an adult. Stay home until its safe. Don't visit people. Do only the most necessary shopping in as few trips as possible. Exercise at home. Something a small number (though notable number) of Americans don't seem to understand is that we live in a society and that requires making sacrifices (sometimes notable ones including big chunks of your paycheck and dealing with inconveniences) to keep others out of misery and society and its streets safe. It is pretty unfair for the majority of Americans who would be happy to contribute to things like medicare for all and say...avoid thousands of pointless coronavirus deaths. Get over yourself and respect the rules like everyone else does. ShabiDOO 16:17, 14 April 2020 (UTC) - Think about it this way. This thing will be over a lot faster if you just stay the fuck home like the authorities are begging you to do. Chef Moosolini’s Ristorante ItalianoMake a Reservation 16:39, 14 April 2020 (UTC) - are michigans rules really that inconsistent and is it really excessive over reach? your state has the 3rd highest cases in the us. that would suggest to me its all pretty necessary. I haven't been able see much that is inconsistent in michigans approach personally either. the us as a whole's approach has been inconsistent, but that's largely down to the federal government and whose running the show there. ive no doubt any anger over the lockdown stems from or is fed by that. inconsistent would be putting far to positive a spin on it. i'm trying very hard to not bang on about it all the time, but it really difficult not at the moment - everything happening in the us right now, is a direct result of trump - inconsistency, lies, contradictions, misinformation all majorly contributed by trump, exasperated by trump, with attacks on media so constant that by now, there cant be any source for info available to the us public that hasn't been labelled as hideous bias. anger at the states government for doing what is necessary is misplaced. it should be directed at the man whose ego and caprice is killing thousands of americans. every appearance he makes is more horrifying than the last, its incomprehensible to me that he has any kind of support left at all. hes killing people AMassiveGay (talk) 17:21, 14 April 2020 (UTC) - His base is so awful that anything positive that does occur during the pandemic, his base will believe it. Or that they will say that it's not as bad as it could have been or it would have been worse under Clinton. Or that none of the things he did was really his fault or that it's not to be blamed for the pandemic, just blame illegal immigration and China instead. I'll repeat what everyone else has been repeating for eternity, this man has a cult of personality, and if he were to propose to nuke California, his base would be fine with it. БaбyЛuigiOнФire🚓(T|C) 19:10, 14 April 2020 (UTC) - As for the protest whether you support it or not- it will be an interesting situation. There are also protests due to lack of medical supplies and detention of immigrants while other prisoners are being let free. You already know my position but this will be an interesting turn of events. I am sure many of you would agree that this whole thing will be of interesting. This will certainly have an effect on the Presidential election. --Rationalzombie94 (talk) 20:19, 14 April 2020 (UTC) - Zombie could you please give me the formula? The acceptable thousands of people dying of covid (not just now but in the future) for each day the economy isn't inconvenienced? Are 1,000 grandmothers, grandfathers, babies, young people with lung problems and kidney problems, a couple people as young and healthy as you ... worth it for kick-starting the economy. 1,000 per day? Is that a fair compromise? ShabiDOO 08:54, 16 April 2020 (UTC) bobvids on The Quartering[edit] Might be useful for whomever is creating the page on The Quartering? Gunther8787 (talk) 17:38, 13 April 2020 (UTC) - May take a look but I think in order to get an accurate page, someone has to sit down and watch his videos. I haven't seen a second of this guy yet and the thumbnails and video titles tell me I'll be having a splendid time. 😒 БaбyЛuigiOнФire🚓(T|C) 18:49, 13 April 2020 (UTC) - I have watched some of his videos. He is into games, and YouTube drama. Right now some stuff about a person named Lucy Lu for using copyright material. Complains about anti-orangeman content, is " anti-woke", likes Tim Pool. Doesn't do a lot I would call significant. Mostly non political content (I think). Why bother?Ariel31459 (talk) 02:53, 14 April 2020 (UTC) - I mean you also have slanderous pages on both Styxhexenhammer666 and Razorfist. So I don't see the issue.108.208.14.123 (talk) 15:24, 18 April 2020 (UTC) 101 pseudo-evidences[edit] I wan wondering whether the classic response to '101 evidences for a young earth and Universe' be edited? Teerthaloke101 (talk) 09:35, 14 April 2020 (UTC) - I would say no for two reasons. First of all, the things being refuted are literally the alleged 101 evidences for a young age of the Earth and the universe. Secondly, some YEC looking for the proposed "evidences" might accidentally end up here and learn something.Bob"Life is short and (insert adjective)" 12:11, 14 April 2020 (UTC) - Correct, Bob. If you're talking about changing what the actual 101 evidences are, Teerthaloke101, we can't do that because this is a refutation of an actual document. Changing what we're quoting puts words in their mouths and therefore also degrades the rationale for our fair-use quoting of their possibly-copyrighted document. Bongolian (talk) 18:56, 14 April 2020 (UTC) No, I was talking about modifying our response to some particular 'evidence'. Specifically. the evidence about dinosaur soft tissue. There is continued doubt about whether the soft tissues found with dinosaur fossils belonged to the fossilized dinosaurs or had a recent separate origin. Teerthaloke101 (talk) 08:39, 15 April 2020 (UTC) - Ah. Sure, if you are confident you have found something wrong then go ahead and fix it.Bob"Life is short and (insert adjective)" 16:31, 15 April 2020 (UTC) ContraPoints video from January[edit] This is apparently a video she made where she's explains the whole twitter shitshow that happened a few months ago. Yes, it's 1h40m. The first 20 min. is about this 18 year old that was being accused of being a rapist. Gunther8787 (talk) 12:09, 14 April 2020 (UTC) - a 1h40m video on a twitter shit show is 1h40m too long. summarise if yo want commentAMassiveGay (talk) 13:16, 14 April 2020 (UTC) - "Breadtube" becoming increasingly centered on drama was an easy prediction to make. And I'll predict that will continue. I still like some of the content. ikanreed 🐐Bleat at me 13:30, 14 April 2020 (UTC) - Footnotes version of the Contra video. Contra passive-aggressively responds to criticism of her making enby-phobic comments and generally having bad takes as well associating with and giving the impression of legitimacy to Buck Angel (who is a crappy person). Most of it is waffle and largely irrelevant crap. I can link transcripts to a at least decent series of response videos if anyone wants them. ☭Comrade GC☭Ministry of Praise 13:42, 14 April 2020 (UTC) - Context is important. Who is this "she" who has made a video?Bob"Life is short and (insert adjective)" 14:38, 14 April 2020 (UTC) - ContraPoints, AKA Natalie Wynn. A progressive trans youtuber of moderate fame. ikanreed 🐐Bleat at me 15:20, 14 April 2020 (UTC) - Videos? I thought that only one person made a video response (based on her page)? Also, what's "enby-phobic"? Gunther8787 (talk) 10:36, 15 April 2020 (UTC) - @Gunther8787 Bigotry and/or discrimination towards non-binary people based around their gender expression. ☭Comrade GC☭Ministry of Praise 13:02, 15 April 2020 (UTC) - Yes grammarcommie please link videos with well thought out responses that deal with the argument. I'd like to see them ShabiDOO 13:41, 16 April 2020 (UTC) - @Shabidoo Part 1. (Transript.) Part 2. (Transcript.) Part 3. (Transcript.) Apologies for the delay. ☭Comrade GC☭Ministry of Praise 15:32, 18 April 2020 (UTC) - @GrammarCommie Peter's first video has more downvotes (1001) than upvotes (881) for some reason, unless Contra's fanboys jumped on that video... Plus, the Tati part makes you wonder why she'd (Contra) clip that out of her video... - Oh, and is Essence Of Thought (30,4K subs) on mission? Based on his videos, I think Peter needs a page. Gunther8787 (talk) 14:34, 20 April 2020 (UTC) Newest addition to RationalWiki (That I kinda need a little help with)[edit] Louisiana Baptist University and Seminary!! Took me an hour to create. Keep in mind that this is a mere start. --Rationalzombie94 (talk) 23:16, 14 April 2020 (UTC) - Can you format the sources? It's not hard, just time consuming. --It's-a me, LeftyGreenMario!(Mod) 23:20, 14 April 2020 (UTC) - You should write this to the Draft namespace first and then build up on it there. I can't help at the moment because I'm busy writing up a draft myself and it's time-consuming. БaбyЛuigiOнФire🚓(T|C) 23:21, 14 April 2020 (UTC) - How do I format links? Never figured it out. Please and thank you. --Rationalzombie94 (talk) 23:28, 14 April 2020 (UTC) - I've formatted one reference for you. Typically, the coding goes like this for web pages <ref>Last Name, First Name. (Date of Publication). [htmldotcom Title of the webpage]. ''Publication Name''. Retrieval date.</ref> БaбyЛuigiOнФire🚓(T|C) 23:46, 14 April 2020 (UTC) - Do I add the web link to [htmldotcom Title of the webpage]. --Rationalzombie94 (talk) 23:47, 14 April 2020 (UTC) - (edit conflict) Well, you have to know the citation format for Wikis. There's a documentation on cite_web, but just follow what the examples are. Last name, first name of author; publish date in parentheses, title of article, publisher in italics, date of source accessed. That's the general pattern I go with, but for other sources, you should check documentation. --It's-a me, LeftyGreenMario!(Mod) 23:50, 14 April 2020 (UTC) - Check the coding for this page and how it's linked. You can get a good understanding of how titling your external links work. БaбyЛuigiOнФire🚓(T|C) 23:54, 14 April 2020 (UTC) - Oh, by the way, if you want to make your article use multiple refs from the same source, use <ref name="WhateverYouLike">Last Name, First Name. (Date of Publication). [htmldotcom Title of the webpage]. ''Publication Name''. Retrieval date.</ref> and then use <ref name="WhateverYouLike"/> for any subsequent uses of the same ref. БaбyЛuigiOнФire🚓(T|C) 23:54, 14 April 2020 (UTC) Your questions about wiki markup and the structure of a RationalWiki article are summarized nicely in the style manual. You should read it, the community put an awful lot of effort into it. Cosmikdebris (talk) 01:20, 15 April 2020 (UTC) - You can also use reference #9 as a template for the others. Bongolian (talk) 04:25, 15 April 2020 (UTC) Illusions[edit] So I tried this out and very briefly I saw my vision distorted when I looked away, what is this an example of? Also are there any other things that have the same effect. I know there was one with a flag that you stare at and then look at a blank paper and you'll see it in different colors.Machina (talk) 00:57, 15 April 2020 (UTC) - The vision network in your brain does not directly see images like a computer camera does with pixels. It would be far too much data for your brain to handle. So your eye and optical nerves simplify the image somewhat, then the optical center's of your brain divide it into "metadata" that is a vastly over simplified version of the image that gets the job done. The thing is, this simplification procedure doesnt work on all images, especially images with many little highly contrasting lines or squares. Your brain basically glitches out and sees them as moving or imprints colors over top of things. MirrorIrorriM (talk) 12:56, 15 April 2020 (UTC) - Might be tangentally connected, turn your volume down, there's little done to the audio here it peaks and has echo, But the color brown is not a point on the light spectrum - a video on how Brown is contextual. I'm a big fan of brown also but now I know where it comes from. It's kind of a tiresome video because it's made by an engineer, and the audio is awful and the jokes are bad, but the ideas are systematic and really good, that brown is contextual in vision and interpretation and not a point on the light spectrum, making brown a shade of orange with a broad context. In some sense, an illusion. Just really tough to listen to unless it's low volume, the audio problems are earnest, bad gear in the wrong room, can't be fixed in post, can't believe this guy also does videos on the engineering of audio equipment. Gol Sarnitt (talk) 01:54, 16 April 2020 (UTC) - if only there was an online encyclopedia where you could look up lots of stuff --47.146.63.87 (talk) 03:05, 16 April 2020 (UTC) - Very good, BoN, what was your favorite? Gol Sarnitt (talk) 02:31, 17 April 2020 (UTC) - I like the lilac chaser. Also I find it pretty remarkable to see how easy it is to demonstrate the blind spot. --47.146.63.87 (talk) 04:50, 18 April 2020 (UTC) - I like that one too, thanks for sharing. I didn't notice I was seeing it until I knew what to look for, and then it was like "yeah, that's the motherfucker right there!" very funny to me. I can't pick one, but I do like exploring the limits of our tools every now and again. Enough adds up to a pretty loose grasp on reality, and I think that's important. I've experienced things that can only be explained as "Ghosts did it or I'm broken, because I cannot recreate what I just saw." It's why I'd make the most boring ghostbuster you'd ever see. In a haunted house "I saw something out of the corner of my eye! But that happened yesterday too, soooo, probably nothing." Gol Sarnitt (talk) 01:04, 21 April 2020 (UTC) thank you...[edit] Thank you so much you rats for being a place I can come on the onlines and know I can pretty much trust yall, no matter how much you might bicker amongst yourselves. It is going to be a gnarly road forward for us all and I just want to express some admiration. Give yourselves an elbow bump. Whoever has been on point with the WIGO lately double elbow bump. I appreciate yall. 206.53.88.85 (talk) 03:44, 15 April 2020 (UTC) WHO vs Trump[edit] So I've heard anti-china corruption allegations for a while now, something along the lines of "China is buying out the top WHO officials rather than contributing fully to the budget and that's why they won't mention Taiwan etc.". I was always under the impression the WHO had been able to maintain a degree of political independence. Is Trump cutting the budget a stopped clock (because the protest over corruption is justified) or just opportunism and dangling the budget like a carrot to influence the organisation? Were the awkward interviews just Aylward being inoffensive to an easily antagonized China? Anyone have any insight here? McUrist (talk) 09:07, 15 April 2020 (UTC) - As far as I can tell he just did it because they kept telling him that his "cures" were stupid. ☭Comrade GC☭Ministry of Praise 13:46, 15 April 2020 (UTC) - I've gotta disagree about the WHO maintaining a degree of political independence. They officially endorsed traditional Chinese medicine because of political pressures just 2 years ago. The US leans on them equally as hard, and so do many other countries. It's dangerous to discount the sum total of public health expertise they've gathered because of things like that, but it's also not right to think of them as insulated from political pressures. ikanreed 🐐Bleat at me 13:52, 15 April 2020 (UTC) - Yes, that Traditional Chinese Medicine endorsement is a real black mark against them and does raise some questions about their impartiality.Bob"Life is short and (insert adjective)" 16:26, 15 April 2020 (UTC) - I always saw the endorsement of TCM as a problem not unique or limited to this year to WHO as other organizations we've held as science-based became susceptible to it. The WHO has been promoting supplements for a while, as far as in 2015. Nature caught promoting TCM back in 2011. Science also caught promoting TCM. Establishment of alt med agencies in government (by Democrats), such as the NCCIH. Universities having alt-med promotions anf treatments including hospitals. NatGeo touting benefits of TCM (ok debatable if NatGeo is science-based). Naturopaths fighting for licensure in states. What the WHO is doing, I see less of political pressure as it is marketing and people blind-sided by exotic mysticism and how dubious TCM is. --It's-a me, LeftyGreenMario!(Mod) 19:17, 15 April 2020 (UTC) - It's notable that different parts of WHO have held seemingly contradictory viewpoints at the same time. The International Agency for Research on Cancer (IARC), part of WHO, concluded in 2002 that Aristolochia species were carcinogenic to humans,[2] and later strengthened their opinion in 2012.[3] Yet in 2010, WHO released a publication recommending Ayurvedic medicine, including specifically Aristolochia indica.[4] The latter document was produced based on a WHO conference on phytotherapy that exclusively included homeopaths, Ayurvedic medicine specialist and other alt-medicine proponents. As far as I'm aware, IARC is strictly science-based and includes advice from top scientific experts. Bongolian (talk) 20:28, 15 April 2020 (UTC) - Which is consistent with a scientific organization being under political pressure. Science says X, politics says Y, publish both and assure all the Yists that you understand their concerns with X. It's only when you're under direct political control that you start suppressing X in favor of Y. ikanreed 🐐Bleat at me 21:38, 15 April 2020 (UTC) Although the WHO has many faults including trying to make murderous dictator Robert Mugabe a goodwill ambassador it is, unfortunately, all we really have as a global health coordinator. Trump is probably not even aware of the TCM and Mugabe disasters. So I think he is wrong for him to cut funding. At some point when the local political feuding has died down and the petty nationalistic fights have finished we are going to be looking for someone to coordinate the global response - define standardized testing, diagnosis and treatment protocols and manage the anticiupated immunization program. And the WHO is the only organisation in a position to do this. I just hope they don't recommend treatment with tiger gall bladder and immunization via acupuncture. (That last sentence isn't serious)Bob"Life is short and (insert adjective)" 08:47, 16 April 2020 (UTC) - It's hard to say though that it's entirely nationalistic fighting. It's maybe more focused on legitimizing TCM, with the WHO just being politically correct in order to maintain their position (eg. give some ground to stop some of the CCP's hostility to oversight). I'm consistently surprised at how how internally focused the Chinese government is, maybe because we're used to seeing the US trying to be world police. TCM "research" is such a big deal to the Chinese government and a point of national pride. I think the CCP's interest in the influence side is, again, internal: They don't want someone in a position to make them look bad or talk about Taiwan. All speculation though. McUrist (talk) 10:05, 16 April 2020 (UTC) - Oh that wasn't a defense of trump's barbaric actions, just a warning against thinking that the WHO is truly independent. ikanreed 🐐Bleat at me 12:30, 16 April 2020 (UTC) - I understand that. I just wanted to remind people that, for all its obvious faults, the WHO is what we have.Bob"Life is short and (insert adjective)" 13:23, 16 April 2020 (UTC) - as I understand it TCM is 90% boner pills AMassiveGay (talk) 22:15, 19 April 2020 (UTC) The probability of 0 isnt impossibility[edit] Uuuuuummmmm eeeeee okayyyy, any probability nerds out there: is this true??? I'M BACK Blaze_Zero85.58.203.69 (talk) 09:39, 15 April 2020 (UTC) - I’m probably not the nerd your looking for. But I think it’s attempting to explain how sometimes a mathematical proof involves disproving the assertion, reaching a contradiction. E.g. “Thus and such must be evenly divisible by 3” and then when you throw a bunch of equations around you find a paradox where the end result cannot possibly be divisible by three. Then when you marry calculus with sloped curves and things “approaching” infinity or approaching 0 there’s still that tiny bit of non absolutes involved that you cannot say 3=3, end of story. Antigem (talk) 10:27, 15 April 2020 (UTC) - Oh don´t worry, I´m just a guy with basic studies; pls bear with me xD. It´s just Youtube decided to recommend me this (for some reason) and I got a little curious. - So I got from this is that if you wanna ask the chances of getting (example) tails: it´s more correct to ask the probability of the probabilty or just the probability of it? - Or am I just making a mess of myself? - Blaze_Zero85.58.203.69 (talk) 12:14, 15 April 2020 (UTC) - The terminology used in the video is terrible. It should be that an "Observed Sample Proportion of 0" does not mean a "Population Probability of 0 with 100% confidence". Basically in the coin flip example, you would have to flip an infinite number of coins to be *truly certain* the probability of an event is 0. This is why statisticians always talk about confidence levels in numbers. After 30 flips if none came back heads, we could be 99% confident (roughly) that heads is an impossibility. More flips would eventually lead to a confidence of say 99.9999% that heads is impossible. But every flip only makes that 99% *approach* 100%, but it never reaches it. MirrorIrorriM (talk) 13:24, 15 April 2020 (UTC) - God, he really used bad terminology didn´t he? Thank you, now I think I understand a little better! Blaze_Zero85.58.203.69 (talk) 19:25, 15 April 2020 (UTC) - A probability known to be zero based on a valid deduction in mathematics is in impossibility. A probability measured by way of sampling to be zero isn't. This is really obvious stuff. ikanreed 🐐Bleat at me 13:43, 15 April 2020 (UTC) - In mathematics, a probability of 0 means impossible. That is a certainty beyond dispute, a mathematical identity. In real life however (e.g., biology, sociology, physics, chemistry), probabilities are measured and never really absolutes. Hence, scientific papers will report for example, p<0.01 or p<0.00000001, the later case indicates that probability is remote but not impossible. Joe YouTube must be confusing "0" with "practically 0" or something like that. I can't be bothered to watch YouTube in general, but the probability that I will watch it is not zero. Bongolian (talk) 18:27, 15 April 2020 (UTC) - Even in the world of pure mathematics, this logic breaks down when the possibility space is continuous. For example, if I pick a random real number between 0 and 1, what probability does it have to land on exactly 0.5? Well, there are an infinite number of real numbers available to choose, the probability is 1 out of infinity. If that has any well-defined meaning at all, it's got to be 0. This works for any arbitrary real number you might pick. And the probability of picking an arbitrary real number cannot be greater than zero, because it can trivially be proved that if the probability was greater than zero, the total probability of choosing any real number between 0 and 1 is infinity, which is obviously absurd. But then that means it is possible for a random event to land on some outcome that had probability 0; that this will happen is certain, in fact. This is the contradiction the video aims to explain, and this is why mathematicians say an event with probability 1 or 0 happens "almost surely" or "almost never" respectively. Also, the video is part 2 in a series about how to solve problems where the probability of an event is itself unknown, which is complicated by the fact that (as MirrorIrroriM correctly noticed) you cannot gain a sure answer to the state of that probability just by observing outcomes, and so you must instead produce a list of probabilities that the probability of the original event is any given real number between 0 and 1, thus producing the original paradox. I would recommend the first video in that series (and the Wikipedia page I linked earlier, plus its notes and references) if you want context on that, especially if you don't trust me, the guy who just created an account 20 minutes ago to disagree in a talk thread, to deliver that context unharmed. thecnoNSMB (talk) 08:35, 16 April 2020 (UTC) - Nah, if you structure a question as "what's the probability of drawing 5 aces in a row from a standard deck without replacement mathematically, it's quite easy to prove the answer is absolutely zero. ikanreed 🐐Bleat at me 12:31, 16 April 2020 (UTC) - This reminds me of Zeno's stuff. @Bongolian: mathematically, zero probability of a set of outcomes does not necessarily mean impossible. Zero probability in mathematics means something like: the Lebesgue measure of a subset (desired outcomes) of the unit interval (all possible outcomes) is equal to zero.Ariel31459 (talk) 17:40, 16 April 2020 (UTC) - @ikanreed Yeah, because a standard deck of cards is a discrete possibility space, which is fundamentally different than a continuous or infinite one. I'm not saying "probability 0" never means "impossible," I'm just saying it doesn't automatically mean "impossible." It seems to me like you might be making a category mistake re: probability theory and its subfields. Ariel seems to be on the right track. thecnoNSMB (talk) 18:34, 16 April 2020 (UTC) About Sanders[edit] So, my father told me that he read somewhere (he's not telling me where he read this) that Sanders used to be a communist/radicalist. Now I know that he is subscribed to a click-bait newspaper, so I thought that those douchebags were at it again. Except I can't find anything on their site. So, I decided to google "communism Sanders" to see who wrote this tripe, and bumped against an article from a dutch clickbait newspaper called "De Volkskrant", were, according to them, Sanders defended Cuba. Just what did he actually say about Cuba? Gunther8787 (talk) 12:11, 15 April 2020 (UTC) - @Gunther8787 He said their healthcare and education system were good. Which is true. We even have a similar statement in one of our articles. ☭Comrade GC☭Ministry of Praise 12:30, 15 April 2020 (UTC) - I don't follow US politics that much, but I'm never impressed by any argument based on "Somebody used to be X", or "used to believe in X". I used to be a Christian. So what? It's what someone believes now that's important.Bob"Life is short and (insert adjective)" 16:21, 15 April 2020 (UTC) - Meh, if someone changed their mind, that's fine, but I want to hear from them why. What new information made you reconsider your belief? If someone said "HIV was created by Muslims as a bioweapon", but now says it wasn't, I'd be interested in knowing why! But most of this stuff in politics is not about learning more about a person's beliefs. It's "X said A, which is Bad, and that means X is a Bad Person and you shouldn't support them". --47.146.63.87 (talk) 23:37, 15 April 2020 (UTC) - Did you try a search for "sanders cuba"? It was all over the U.S. media a couple months ago. He made a statement that was strictly true but politically tone-deaf. His obvious point was "Castro's regime improved Cuba in some ways even as it did other things that are reprehensible, and this shouldn't impugn the good things", but it was easy to misconstrue him as "SANDERS LOVES CASTRO AND IS A COMMIE", which is what the whole right-wing media complex promptly did, followed of course by "establishment" media "reporting the controversy": "Some say Sanders idolizes Castro and will start executing landlords in Central Park if elected. Others disagree." --47.146.63.87 (talk) 23:37, 15 April 2020 (UTC) - "...Sanders used to be a communist/radicalist..." Excuse me, what planet is this? nobsFree Roger Stone! 18:22, 16 April 2020 (UTC) - Well he never said it wasn't true! As I'm sure you know everyone to the left of Romney is a crypto-commie, and even he looks a bit pinko! Can't trust those heathen Mormons! ("Radical" is such a useful word because since your opinions are of course correct, anyone who disagrees is "radical". Like those "radical abolitionists" and their "agitation"!) --47.146.63.87 (talk) 20:19, 16 April 2020 (UTC) The Lansing, Michigan Protests aka "Operation: Gridlock" is in full swing[edit] Holy crap the protest is massive- When I first heard of it I honestly did not expect that many people. I was wrong. Guess that many people are pissed. --Rationalzombie94 (talk) 21:23, 15 April 2020 (UTC) - These people are fucking morons and the cops should have arrested them. One of them even said, "I'd rather die from the coronavirus than see a generational company be gone." being so blatantly selfish of the damage he's instigating. БaбyЛuigiOнФire🚓(T|C) 21:32, 15 April 2020 (UTC) - What do you say to people who need to work to get by and have no alternative though? Throw them in jail for being between a rock and a hard place? ikanreed 🐐Bleat at me 21:34, 15 April 2020 (UTC) - It's a real issue, but it's not something worth clogging the streets over, nor encouraging a mass congregation of people; there are people still outside on the sidewalks. Yes, the shut down stinks. Yes, it affects wages. However, this is the best response to curbing a pandemic, and the alternative is to let the virus run rampant and kill people, which I think would have worse long term economic ramifications than the shut does. БaбyЛuigiOнФire🚓(T|C) 21:57, 15 April 2020 (UTC) - One model predicted that without social distancing, 40 million people would be killed worldwide this year. That would be roughly on par with the last big pandemic, the Spanish flu, which seems about right. One study of the economic impact of the Spanish flu suggested that cities that implemented "non-pharmaceutical interventions" such as social distancing, in the medium term, bounced back. Those that didn't suffered a greater spike in mortality, which created far worse economic problems in the long term. Right wing populists aren't known for looking at scientific data or thinking long term in general, but that's the data I see. 72.184.174.199 (talk) 02:22, 16 April 2020 (UTC) - It's amazing how crises underpinned by right wing ideology(no social safety net or other way to survive without constant work) create such effective populist right wing outrage. ikanreed 🐐Bleat at me 21:34, 15 April 2020 (UTC) - I was about to mention this to, how a right wing response to this pandemic created this shitstorm in the first place. But of course, conservatives are too short-sighted to see it. БaбyЛuigiOнФire🚓(T|C) 21:58, 15 April 2020 (UTC) - A social safety net can only do so much. People lose their businesses and even when this thing blows over, their income is gone. --Rationalzombie94 (talk) 22:11, 15 April 2020 (UTC) - not just a right wing response making thinks worse. right wing populism AMassiveGay (talk) 23:11, 15 April 2020 (UTC) - @Rationalzombie94Nominally safety nets should help any business not over-leveraged to hell weather the storm and come back. They wouldn't have to worry about the biggest recurring bill at most businesses(payroll) and owners could survive. If they're deeply deeply in debt with every inch of collateral dumped on loans for constant expansion, yeah, sadly that will bring you under. And if we had a social safety net I'd think debt holidays for shuttered business was good policy to resolve that particular question. ikanreed 🐐Bleat at me 23:34, 15 April 2020 (UTC) - It's almost as if high density low income populations and low density high income populations are living in entirely different worlds. It's garbage thinking to say "I should be able to go to my lake house unhindered" and it's garbage practice to say "I can't afford to live in my apartment literally tomorrow if I can't go to work" and this fucking beautiful convergence of complaints is falling squarely on Michigan's governance and their inability to work on it from a locale to locale basis. However, somehow the Federal government is off the hook for not wanting to try, and defunding the WHO (which I always pronounced as "whoa," saying "who" is like not even understanding the words World Health Organization or how they're pronounced) From the same people who say it's all made up and the people who are most disproportionately affected do we see this complaint that government is fucking up the response. It's not a fucking plot to destroy the economy for political gain, and not just a fucking difficulty in governing. It's like people think the people they voted in are geniuses and it's not up to them at all to take part in their own societies. I dunno, I've been pretty soaked in a bunch of people who have good arguments about avoiding a shutdown, a bunch of people who have good means of social distancing, and a bunch of people who can't make rent without a full paycheck. And instead of cracking open the nut of "Poorly managed exconomic structure" this is either seen as "the people in charge don't care" or "the people in charge are trying to destroy the economy for political gain." I would say the people in charge don't have a clue what they are doing, they are maintaining a system that they don't even care about. Gol Sarnitt (talk) 02:56, 16 April 2020 (UTC) - Why do you assume the protestors' preferred policy is not "let the virus spread unhindered"? Are you still in denial that a good number of Muricans are totally in favor of killing Others if it makes them richer? (Or sometimes even if it doesn't.) Of course most of them find it distasteful or too much work to personally do the killing, which is why diseases are a good method. As is climate change. --47.146.63.87 (talk) 03:13, 16 April 2020 (UTC) - No, that's pretty much how I feel about it, except for the assumed part. And I was full on Operation Ivy back in high school. Gol Sarnitt (talk) 03:58, 16 April 2020 (UTC) - What I find most demoralizing abut all this is that we have laid bare so much of what is wrong with "the system" during this pandemic, and there is a legitimate mass movement of popular anger and there is no shortage of articles on line saying this represents a historic turning point, a pendulum swing to the left where this crisis will make us all better people on issues like healthcare or neoliberalism or climate change, but when I look at the people in power, or the presidential choices, or the actions taken by various elites who ultimately shape policy across the world, I just don't see the necessary reforms being made. At best most people will have to settle for half measures and some countries are already using this to reinforce power like the aftermath of 9/11. This is like climate change in microcosm.Flandres (talk) 04:33, 16 April 2020 (UTC) - Remember that for every left-wing person who sees this and thinks that it represents an opportunity to remake society along their desired lines, there's a right-wing person thinking the same thing. --47.146.63.87 (talk) 04:48, 18 April 2020 (UTC) - Leftwing totalitarianism will be overthrown, beginning in Michigan. And yah, like the cops are going to arrest 100,000 protesters, some carrying arms, without using 100,000 masks and PPE, and throw the protesters in jails recently emptied of leftwing criminals to riot, loot, and burn because of coronavirus. nobsFree Roger Stone! 18:27, 16 April 2020 (UTC) - LOL, 81% agree on the need to keep on socially distancing. Only 10% think we should stop social distancing. 10%! How often do 80% of Americans agree on anything? Seriously, for the most part, the relatively uncontroversial notion of "staying safe" has bipartisan support. Certainly the rules could be tweaked in Michigan, but these idiots are advocating well beyond tweaking, to something most reasonable people know is stupid. As a result, they can yap all they want (and increase the risk of getting COVID-19, good on ya) but they can be safely ignored. 72.184.174.199 (talk) 18:37, 16 April 2020 (UTC) - Is this SUPPOSED to be sarcastic, nobs? БaбyЛuigiOнФire🚓(T|C) 18:44, 16 April 2020 (UTC) - My position is that the rules should be tweaked in a way that protects both health of people and the economy. Stemming the spread of the virus is needed but having a functional economy is needed. We could always go the way of Zimbabwe where currency is useless and epidemics of preventable disease are common. --Rationalzombie94 (talk) 01:12, 17 April 2020 (UTC) - nobs cannot be defeated with numbers or percentages, I'm guessing he read a Chick Tract about the dangers of Communist propaganda or something and whiffed on all the context. Gol Sarnitt (talk) 02:49, 17 April 2020 (UTC) - Sorry Zombie. Nobody here is capable of letting you have you eat a whole cake and yet still have left-overs. The trade-off is a higher corpse-count. If your state honestly gave the slightest shit about unemployed people or homeless people then it would have even the most basic social security net for them...which is doesn't. The kind of people who magically suddenly care about raising homeless numbers (cause these strict covid rules are going to make more homeless people who I am for the first time in years actually worried about) are the same people who would vote against a political party that would slightly raise taxes to help build more homeless shelters. Michigan has next to no safety net for this and it stems from the kind of mentality that human beings should be expendable so that the economy could get going again [read so I don't have to waste my time cooped inside and/or have a lower paycheck because of other people's problems]. ShabiDOO 07:54, 17 April 2020 (UTC) - It's also about minorities getting "handouts". Michigan is very rural, white, and bigoted outside of the urban centers (not unlike a lot of states). I saw something posted elsewhere recently that a lot of white Americans would gladly vote for someone who promised to put them and their family in a cardboard box with nothing but rats to eat by cooking over a fire as long as they also promised to make sure the black family next to them didn't have a rat to cook. Sadly pretty true. --47.146.63.87 (talk) 05:03, 18 April 2020 (UTC) Don't Be Like Belarus, Folks[edit] They still refuse to quarantine anyone. The lesson learned is that Belarus is a horrible role model for other nations.— Jeh2ow Damn son! 22:31, 15 April 2020 (UTC) - No offense to the fine people of Belarus, but since when has Belarus been a role model for, well, anyone? RoninMacbeth (talk) 22:35, 15 April 2020 (UTC) - Belarus is not a role model for anything, I mean anything. Not sure what areas they would be role models unless countries want to a adopt a terrible human rights record? --Rationalzombie94 (talk) 22:42, 15 April 2020 (UTC) - burgeoning dictators may be AMassiveGay (talk) 23:09, 15 April 2020 (UTC) - Lukashenko is the ur-Russia ass kisser, with a terrible porno mustache to boot. I was writing my senior thesis on the Belarusian independence movement when the 2011 Minsk bombing happened, too bad it missed him. The Blade of the Northern Lights (話して下さい) 01:05, 16 April 2020 (UTC) - Belarus is a role model for tankies.[5] Bongolian (talk) 01:49, 16 April 2020 (UTC) - Why do you assume his death would make things better and not worse? A dictator's death frequently leads to chaos if there are no broadly-supported succession plans. In Belarus's case Putin would either install another puppet or gin up an invasion. --47.146.63.87 (talk) 03:08, 16 April 2020 (UTC) - In 2011 I could've seen it working out better; this was right around the beginning of the Arab Spring, which looked promising and, if nothing else, worked out well for Tunisia. While assassinations generally aren't ideal (though it couldn't happen to a nicer guy), and there's definitely the devil you know versus the devil you don't, it would've been plausible that the rest of Europe could exert enough pressure on a country in their own back yard to get it to reform. The Blade of the Northern Lights (話して下さい) 13:28, 16 April 2020 (UTC) COVID-19 and Eugenics, let's take this one slow[edit] I have heard plenty of arguments that, "well, everyone is going to get it, some people are going to die, but we can't sacrifice the economic structure over this." But I would ask, why is an economic structure that fails at protecting its society especially more valuable than the society that makes it possible? Meanwhile, due to the limitations of our own optimized supply chain in our current economic system, the dairy industry is pouring out milk, the pork industry is discussing euthanizing baby hogs, and hospitals operate at { small margins] because we, what, all are supposed to pay an insurance company some cost so that they can pay for the minimum expected number of people needing care, so that if we get sick, everybody else that pays for insurance shares the load for our treatment but we don't get a benefit higher than what we paid in for? Sounds like Communism with buy-in tiers of priority to me. This disruption is supposed to affect everyone and capitalism is supposed to thrive on disruption. Why are the markets crashing while hardcore capitalist cheerleaders are just pissed off? But there are people who say "The economy must move on, and those too sick or poor or old to survive can suck the big one, they got left out and that proves that they were unfit to take part in this economy." Now, I don't want to Godwin's Law here, but I do want to point out that there is a certain attitude about protecting the economy and status quo that does not quite understand how anyone could find themselves in a disadvantageous position against some massive force like our current pandemic without it being an inherent personal and/or sub-societal fault that they have to own up to, and would rather blame those people than question whether any uses of structures as a means to their own position might be unfair. Therefore, if someone will die from lack of ability to conform to the norms of who should physically or economically survive COVID-19, no big deal, it doesn't matter who is most affected, and the disproportionate negative effects the virus is having on communities of lower income an higher density is natural order and not an indication of systemic classism? Gol Sarnitt (talk) 03:43, 16 April 2020 (UTC) - Hypothetical question for you. What would happen to life expectancy if we were to cut all school budgets by 50%? It's not "nothing", because without extra curricular activities, without adequate teachers and supplies, fewer children would graduate and the ones that do would have fewer options, people would make less money, crime would increase, etc etc. Basically, Very Bad things would happen, from something that isn't directly a health issue. Really, cutting most major functions of government would negatively affect life expectancy. Cut the budget for the highways, and you have fewer safety measures and thus more deaths. Cut the budget for emergency services, and that has a more direct effect on life expectancy. Cutting the military, well, that depends on whom you ask. - Regardless, every government has to weigh the cost and benefits of every action they take, and that entirely depends on what resources they have available. Spend too much on one thing, and you don't have another. Life is precious, but not priceless. What is that price? In the US, the average US citizen is worth around 8 million dollars. That's average, by the way, actual values are going to vary, and I will be getting a little bit into that in a second. What does this 8 million dollar price actually mean? Well, if a project is expected to save one life per 8 million spent, it's a good use of money. Perhaps it costs 80 million and is expected to save at least 10, perhaps it costs $80,000 and only has a 1 in 100 chance of saving a life. If it costs more, tough shit. It's terrifying, but bear in mind that every dollar spent on one project is one less dollar available for other projects. Spending $400m on upgrading a new bridge means you can't spend that $400m on schools. That 8 million is basically the amount we've been able to come to in order to save the most lives possible. Poor countries don't have that kind of money to save one life, they are forced to choose between saving lives with building a water filtration plant or ensuring enough food for everyone, things which save lives for relatively cheap. - Why can't we just tax people to save more lives? If it comes out of taxes, bear in mind that poverty is indeed deadly. A poor person in the US has a much, much lower life expectancy than a middle class person, and every dollar in tax reduces a person's health in some small way. Maybe it's an extra shift worked, maybe it's one less home cooked meal that's replaced with fast food, something insignificant to a single person but when dealing with a population of 325 million, otherwise insignificant numbers add up. How many people would die if every person replaced just one meal with a greasy burger? It's more than 0. - In other words, you set the value of the human life too high, you tax people into poverty and you kill more people than you save. You set the value too low, and you fail to save more than you kill. We may not have the right value, but there needs to be that value. - Now, what does this have to do with Covid? You can probably guess. You shut the economy down, people have less money, their life expectancy falls. You issue a stimulus to counteract this, that has to be paid back at some point with a combination of lower government budgets or increased taxes on the middle class (no, the rich aren't going to pay), and people die. The question isn't "should we be more concerned with our money than our lives" but rather "how many lives will be lost through the shutdown versus doing nothing at all". - And even that question itself is wrong. Most people would agree that it's worse to let one baby die than two senior citizens, because that baby could live another 80 years while the seniors may have only 10 years between them. Ignoring which years are worth what and assuming all years are equally valuable, we have to ask the question "how many life-years will be lost through the shutdown versus doing nothing at all", especially considering that the people dying from the virus tend to be the elderly or sick who have the fewest life years left while it's the young who lose the most lifespan from the shutdown. - And I will admit, I don't know the answer. But I can hope that the people at the CDC, WHO and so on, have asked this question and do have an answer. Which is why we are doing what we are doing. CoryUsar (talk) 05:49, 16 April 2020 (UTC) - The harshness is palpable, but I do agree on a couple points. One, it will have to be paid back, and I fully expect my rent to rise as I see some people just calling off their lease and moving out of my apartments, and I don't know how many of them are just defaulting to "sure, if my eviction is reported, my credit will die, but I don't want to be there for the 4 month cumulative bill." But evictions aren't always reported, as that runs the risk of having to go legal as opposed to just being ok with the loss of one or two month's rent. Most apartment complexes do kind of run with that capacity, I have no reason to ask if premature ending of a lease is available, I haven't saved up enough to buy a house yet, unless maybe I have because people are going to lose their mortgages, but I bet mortgages are going to be nasty shit over this, and prioritizing the economy doesn't stop people who pay rent or mortgage or are legally, contractual, actual factual facing massive consequences based on the current economic system from ever getting credit again. It's not that I don't think the economy is all-connected, it's that I don't think it's all-important and that, more importantly, the economy doesn't survive disruption like we say it does. I don't want to go full [assertion of Mammon] here, but there is a practical sense to life that is cost vs gain, sure. So the second point, in natural predation it's the old and the young that get it the hardest. I mean, there's a reason the pork industry wants to head off oversupply by euthanizing baby hogs, not young hogs. A population can survive the death of the oldest and the newborns. But epidemics, be they fungal, bacterial, viral, or parasitic, populations struggle and dwindle. Also, I live in the Midwest, it was 65 degrees on Christmas and it snowed 4 inches today, viruses are not the only threat to a population, how hearty are all of our crops? We are far too secure in "big business, tiny margins, big winning owners, and just enough to keep the workforce working" kind of explanations of why the economy "must press on" in a crisis. Because nobody has any of this "credit" built up enough to stay home? I'm not saying people don't need to go to work, I'm definitely not saying children don't need school as an important resource, I'm definitely not saying it would be solved if I was in charge, I'm saying we were not just unprepared for THIS crisis, the current economic system is wildly unprepared for the next crisis. Water company forced to turn water back on In American cities for households that did not pay their water bills!?! And the justification is that water is a tool in combating viral spread. Well, yes, and thank goodness it is somehow that, too, great job America at noticing something vital. Gol Sarnitt (talk) 01:40, 17 April 2020 (UTC) Anyone Familiar with "Swiss Propaganda Research"?[edit] Recently, came across this website and didn't know what to think of it. Seems to be some sort of 'anti-propaganda' site. How should one approach this? dogman_1234 04:17, 16 April 2020 (UTC)dogman_1234 - According to them Wikipedia is some kind of western disinformation campaign. Wow! I wonder what they would make of us?Bob"Life is short and (insert adjective)" 08:57, 16 April 2020 (UTC) - Their COVID-19 page is full of statements ranging from complete bullshit (many of the unsourced statements can easily be countered with a simple Google search) to cherry-picking to "shit source reading" in order to promote the viewpoint popular among certain sides of conservatives (including the conspiracy side this person seems to be on) that COVID-19 is nothing and the economy should be re-started or something. Initial read is to treat this as a "fake news" site in the direction of, say, the better known Zero Hedge or Wikispooks -- way over the top conspiracy. It is probably one guy's personal yapping outlet. The analysis that negative media reporting on Donald Trump is because the Council of Foreign Relations rules the media and the world and he's not on it or something is a real hoot, that's a new one, he should add that to the QAnon conspiracy of everything graph. 72.184.174.199 (talk) 14:17, 16 April 2020 (UTC) vitamin d and lockdowns[edit] are we all going to get rickets if we not going outside much? AMassiveGay (talk) 13:10, 16 April 2020 (UTC) - Lockdowns perfect to go run in circles in a field, provided you can. Realistically not going to infect someone. May as well use the extra time for something healthy. Personally going for 20km a week.McUrist (talk) 13:32, 16 April 2020 (UTC) - Indeed - if you can go outside. Not all of us have that option.Bob"Life is short and (insert adjective)" 14:03, 16 April 2020 (UTC) - Much as we shit on supplements here, and for good reason, they're an appropriate way to deal with an actual nutrient deficit. ikanreed 🐐Bleat at me 14:26, 16 April 2020 (UTC) - Fortunately, I have a balcony and it has become something of a daily ritual for me to sit there for those roughly three hours when it’s in direct sunlight each day (work permitting). Having a cocktail and a cigar while doing so doesn’t detract from the experience, either. ScepticWombat (talk) 09:22, 18 April 2020 (UTC) - im still able to go for a stroll so not really a problem this end. plus I'm pale enough to burn in moonlight so im confident I could generate vit d in a pitch black cave a 1000 thousand feet underground. AMassiveGay (talk) 22:13, 19 April 2020 (UTC) Fuck fox news[edit] They're now on national television, attributing to "sources" the conspiracy theory that coronavirus was made in a Chinese lab. Bomb shelter time? ikanreed 🐐Bleat at me 13:43, 16 April 2020 (UTC) - I'm reading the FOX news article and it's odd. It says "the virus sprang from Wuhan facility" but later says that the original infection was bat to human - and that the human worked at the lab. But those are not the same things. The initial implication is that the lab created it, but then they row back on that in the body of the article. - Who would have expected doublethink from Fox?!Bob"Life is short and (insert adjective)" 14:01, 16 April 2020 (UTC) - We're brewing towards cold war 2. The doublethink is way less important than the consequences of the propaganda. ikanreed 🐐Bleat at me 14:22, 16 April 2020 (UTC) - Bob, let's go slow on this. There's a difference between "made in a lab" and "came from a lab"; there a difference between "accidentally came from a lab" and "deliberately came from a lab"., Have we covered all subsets and contingent possibilities? Two things are certain, Coronavirus did not originate in the Wuhan wet market where no bats were sold, and did not originate from eating bats in the Wuhan wet market where no bats were sold. You are the victim of officially controlled CPP racist propaganda aimed at denigrating the cultural eating habits of the Chinese people when you repeat the those conspiracy theories. nobsFree Roger Stone! 18:35, 16 April 2020 (UTC) - I'm quoting Fox news on the "came from a bat" thing. But as Fox is the most unreliable mainstream news source I am aware of there is a lot of doubt on that statement. Nevertheless you seem to have some additional certain information and perhaps you should get in contact with the CDC who I am sure would be happy to hear from you.Bob"Life is short and (insert adjective)" 20:16, 16 April 2020 (UTC) - First of all, instantly attributing this notion that "lol Chinese eat everything" is something you've brought up that no one else did and something only the racist morons bring up. Get your cultural facts straight: eating stuff like dogs and cats and bats isn't widely practiced in China, and people who claim that China needs to stop eating bats needs to get their facts straight before they act like racist buffoons. Spread of the virus is not as simple as consumption of a weird and strange meat. It's more of a problem with the practice of the wet markets in general than it is Chinese culture. БaбyЛuigiOнФire🚓(T|C) 19:03, 16 April 2020 (UTC) - False dilemma: - P1: A place could only have been the origin of the disease if bats were sold there. - P2: No bats are sold in the Wuhan wet market. - C: The Wuhan wet market is not the origin of the disease. - Not to mention I've seen some reporting from reliable sources (i.e. not Murdoch's propaganda outlets) saying some experts think it may not literally have jumped to humans in the exact location of the wet market, but might have jumped to humans once or more in the Wuhan area and then circulated for a bit before starting to disperse to other regions. This is pretty much what happened with HIV. --47.146.63.87 (talk) 19:37, 16 April 2020 (UTC) - Right, though that probably won't happen as long as Trump is in charge. "China is terrible and they're killing us but it's so great they're led by the tremendous President Xi who's a great guy, believe me." But under President Tom Cotton... --47.146.63.87 (talk) 19:37, 16 April 2020 (UTC) - China's track record of bad biosecurity measures could be a logical explanation. If it came from a lab (possible) the likely explanation would be cross contamination or animals being packed tightly together allowed zoonosis to happen. If it was a biological weapon it would be a pretty shitty way to kill. As for a bioweapon, why would China economically cripple its trading partners? That would be stupid. The bad biosecurity measures be it mundane, would be more logical than a bioweapon. --Rationalzombie94 (talk) 23:08, 16 April 2020 (UTC) - SARS is known to have escaped Chinese labs on multiple occasions, and lab animals have been sold at local markets in the past, so an escape from a lab is entirely plausible. And the creation of potentially dangerous chimeric viruses has been going on for a while as a standard method of examining the infectious potential of nonhuman viruses. 192․168․1․42 (talk) 03:10, 18 April 2020 (UTC) - Let us accept for a moment your three assertions. There are a vast number of facts in this world which can be combined in many ways to support any particular hypothesis (or for that matter conspiracy theory). What exactly are you claiming happened in the case of COVID 19 and, more importantly, how would you test that claim? Remember the assertion that there is no evidence your claim is false does not make it true.Bob"Life is short and (insert adjective)" 10:25, 21 April 2020 (UTC) With the bat thing, covid is not thought to have jumped from bat to human but rather to have jumped from bat to a third animal, a pangolin is thought likely, and then to have jumped to human from there. As for speculation about mistakes in labs, I care not. while the virus still rages its an irrelevant distraction and in no way exonerates early mistakes nor the continued appalling handling of certain governments. what ever china's role in this ultimately in all this we have known of a threat like this for years. ours repsonses are entirely on us and our governments' responses are entirely on them. it seems that we will be unlikely to learn the lessons we are currently being taught in favour of who we can be blame. we don't need to ok to china for that when we can and should look closer to home AMassiveGay (talk) 12:41, 21 April 2020 (UTC) Some depressing news...[edit] A high school friend that I had has just died from COVID-19. You can't deny how powerful a single virus is. And I'm pretty sure that a lot of climate change denialists could actually point to the disease as evidence that the earth is not getting hotter, but colder. Sadly, my friend will never cringe at those idiots ever again.— Jeh2ow Damn son! 16:14, 16 April 2020 (UTC) - Keats once said "Nothing is real until it is experienced". I'm sorry COVID-19 is real for you. ikanreed 🐐Bleat at me 16:25, 16 April 2020 (UTC) - Yesterday it snowed in mid-April: maybe because the planet is shut down and lower greenhouse gases are being admitted, global warming is taking a holiday and colder whether is in the wind. Conversely, the no reusable plastic bags order was rescinded and we're backing to destroying the planet to save ourselves from a loathsome disease. Oh. the dilemmas are becoming to much for a simple mind to bear. nobsFree Roger Stone! 18:42, 16 April 2020 (UTC) - Yesterday it snowed That's not how global warming works you idiot. БaбyЛuigiOнФire🚓(T|C) 18:53, 16 April 2020 (UTC) - I stopped using bags years before it was popular. Like the overwhelming majority of people, I have these amazing things attached to the end of my arms that enable me to pick up and carry things. If you're unfamiliar, they're called hands. The Blade of the Northern Lights (話して下さい) 19:05, 16 April 2020 (UTC) - Pain in the ass to move thirty-forty items from conveyor (if the store doesn't bag for you) to cart to trunk to final destination, and hopefully you don't drop anything fragile. Harder for some people as well. Of course Costco and some other places have had this solved for decades: give the shipping boxes everything comes to the store in to shoppers. Other stores discard these instead and then give out bags because they would have to organize the boxes, and it's psychologically viewed as "cheap". Something something externalities. --47.146.63.87 (talk) 19:20, 16 April 2020 (UTC) - For sure. But in my case, I'm a tall, healthy, relatively young man, so I don't mind the extra trips. Not like I have anything so pressing that an extra 2 minutes a week will kill me. The Blade of the Northern Lights (話して下さい) 22:01, 16 April 2020 (UTC) - At least you're introspective enough to realize you have a simple mind. --47.146.63.87 (talk) 19:20, 16 April 2020 (UTC) - (trying to keep this discussion about Jeh2ow's serious loss) Oh god, how close is this friend to you? That's devastating. --It's-a me, LeftyGreenMario!(Mod) 20:16, 16 April 2020 (UTC) - That’s awful. I’m so sorry that happened. Chef Moosolini’s Ristorante ItalianoMake a Reservation 21:43, 16 April 2020 (UTC) - Yeah. I'm very sorry to hear of this incident. We're all doing our best right now to curb the spread of the disease so that no further tragic losses can occur. БaбyЛuigiOнФire🚓(T|C) 21:49, 16 April 2020 (UTC) Would pseudo-academic accrediting agencies be missional?[edit] Kinda curious on that one considering that there are some fake accrediting agencies that support creationism, woo and conspiracy theories. --Rationalzombie94 (talk) 22:18, 16 April 2020 (UTC) - Sure, the existing academic accreditation article already a section that deals with accreditation mills and could use expansion. Cosmikdebris (talk) - I agree with it being missional. These institutions are a key part of giving some of these cranks their 'credibility'. Feel free to continue full speed ahead @Rationalzombie94 --NavigatorBR (Talk) - 23:13, 17 April 2020 (UTC) - Yeah, definitely missional as part of the sliding scale pseudo academia that begins with more or less legit institutions with faith statements and the like, shading into woo and nutty religious academies/universities whose only connection to academia is their branding, and finally end up with out and out diploma mills, usually of no fixed abode (i.e. online scams). ScepticWombat (talk) 09:16, 18 April 2020 (UTC) Hungary[edit] So Hungary's "president" recently banned trans folk from transitioning. This is after Hungary's legislature gave him emergency powers. What do y'all think will come of this? RationalHindu (talk) 23:21, 16 April 2020 (UTC) - At this rate I will not be surprised if Hungary faces a credible attempt to kick it out of the EU by the end of this decade. Given its worsening human rights record and the fact it is now essentially an authoritarian state, if it were not already in the EU people would treat it like Belarus if it attempted to join. Granted, the EU is now in dire straits so they can bluster about universal rights but they can't really afford to kick it out just yet.-Flandres (talk) 23:34, 16 April 2020 (UTC) - More like the EU in its present form won't make it to the midpoint of the decade. Kicking out a member requires a unanimous vote of other members; Poland's ruling party is going down Hungary's path and will veto it. But Germany blocking any stimulus and enforcing crushing austerity for the second economic crisis in a row will tear it apart first unless they relent. --47.146.63.87 (talk) 01:11, 17 April 2020 (UTC) - @RationalHindu Shit. Hope Covid-19 takes him. Speaking of which, the guy who said SARS-CoV-2 is a divine punishment for Pride parades has got it.--Delibirda the Annoying Grammar Nazi (talk) 06:27, 17 April 2020 (UTC) - Hungary and to a lesser extant Poland are the total fucking embarrassments of the European Union (now that the UK is out). The only thing they listen to is having their EU funding cut (which the EU commission is slowly doing as much as the rules allow) and the EU court striking down laws like this. It will eventually lead to a show down where the EU can no longer allow them to operate with autonomy. If it were up to me they'd be out of the union at the snap of my fingers. But in the mean time the only tools that are available is cutting the funding they need because of their tanking economy because of the stupid laws they are enacting. anti-trans laws will never hold up in the EU-court. But in the mean time it certainly will make life miserable for trans in Hungary. AT least they can freely move to 27 other countries, many of which will be more than happy to support them. Though that certainly means leaving and losing the little support systems they have in the only home they know. Horrific really. ShabiDOO 09:45, 17 April 2020 (UTC) - And of course, they may also face a language barrier. The majority of Hungarians only speak Hungarian, which is virtually impossible to use outside the country.) @ 17:35, 17 April 2020 (UTC) - For now. Unfortunately as Britbongs should know a bunch of "foreigners" moving in tends to energize the bigots against the EU. "Get them out!" --47.146.63.87 (talk) 04:39, 18 April 2020 (UTC) - So, do we know if the Hungarian legislator are a bunch of fucking idiots, or a bunch of fucking stooges for this fuckin' prick? (Also backing Delibirda the Annoying Grammar Nazi's hope. Scum who make the situation worse deserve to be cursed with this, as punishment for the harm they've inflicted. Since in reality, it's liable to be the only punishment these scum face for their actions. And no, I'm not apologizing for this statement.)--NavigatorBR (Talk) - 23:19, 17 April 2020 (UTC) - Hungary's ruling party is neo-fascist and just passed their Enabling Act last month. This is where I remind people that Hungary was a Nazi German ally. Obviously this is not to say that Hungarians are all Nazis, but that far-right politics has a history there and unlike in Germany was never really publicly discredited. Sebastian Gorka is ethnically Hungarian, and a number of other ethnic Hungarians have been paling around with the English-speaking far-right. --47.146.63.87 (talk) 04:39, 18 April 2020 (UTC) HSUS[edit] The article about Humane Society of the United States really needs to be edited. If they are not PETA-tier bad, then the article should be deleted.Deleted it.--Delibirda the Annoying Grammar Nazi (talk) 08:03, 17 April 2020 (UTC)
https://rationalwiki.org/wiki/RationalWiki:Saloon_bar/Archive354
CC-MAIN-2022-21
refinedweb
20,287
68.5
The QAbstractEventDispatcher class provides an interface to manage Qt's event queue. More... #include <QAbstractEventDispatcher> Inherits QObject. Qt Solution includes a reimplementation of QAbstractEventDispatcher that merges Qt and Motif events together. See also QEventLoop and QCoreApplication. Typedef for a function with the signature bool myEventFilter(void *message); See also setEventFilter() and filterEvent(). Typedef for QPair<int, int>. The first component of the pair is the timer ID; the second component is the interval. See also registeredTimers(). Constructs a new event dispatcher with the given parent. Destroys the event dispatcher. This signal is emitted before the event loop calls a function that could block. See also awake(). This signal is emitted after the event loop returns from a function that could block. See also wakeUp() and aboutToBlock().. See also setEventFilter(). Flushes the event queue. This normally returns almost immediately. Does nothing on platforms other than X11. Returns true if there is an event waiting; otherwise returns false. Returns a pointer to the event dispatcher object for the specified thread. If thread is zero, the current thread is used. If no event dispatcher exists for the specified thread, this function returns 0. Note: If Qt is built without thread support, the thread argument is ignored. Interrupts event dispatching; i.e. the event dispatcher will return from processEvents() as soon as possible. the QEventLoop::WaitForMoreEvents flag is not set in flags, and no events are available, this function will return immediately. Note: This function does not process events continuously; it returns after all available events are processed. See also hasPendingEvents(). Registers notifier with the event loop. Subclasses must implement this method to tie a socket notifier into another event loop. Registers a timer with the specified interval for the given object.. Returns true if successful; otherwise returns false. See also registerTimer() and unregisterTimers(). Unregisters all the timers associated with the given object. Returns true if all timers were successful removed; otherwise returns false. See also unregisterTimer() and registeredTimers(). Wakes up the event loop. Note: This function is thread-safe. See also awake().
https://doc.qt.io/archives/4.3/qabstracteventdispatcher.html
CC-MAIN-2019-26
refinedweb
339
54.39
At 09:23 AM 11/7/2003, Jeff Trawick wrote: >see patch... seems simple enough, but perhaps somebody knows some showstoppers that would prevent this from being implemented on some platform? No, but the code's behavior is definitely not portable, and will make the user's code very buggy... >+APR_DECLARE(apr_status_t) apr_proc_check(apr_proc_t *proc) >+{ >+#ifdef _AIX >+ /* On AIX, for processes like mod_cgid's script children where >+ * SIGCHLD is ignored, kill(pid,0) returns success for up to >+ * one second after the script child exits, based on when a >+ * daemon runs to clean up unnecessary process table entries. >+ * getpgid() can report the proper info (-1/ESRCH) immediately. >+ */ >+ return (getpgid(proc->pid) < 0) ? errno : APR_SUCCESS; >+#else >+ return (kill(proc->pid, 0) < 0) ? errno : APR_SUCCESS; >+#endif >+} Wham. Zombie gone, result code not longer recoverable, if I understand things correctly? Solution is probably to cache all the resulting info within the apr_proc_t structure when the child is mopped up by any apr call, and let all of these status functions check that before looking at the actual process itself. Second problem - will the users registered otherchild handler still be called? I would say yes - it must be to be consistent - so if 'something changed' here, we should react - immediately or no? Bill
http://mail-archives.apache.org/mod_mbox/apr-dev/200311.mbox/%3C5.2.0.9.2.20031107101356.01211d38@pop3.rowe-clan.net%3E
CC-MAIN-2017-22
refinedweb
209
63.49
LoPy DevEUI set to 0000000000000000 Hello, The first time I got the LoPy DevEUI (dev_eui = binascii.hexlify(network.LoRa().mac())), it was a normal DevEUI type (70b3d549XXXXXXXX). A day after, it was 00000000000000. What could have occured to erase the hardcoded DevEUI of the LoPy? Thanks, Guizmo - andrethemac last edited by I have the same problem after upgrading to release='1.16.0.b1', version='v1.8.6-849-055728a on 2018-02-13' now I have to do a wlan init (and wlan deinit) to get the mac address firmware bug? tnx André I am using following script to set arbitrary DevEUI: fo = open("/flash/sys/lpwan.mac", "wb") mac_write=binascii.unhexlify("b44b2bdfea11fdb9") fo.write(mac_write) fo.close() Then reboot the device. "b44b2bdfea11fdb9" is an example of arbitrary DevEUI Could you please email me your wifi mac address to sebastian@pycom.io. You can get this by running: from network import WLAN import binascii print(binascii.hexlify(WLAN().mac())) @seb I used the Firmware update tool (last version) before loading any code on the board I also flashed the board with the mkfs command Have you performed any firmware updates, or tried to flash your own firmware?
https://forum.pycom.io/topic/2689/lopy-deveui-set-to-0000000000000000
CC-MAIN-2020-40
refinedweb
198
65.83
the river) you’d have to call your friend and ask for more information. Because this would be confusing and inefficient (particularly for your mailman), in most countries, all street names and house addresses within a city are required to be unique. Similarly, C++ requires that all identifiers be non-ambiguous. If two identical identifiers are introduced into the same program in a way that the compiler or linker can’t tell them apart, the compiler or linker will produce an error. This error is generally referred to as a naming collision (or naming conflict). An example of a naming collision a.cpp: main.cpp: When the compiler compiles this program, it will compile a.cpp and main.cpp independently, and each file will compile with no problems.! Most naming collisions occur in two cases: 1) Two (or more) definitions for a function (or global variable) are introduced into separate files that are compiled into the same program. This will result in a linker error, as shown above. 2) Two (or more) definitions for a function (or global variable) are introduced into the same file (often via an #include). This will result in a compiler error. As programs get larger and use more identifiers, the odds of a naming collision being introduced increases significantly. The good news is that C++ provides plenty of mechanisms for avoiding naming collisions. Local scope, which keeps local variables defined inside functions from conflicting with each other, is one such mechanism. But local scope doesn’t work for functions names. So how do we keep function names from conflicting with each other? What is a namespace? Back to our address analogy for a moment, having two Front Streets was only problematic because those streets existed within the same city. On the other hand, if you had to deliver mail to two addresses, one at 209 Front Street in Mill City, and another address at 417 Front Street in Jonesville, there would be no confusion about where to go. Put another way, cities provide groupings that allow us to disambiguate addresses that might otherwise conflict with each other. Namespaces act like the cities do in this analogy. A namespace is a region that allows you to declare names inside of it for the purpose of disambiguation. The namespace provides a scope (called namespace scope) to the names declared inside of it -- which simply means that any name declared inside the namespace won’t be mistaken for identical names in other scopes. Key insight A name declared in a namespace won’t be mistaken for an identical name declared in another scope. Within a namespace, all names must be unique, otherwise a naming collision will result. Namespaces are often used to group related identifiers in a large project to help ensure they don’t inadvertently collide with other identifiers. For example, if you put all your math functions in a namespace called math, then your math functions won’t collide with identically named functions outside the math namespace. We’ll talk about how to create your own namespaces in a future lesson. The global namespace In C++, any name that is not defined inside a class, function, or a namespace is considered to be part of an implicitly defined namespace called the global namespace (sometimes also called the global scope). In the example at the top of the lesson, functions main() and both versions of myFcn() are defined inside the global namespace. The naming collision encountered in the example happens because both versions of myFcn() end up inside the global namespace, which violates the rule that all names in the namespace must be unique. The std namespace When C++ was originally designed, all of the identifiers in the C++ standard library (including std::cin and std::cout) were available to be used without the std:: prefix (they were part of the global namespace). However, this meant that any identifier in the standard library could potentially conflict with any name you picked for your own identifiers (also defined in the global namespace). Code that was working might suddenly have a naming conflict when you #included a new file from the standard library. Or worse, programs that would compile under one version of C++ might not compile under a future version of C++, as new identifiers introduced into the standard library could have a naming conflict with already written code. So C++ moved all of the functionality in the standard library into a namespace named “std” (short for standard). It turns out that std::cout‘s. Similarly, when accessing an identifier that is defined in a namespace (e.g. std::cout) , you need to tell the compiler that we’re looking for an identifier defined inside the namespace (std). When you use an identifier that is defined inside a namespace (such as the std namespace), you have to tell the compiler that the identifier lives inside the namespace. There are a few different ways to do this. Explicit namespace qualifier std:: The most straightforward way to tell the compiler that we want to use cout from the std namespace is by explicitly using the std:: prefix. For example: The :: symbol is an operator called the scope resolution operator. The identifier to the left of the :: symbol identifies the namespace that the name to the right of the :: symbol is contained within. If no identifier to the left of the :: symbol is provided, the global namespace is assumed. So when we say std::cout, we’re saying “the cout that lives in namespace std“. This is the safest way to use cout, because there’s no ambiguity about which cout we’re referencing (the one in the std namespace). Best practice Use explicit namespace prefixes to access identifiers defined in a namespace. Using namespace std (and why to avoid it) Another way to access identifiers inside a namespace is to use a using directive statement. Here’s our original “Hello world” program with a using directive: A using directive tells the compiler to check a specified namespace when trying to resolve an identifier that has no namespace prefix. So in the above example, when the compiler goes to determine what identifier cout is, it will check both locally (where it is undefined) and in the std namespace (where it will match to std::cout). Many texts, tutorials, and even some compilers recommend or use a using directive at the top of the program. However, used in this way, this is a bad practice, and highly discouraged. Consider the following program: The above program doesn’t compile, because the compiler now can’t tell whether we want the cout function that we defined, or the cout that is defined inside the std namespace. When using a using directive in this manner, any identifier we define may conflict with any identically named identifier in the std namespace. Even worse, while an identifier name may not conflict today, it may conflict with new identifiers added to the std namespace in future language revisions. This was the whole point of moving all of the identifiers in the standard library into the std namespace in the first place! Warning Avoid using directives (such as using namespace std;) at the top of your program. They violate the reason why namespaces were added in the first place. We’ll talk more about using statements (and how to use them responsibly) in lesson 6.12 -- Using statements. Would be great to see a "Best Practice" suggestion in this section on how to avoid repeating ourselves when writing code that specifies namespaces. How do we not strain our fingers? Is there any way to add a code snippet std::cout when we type cout, for example? Or a shortcut that places "std::" in front of all recognized standard library verbs? etc. By the way - loving the course! 'Or a shortcut that places "std::" in front of all recognized standard library verbs? etc.' Wouldn't that defeat the purpose of namespaces? from the page -> 'When using a using directive in this manner, any identifier we define may conflict with any identically named identifier in the std namespace. ' How could it tell? The sentence "In C++, any name that is not defined inside a class, function, or a namespace is considered to be part of an implicitly defined namespace called the global namespace (sometimes also called the global scope)." Should read "any identifier" not "any name"? I tried causing a naming conflict with pow function but somehow it always chooses local definition I defined the pow function incorrectly to identify which pow function is used It didn't cause a name conflict because you did not include the std namespace, so it will only use the pow from the standard library if you use std::pow. If you want to cause a conflict, you need to insert "using namespace std;" into the 3rd line. There are two ways to use libraries defined in std namespace. explicitly using std:: as I've done or the using directive which has been advised against. In my program even when I add the using directive no conflict occurs and it uses my locally defined pow function. If I move the pow function to a separate pow.cpp file and create a pow.h header file for it. Then use #include "pow.h" before #include <cmath> then a name conflict occurs. But if I use it after cmath, the pow function used in the program is the one defined in cmath regardless if it has std:: or not. Turns out you have to be careful with libraries that have C equivalents <cxxx> <xxx.h> This is Wrong as even with including the Using namespace std; (using directive statement) in the third line there is no conflict Hey, I ran the first program to use main.cpp and a.cpp. The program compiled and I didn't get any output in the console window. However the project did abort in the build log. (C::B 20.3) This may be a dumb question, but how do we know that the linker did the aborting. I didn't see any wording to that effect in the build log. Is there someplace else the linkers error shows on C::B? Just don't use same function names 4Heed Hey as the scope is a compile time property if i do something like this for the first given example : (assuming I've already added necessary Header file and main function in main file) 1)a.cpp static void func(){ //Does nothing } 2)main.cpp void func(){ //Also does nothing } Will this work as each file is compiled individually and function in a.cpp has file scope so this shouldn't result in naming conflict right? P.S. sorry for not using code tags mobile browser has some issues with the website Yes, this works. Hello Thank you for the amazing amazing tutorials you provide. I was wondering if you have tutorials like these for other topic? Is it okay to use the "using" directive to access specific names from the std namespace? For example: Yes Here, you said the compiler can’t tell whether we want the cout function that we defined, or the cout that is defined inside the std namespace. I have a questions: We have main() and cout() functions which are defined inside a global namespace scope. So, cout(library) is defined inside a local scope of main(), while the function cout() lives in a global namespace, why there would be any conflict here? They are defined in two different scopes? > cout(library) is defined inside a local scope of main(), `cout` is a variable, it's defined in the `std` namespace, which you merged with the global namespace by `using namespace std;`. When I removed "using namespace std", then I didn't get any error! WoW! That's amazing! Thank you SO SO much! Here, the following code violates the second rule of ODR (2. Within a given program, an object or normal function can only have one definition. ), I was wondering why this program is compiled and linked properly without giving any error?! Here there are two definitions for "cout", one in library, one in a.cpp. One is `basic_ostream cout` in the `std::namespace`, the other is `int cout()` in the global namespace. They have different names (Because of the namespace), and different types. If you try to add another `int cout()` to main.cpp, you'll get an error. Actually cout(library) is NOT defined inside a local scope of main(). It was just "called" there. It is defined in the "iostream" library which you added to your global namespace when you specified "#include <iostream>" 1) "...this meant that any identifier in the standard library could potentially conflict with any name you picked for your own identifiers..." Shouldn't this sentence be written as?It is kind of implied that any name! this meant that any identifier in the standard library could potentially conflict with any name you picked, that has the same name as standard library's, for your own identifiers 2) "It turns out that std::cout's ." I think the above statement correct if this statement is added at the end "as long as we use std:: as prefix"; otherwise, we could have a identifier named "cout" in out program which conflicts with cout library! Hello, I looked at this example but I'm confused as to why we shouldn't use "using namespace". We get a compile error anyway even without the namespace, because you said in the previous lessons that we can't use a keyword for an identifier. So looking at the example, using namespace is safe as long as you don't use keywords as identifiers which is something we won't do anyway. Can you help me understand this please? Thank you This point is that the following code works: Later, you decide to add a function to your code, you call it "cout" There's nothing wrong with each of these snippets in particular. Note that it doesn't have to be you who added the `cout` function, it could come from a library too. When you combine the two codes, ie. add `cout` to the program, problems arise. These problems are unnecessary and could have been avoided by not `using namespace`. Perfect! I got it. Thank you Nascar. Can't you at least just do ... most people aren't going to be declaring their own namespace with cout. Much better than typing std::cout<< all the time It doesn't have to be you who defines another entity with the same name as on in a library. The `std` library itself has entities that collide with standard functions (eg. `std::min` vs `min`). Using `using std::cout` is better than `using` the entire namespace, but should be avoided still. If you know that the entity you're `using` doesn't collide with anything, you can add a `using` directive for it, but don't do so at file-scope. Add the `using` directive inside the function you're accessing the entity in. "and" Jonesville should read "in" Jonesville. Also, thanks for this website, it's the only programming course that I've managed to stick with so far. Lesson updated, thanks! Amazing tutorial do you have another tutorial like : data structure?! but in other lessons you say that compiler dont look what is int the other files so why its make error The compiler doesn't care about other source files, but the linker does. The compiler compiles each source file individually, the linker combines the compiled files into one binary. thank you, but for example as defined by a variable with the same name in different files, there is no error why If you define two variables in different files with the same name you get an error. We walk about this in the lesson on global variables. This tutorial is amazing bro this is an amazing tutorial , i'm actually enjoying it and also clicking on every ad to support it thanks a lot guys :) "A namespace is a region that allows you to declared names inside of it for the purpose of disambiguation" Grammatical error. Change "declared" to "declare"! Merry Christmas! Fixed, thanks! "There are a few different ways to do this." Only two are mentioned here, better to say: "There are a couple ways to do this." or "There are a few different ways to do this. We will highlight two here, the other methods (?) are bad (?)." Hello Alex! I would be thankful if you can find a way to show the readers which part of the tutorial is updated or which new content is added. I went through this tutorial quite some time ago and now I do not know what to look for in this update. :) Thanks Unfortunately I'm not aware of any easy way to do this. :( very good notes "Avoid using directives (such as using namespace std;) at the top of your program. They violate the reason why namespaces were added in the first place." then why "using namespace" was introduced? When will it be useful? The rule isn't "never use", it's "avoid". There are cases in which `using namespace` is useful. If you know that your libraries are compatible with each other (`std` isn't even compatible with other parts of C++, so don't use `using namespace std;` unless it's in a small scope), you can use `using namespace`. It can still be useful when used inside a smaller scope, such as a function. @Alex please explain it with an example..why can it be used inside a smaller scope, such as a function? Using `using namespace` in a function limits the scope that's affected by the `using` directive. Anyone reading the function should be able to see the directive and write code accordingly. If the directive was at file-scope, it's easy to miss. I'll use `chrono` for an example of a `using` directive. It doesn't make sense for `std`. As you can see, it makes sense `using namespace` in this case, as the code without it is a lot longer and not as easy to read. If we used the namespace at file-scope, we wouldn't be able to user other user-defined literals anymore. Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/2-9-naming-collisions-and-an-introduction-to-namespaces/
CC-MAIN-2021-17
refinedweb
3,091
71.34
Asynchronous Execution in Visual Basic .NET Brian A. Randell MCW Technologies, LLC June 2003 Summary: Tackles one of the most common practical uses of multithreading and shows you how to execute a task on a secondary thread that does not block the main user interface (UI) thread of the application. (11 printed pages) Download the VBMultiThreading.msi sample file. Note To run the sample application, you will need a version of Microsoft Windows® with version 1.0 service pack 2 (SP2) of the .NET Framework installed. All code presented in this article is Visual Basic® .NET, written and tested using Visual Studio® 2002. Testing was done on Windows XP Professional SP1 system. Introduction Using File Search Non-blocking User Interfaces Details of the Sample Application Only the Tip of the Iceberg Introduction With the release of Visual Basic .NET, Visual Basic developers can safely create secondary worker threads. Yes, I know there were ways around this in earlier versions of Visual Basic, but except for the Timer control, any other mechanism required tricks with the Win32 API or the use of third-party controls. In Visual Basic .NET, creating a secondary thread is as easy as this: Proper use of multiple threads in an application is, of course, not this easy. Multithreaded programming is hard—really hard. The goal of this sample application is to tackle one of the most common practical uses of multithreading—the ability to execute a task on a secondary thread and not block the main user interface (UI) thread of the application. The sample application is a simple program that searches a specified drive for files that match a search specification, such as *.vb. The program itself is written as two components: - A Windows Forms application providing the user interface in FindFiles.exe. - The actual search for files taking place in a Class Library project and compiled as FindFilesLib.dll. The sample application supports Debug and Release versions as is usual. The Debug version has extra code that logs certain events to a text file that you specify. (See the Appendix at the end of the article for more information.) Remember, multithreading is a large topic. This sample application focuses on solving only one type of problem. The problem to solve is how to search for files and not block the UI. In addition, the sample application needs to support a cancel feature to end the search if the user clicks the Cancel button. For more information, see the References at the end of this article. Using File Search File Search allows you to search a specified path for a file or set of files using a specific file name or wild cards. Getting started requires that you choose either the Debug or Release version. The Debug version of the sample application requires a valid path for the debug trace file. Specify this path by setting the value of the mLogFile variable defined in the Control class. There are a few Debug.Assert statements in the Main method used to validate the value specified. In addition, the application removes the default trace listener, the Output window, so that it isn't polluted with all of the data going to the log file. Clicking the Search button after the application is loaded starts the process. By default, the application will search the local C: drive and all its subdirectories for files ending in the .vb extension. The release version works the same way excluding the creation of the log file. You can change the drive searched by selecting it from the combo-box labeled Look In. In addition, you can type any valid drive and path combination. If you want, you can click the ellipsis button (labeled "…") to the right of the combo box to invoke the standard Windows Browse For Folder dialog. If you're interested in how this was accomplished, you can take a look at the class FolderDialog, as the dialog itself is not directly exposed by version 1.0 of the .NET Framework (Special thanks to Ken Getz for providing the code.) Finally, you can reset the UI to its original size by selecting the Reset Size command from the View menu. Also, if you want some information about the process and the number of threads allocated by the common language runtime, you can open the sample application's About Find Files dialog box, select the Information tab, and then click on the Process Information icon as shown in Figure 1. Figure 1. About Find Files dialog and corresponding icons Non-blocking User Interfaces The core issue in the sample application is to have a non-blocking user interface. The first major issue to consider is how to get the search to occur on a worker thread. The next problem that many developers aren't aware of is that UI elements must only be "touched" by the thread that created them. This is a rule imposed by the current Windows GDI architecture upon which Windows Forms is built. The final two problems are how to build a class that is thread-safe and does not pummel the client with too much information, negating the benefit of the worker thread. Threads The .NET Framework provides rich support for multiple threads of execution. There are two interesting classes in the .NET Framework specifically related to threads: - System.Thread.Thread - System.Diagnostics.ProcessThread The Thread class represents a managed thread. You can create managed threads explicitly, or use the managed threads provided by the ThreadPool. Managed threads do not necessarily correspond one-to-one with operating-system threads. The ProcessThread class, on the other hand, represents an operating-system thread. Use the ProcessThread class to obtain diagnostic and performance information. When you work with threads in your applications, there are different personas applied to threads. It is possible for a thread to embody more than one persona at a time. Some of these personas are exposed as properties of the Thread class. Others are implied by the behavior of the thread. The following table lists some personas and additional information. Because threads can have various personas in your application, you will often want to distinguish one thread from another. The Win32 API provides each unique thread with a 32-bit thread ID. This ID is available by accessing the shared GetCurrentThreadId function of the System.AppDomain class. This ID represents the physical OS thread. Remember, the common language runtime maps its own abstraction on top of Win32 threads. It is possible for the runtime to map multiple runtime Thread instances to one OS thread. So, although it is useful to know which OS thread is performing the work, you are more interested in the runtime Thread instance. Accessing the current runtime Thread instance is accomplished by accessing the shared, read-only property CurrentThread exposed by the Thread class. Because multiple runtime threads can be mapped to an OS thread, you need a way to tell one thread from another. This is accomplished by giving each thread a name. Unfortunately, the only way to give a thread a name is to actually have code running on the thread. Unlike ProcessThreads, there is no way to enumerate a collection of all the managed threads in an application domain or process. Rather, you must check to see if a runtime thread has a Name ( Thread.CurrentThread.Name Is Nothing), and if not, give it a name to distinguish one instance from another. You will find that in the Debug version of the sample application, that's exactly what is done. In most procedures, the current thread is interrogated and given a name if it doesn't already have one. If you examine the Threads window (accessible during a debugging session by means of the Debug, Windows, Threads menu), you will be able to see the current thread's ID, Name, and other information. Figure 2 shows the Threads window during a debugging session. Figure 2. The Visual Studio .NET Threads Window During a Debugging Session of FindFiles.exe In Figure 2, note that there are three threads shown. One is named Main Thread and another is named Thread Pool Thread:FindFiles. Both were named by the application code. The third thread doesn't have a name, but if you do some poking around, you'll find that this background thread is used by the common language runtime when it performs garbage collection. If you want to verify this, uncomment the code for FileSearch's Finalize method. The Thread Pool and Delegates Now that you know a bit about threads in a managed application, you need to know how to actually get a worker thread started. As mentioned at the beginning of this article, you can create your own threads, but you won't be doing it in this sample application. The common language runtime team knew that developers would want to use more than one thread in their applications. To facilitate this, the runtime automatically creates a thread pool of up to 25 worker threads for each Windows Forms application. On symmetric multiprocessing (SMP) computers, there will be one thread pool per processor. Note that the runtime does not necessarily allocate all 25 threads when a program starts. So the question that should be swimming through your head is, "How do I use threads in the thread pool?" There are a few ways to use a thread from the thread pool. You're going to access the thread pool through delegates. Delegates are sometimes referred to as type-safe function pointers. Delegates provide a way to prototype a specific method signature without knowing what type is going to provide the implementation. Delegates are useful when defining callback operations and are the foundation for Events in the .NET Framework. In order to access a worker thread, tell the worker thread what code you would like to execute and, optionally, what piece of code you would like notified when the task completes. One of the reasons delegates are preferred over other methods is that you can pass parameters to the worker thread and the runtime takes care of all the nasty details. If you investigate creating your own threads using New Thread, you will find it's a bit of work. The first thing you need to do is to define a delegate that matches the signature of the method you want to execute. In the sample application, you want to execute the FindFiles method of the FileSearch class. Note that either the component that contains the FileSearch class or the consuming application can define the delegate. In this sample, FindFilesLib exposes a delegate. Here's the signature for FindFiles: Here's the signature for its matching delegate: That's not too difficult. The big difference is that there is code inside the FindFiles method. Delegates are abstract types like interfaces and they don't provide their own implementation. Note that the runtime does provide a bunch of plumbing to make delegates work, but you don't write any delegate-specific code. With the delegate defined, you now can call FindFiles asynchronously. In the sample application, you will find the code to do this in the Click event for the button named btnSearch. The relevant code is listed below:btnSearch. The relevant code is listed below: ' Defined in the declarations section of frmMain Private mobjFileSearch As FileSearch ' Code omitted for clarity mobjFileSearch = New FileSearch(Me.cboLookIn.Text, Me.txtFileName.Text) Dim cb As New AsyncCallback(AddressOf Me.OnFindComplete) Dim del As New FindFilesDelegate(AddressOf mobjFileSearch.FindFiles) del.BeginInvoke(cb, del) First, you need a reference to a valid instance of the type that will be performing the work. This is the mobjFileSearchmobjFileSearch). At this point, all that is left to do is to execute the code. As mentioned, the runtime provides the actual plumbing that makes delegates work. To execute asynchronously, call the BeginInvoke method off of the delegate variable. When BeginInvoke is executed the first time, there will be a slight delay as the worker thread is fired up. Once it has started, the runtime returns control to the calling thread, leaving the UI free to do other tasks. Updating the UI With the worker thread happily on its way, the next issue is how does the worker thread notify the client when it finds a file? As with any programming problem, there are many solutions. A simple way is to fire an event. When a worker thread fires an event, the event is processed by the client code using the same thread. This becomes a problem because you want to update the UI (the ListView control) with the found file's information. As mentioned earlier, UI elements can only be "touched" by the thread that created them. The worker thread cannot put data into the ListView. The Windows Forms designers knew this little glitch would come up, so they exposed a special delegate version of BeginInvoke off of each control (including forms, which are, in fact, glorified controls). You use BeginInvoke to perform a thread switch from the worker thread back to the UI thread where you can safely update the controls. In addition, every control exposes a Boolean property, InvokeRequired, so that you can easily check whether or not you need to switch threads. BeginInvoke is subtly different than the previous example in that it supports two overloaded versions. Version one accepts a single parameter. A delegate reference representing the code you wish to use to update the UI. The second version accepts an additional parameter—an array of objects representing the input data. In either case, it has the same effect: switching threads. Here's a pared down example from the sample application showing it in action: Thread Safety A big issue for Visual Basic .NET developers moving from earlier versions is thread safety. If you created a component in Visual Basic 6.0 for example, the Visual Basic runtime protected you from the complexities of multithreaded component development. All of your code executed is in either the Main COM thread or in another single-threaded apartment (STA). The STA protected your code from simultaneous access by multiple threads. This was the default behavior. In the .NET world, all bets are off. The code you write is inherently thread-unsafe. Your components are responsible for all thread synchronization issues. Yes, now you too can use mutexes, synclocks, and so forth, to control access to your data. Be careful what you ask for; you just might get it. (This topic however is beyond the core focus of this sample. Please see the references listed at the end of this article for more information.) The code for this sample application is written to be thread-safe using locking primitives as necessary. See the comments in the code for more information. Being Polite to the Client The final issue we need to worry about is building a polite component. The component is thread-safe and supports asynchronous execution. The final step is making sure the component doesn't overwhelm the client with too much information. If it did, it would negate the benefit of multiple threads. It turns out that the main issue is the UI itself. It is our main point of contention. You want the UI to update when there is new information from the worker task. In this sample application, that means new directories and new files found. However, the UI also needs to be able to do other tasks. If it's always busy processing new directory and new file-found events, it will never be able to respond to other demands like the user clicking the Cancel button. The solution is to have the component expose a Boolean ClientIdle property. The client can notify the component when it's doing nothing and allow the component to raise events. If the client is busy, the component will store the interesting data, such as the file found, in some client-accessible data structure. The client can then retreive the data when it has a chance. In addition, what's elegant about this solution is that a client can run the task without listening to events at all. The client can simply wait for the callback to occur, signaling completion, and then harvest the data at the very end. This allows the component to be used in applications such as ASP.NET, where periodic events are not reasonable. Details of the Sample Application At this point you should have a pretty good idea of the issues involved in writing a UI that supports asynchronous operations, provides periodic notifications, and is responsive to the user. Let's look at some of the more unique aspects of the sample application. Listening to Events As mentioned earlier, the class FileSearch fires an event when it finds a file as well as when it changes directories. The two events are listed below: Events in Visual Basic .NET use the somewhat familiar syntax provided in previous versions of Visual Basic. There are also features provided that make it even more flexible. For instance, the ChangeDirectory event is defined using a delegate: The MoreFilesFound event uses a system-provided delegate System.EventHandler. The events could have been defined as follows: Which way is better? It isn't really an issue of which is better. It turns out that the first way can be more flexible. The reason it was done in this sample application is to expose you to the feature. In addition, this method is more explicit in showing how events are a convenient wrapper on top of delegates. Regardless of how the events are defined, the client application can hook the events in one of two ways. The first way is to statically bind, using WithEvents. The downside to this is that the client is always listening. With Visual Basic .NET you can dynamically hook events, as well as stop listening. This is done using the AddHandler and RemoveHandler commands. Examine the code in btnSearch_Click and OnFindComplete for examples. Accessing Shared Data To be polite, a component should not hammer the client with a constant barrage of events. In this sample application, a Queue object is used to store instances of FileInfo objects every time the server code finds a file. If the client application is interested in knowing when a file is found, the client code sets the FileSearch's ClientIdle property to True. Then when the FileSearch component finds a file in the EnumFiles method, it checks to see if the client is idle and that there is a least one FileInfo object in the queue. If both conditions are met, it fires the MoreFilesFound event using RaiseEvent. The client can the tell the server to not fire anymore events by changing the ClientIdle property to False, performing the thread switch to the UI thread by means of BeginInvoke, and letting the server continue searching. While the server component is searching, the client application can access the queue through the read-only FilesFound property of the FileSearch instance. The client is free to read as many files as it wants. The sample has the client application read only 25 files at a time before it returns to normal processing. When it's ready to check for more files, it simply sets ClientIdle to True and the process repeats. Notes on the Queue object The Queue object used is built into the .NET Framework and is available in the System.Collections namespace. A queue is a great data structure as it supports adding (enqueuing) and removing (dequeuing) from the object at the same time. It's the job of the queue designer to handle multiple threads. It turns out that the .NET Framework designers did just that. You can access a synchronized version of the queue by calling the shared Synchronized method of the Queue class passing the queue instance you want synchronized as the parameter. Task Completion When the search is started, the UI tells the worker thread through BeginInvoke where it should call back to when the task is complete. One thing to remember is that the callback occurs on the worker thread. It is still necessary to perform a thread switch in order to safely finish updating the UI. Finally, one of the major benefits of having a callback for task completion is the opportunity to check whether the process completed successfully. If you fire a delegate using BeginInvoke without specifying a callback object, there will be no way to know if the task failed. When you callback procedure is called, you can check for exceptions by calling the appropriately named EndInvoke function. You should always call EndInvoke within a Try/Catch block because any untrapped exception that occurred in the server will be thrown within your callback procedure. See the code in OnFindComplete in the sample application for details. Only the Tip of the Iceberg As you examine the code in the sample application, remember that this is a focused example in a very large world of possible scenarios. It has only touched on the possibilities of what can be done with Visual Basic .NET and the .NET Framework. References Currently I have not found any book dedicated to concurrent programming with threads and delegates with the .NET Framework or Visual Basic .NET. There are some good chapters in the following books: - Programming Microsoft Visual Basic .NET by Francesco Balena [Microsoft Press, 2002, 0735613753] - Essential .NET, Volume I: The Common Language Runtime by Don Box [Addison Wesley Professional, 2002, 0201734117] Other books that do not have .NET Framework or Visual Basic .NET concepts or samples, but are worth reading include: - Win32 Multithreaded Programming by Aaron Cohen and Mike Woodring [O'Reilly & Associates, 1998, B00007GW3Z] - Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea [Addison Wesley Professional, 1999, 0201310090] Appendix A: a note about the Debug log If you run the application using the Debug build, you can get a trace log showing what thread a particular piece of code is running on. This can be useful to understand what is going on inside the program. The log file is created in the Control class's Main procedure (defined in the frmMain.vb source file). Before the program will run, you need to set the value of the variable mLogFile defined in the declaration section. Once set, the file will automatically be created when the program starts. Note also the code in Main turns OFF the default trace handler for the Debug (Output) window. See the comments for more information. The constant MaxTraceLines defined in both frmMain and FileSearch determines how many trace lines to write out. The values are currently set at an arbitrarily low value to reduce the size of the log file. Change to your taste. The number of log entries that will be created can be deduced using the following information:
http://msdn.microsoft.com/en-us/library/aa289178(v=vs.71).aspx
CC-MAIN-2014-42
refinedweb
3,822
64.1
. The length of dynamically allocated arrays has to be a type that’s convertible to std::size_t. We could use int, but that would cause a compiler warning when the compiler is configured with a high warning level. We have the choice between using std::size_t as the type of length, or declaring length as an int and then casting it when we create the array like so: std::size_t int length 9, fixed arrays can also be initialized using uniform initialization: Explicitly stating the size of the array is optional. Doing so can help catching errors early, because the compiler will warn you when the specified length is less than the actual length. As of the time of writing, the GCC still has a bug where initializing a dynamically allocated array of chars using a C-style string literal causes a compiler error: If you have a need to do this on GCC, dynamically allocate a std::string instead (or allocate your char array and then copy the string in). time Question #1 Write a program that: * Asks the user how many names they wish to enter. * Dynamically allocates a std::string array. * Asks the user to enter each name. * Calls std::sort to sort the names (See 9.4 -- Sorting an array using selection sort and 9.11 -- Pointer arithmetic and array indexing) * Prints the sorted list of names. std::string std::sort std::string supports comparing strings via the comparison operators < and >. You don’t need to implement string comparison by hand. A reminder You can use std::getline() to read in names that contain spaces. std::getline() To use std::sort() with a pointer to an array, calculate begin and end manually std::sort() Show Solution hi Alex and Nascardriver i wanna ask you about this snippet of code below: it seems to me that we actually don't need to do indirection(putting an '*'/asterisk) in order to access each member of the dynamic array, doesn't it? Why is that so? Why does this work differently compared to when we're accessing single dynamic variable? Thanks before! The [] operator does an implicit dereference. Hi, I have a question about c-style string symbolic constants and dynamically allocating array. when I try to delete name after newing a piece of memory,the compiler suggest me to use delete instead of delete[]. I undestand name only store the address of the pointer to the only-read string. However, if I only delete the pointer to pointer(which is name), will the string itself cause a memory leak? You're not allocating a string, so there's no string to be deleted. You're allocating a pointer and deleting a pointer. A dynamic allocation of a char array initialized from a string literal looks like this Thank you, I think I get the point. So, the string "Alan" itself will stores in static memory and the pointer to this string is allocated by dynamic allocation. However, when I delete the pointer, do I also lose the memory address of string? Yes, you lose the string. The string remains in memory, but it's inaccessible unless you have another pointer pointing to it. Thank you! I misinterpreted the question, so I went in the "harder way" and actually am glad my code still worked: I know I broke the "Don't repeat yourself" rule in the output of the array of strings, but it was just because I didn't find necessary to make a function to it... Hi Alex and nascardriver, this is what I did for the program asked. It works fine but I wanted to know any suggestions so that I can improve this piece of code. I'm an absolute beginner and I had a hard time understanding dynamic memory allocation and how pointers work and I'm starting to understand how it all connects. Thanks for your hard work! I think there needs to be a bit more info on using std::sort for the quiz question. The section 9.4 example uses the begin() and end() functions for the arguments, which won't work here with the pointer-to-array, and pretty much every online reference on sort() talks about iterators which are later in the course. This was shown in lesson 9.11 with `std::count_if()`. I've added a reminder to the quiz. “How does array delete know how much memory to delete?” The answer is that array new[] keeps track of how much memory was allocated to a variable, so that array delete[] can delete the proper amount. Unfortunately, this size/length isn’t accessible to the programmer Can you please explain what do you exactly mean when you say that the size isn't accessible to the programmer? For some reason i'm a bit lost here. Thanks Although it might be known to the run-time, there is no way to access a dynamically allocated array's size. So no using std::size() or sizeof() for dynamically allocated arrays right? Never use `sizeof()` for arrays since C++17. `std::size()` tells you that you can't use it with decayed arrays if you try to do so. If you dynamically allocate an array, you have to keep track of its length yourself. Got it. Thanks Pointers in this chapter are all declared as , although it was written somewhere that we should stick to Is it OK or should I point out this issue in each chapter this occurs? Thanks for pointing it out. I won't fix the pointers in this lesson, because it's due for an overhaul anyway. I suspect there are a lot of lessons where this is "wrong". If you're going to write a comment anyway and you happen to see that the lesson is mis-formatted, please point it out. Don't go out of your way just to write comments about wrong formatting, that'll generate too much work for you as well as us. Also, just curious - what's the difference between std::getline() and std::cin.getline()? Which one should we use, or does it not matter? std::getline works with C++ strings (std::string) whichis what you want. std::cin.getline works with c-strings (char[]) which you do not want. Ah, thanks for the reply. Back to a previous lesson where you guys explained how array[0] is the same as *(array), does array DECAY when you do array[0]? If so, it would turn into "memory address of first element"[0], which would be the same as *("memory address of first element")? Hi. This's my code for question. I am not sure, is it good or something needs changes? Today I Learned, that "Unlike C, C++ allows dynamic allocation of arrays at runtime without special calls like malloc() ...". And to my surprise this runs: I remember that I had been told this does not compile and I had checked in early 2000s in Turbo c++ and Borland c++. Why is this???? This isn't valid C++. Your compiler is misconfigured. I saw it here: You can check here that it runs: But I checked in VS2019 and it did not compile as expected. Hi Nascardriver and Alex, Almost the same solution, I was struggling a bit with std::sort (and calling the std::begin and std::end), instead of sort(<pointer>) What do you think? Hi! - Line 16, 17, 30: List initialization - Line 17, 30: Pre-increment is cheaper than post-increment - `size_t` is C, `std::size_t` from <cstddef> is C++ - Avoid returning manually allocated memory. The caller of `returnNamesFromUser` can't know that they have to `delete[]` the memory. Keep the `new` and `delete` in the same function if possible. Thank you nascardriver. What book do you recommend for the beginner, Is the "C++ Primer" good enough? I'm on the final year of my CS college, but I had a break for a couple of years due to private and health issues. So I'm getting back to path to finish college, and I'm starting by revising C++ (it's the best starting point for the development). I can't recommend any books, I don't like books. They get outdated with no way of updating or marking them. You'll read a book not knowing that what you're reading is deprecated or bad practice. Ah I see. You are right, I have started working with Primer, but I'm following the best practices from here. Can you share your dev experience, for sure you are working for 10+ years. It's hard to find guys such as you and alex, to have patience with the students. Be sure to read up on how C++ has changed since the book's release I'm developing since 2012, professionally since 2020. From my experience so far, developing professionally slows down my learning process, because I don't have as much time to play around and I'm limited in tools, whereas I could do whatever I want for however long it takes non-professionally. I understand you fully. I'm working in IT industry for 5 years now, but mostly testing and mgmt agile work. When your work for 8 hrs and you have family there is less and less time for yourself. Do you watch f1 besides nascar? I only know Jeff Gordon, number 24. Thank you very much for your time. I watch neither actually. Maybe I'd watch f1/e if it were easily accessible via kodi Hey! I didn't understand std::size_t function. Could you explain that again? And why did we not delete the size_t variable after ending `std::size_t` is a an integer type. You only need to `delete` variables that you created with `new`. mine was far from the answer given #include <iostream> #include <iterator> // for std::size #include <algorithm> // for std::sort #include <string> // for std::string int main() { std::cout << "How many names you wish ? : "; std::size_t nameCount{}; std::cin >> nameCount; std::string *names{ new std::string[ nameCount]{} }; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); for (std::size_t elem{ 0 }; elem <= (nameCount - 1); ++elem) { std::cout << "\n" << elem + 1 << ". "; std::getline(std::cin, names[elem]); } std::sort(names, names + nameCount); for (std::size_t elem{ 0 }; elem <= (nameCount - 1); ++elem) { std::cout << "\n" << elem + 1<< ". " << names[elem] ; } delete[] names; return 0; } i was having some difficulties remembering which headers to include for each functions we use like std::string then i realized i had std::string typed in without the compiler giving any errors even though i did not have #include <string> typed in. how is this possible ? ALSO why is it that when i type int *ptr my compiler automatically moves the * to int int* ptr Section "Headers may include other headers" That's your auto-formatter forcing you to use a consistent style I'm slightly confused - for the quiz, I forgot to #include <cstddef> and <string> (I didn't use std::limit in my solution), but my code that had both std::size_t and std::string in it compiled, and ran fine. I then tried removing the <algorithm> and <iostream> headers, and it will only compile if <iostream> is in it, but otherwise it doesn't seem to matter. What's going on here? Does <iostream> implicitly #include all of the std namespace? If so, why wouldn't we use something like #include <stdlib> (I don't know if that's a real header, I mean it as an example) to have the whole library at our disposal? Thanks! Hey there LOL mine too. i seem to recall some notes in the early chapters about this but i forgot now. i was able to use size_t without including the <iterator> header Yeah, I found it in Chapter 2.10: My co-worker showed me how to use for strings and how to use it if the comparator is not defined. He also said if you were building this with optimized resource management in mind, put at the end of the program right before Does that seem about right to you? Also, what's a comparator and when is it used? Ah I see the solution now! I couldn't get std::sort to work without accommodating for the comparator in Virtual Studio 2019! Maybe if I used "auto" for creating and initializing the array this would have worked? Yes, it was creating and initializing the array as type "auto"! `std::sort` uses `operator<` of the array's type by default. Since `std::string` has `operator<`, you don't need to provide a comparator. You only need to provide a comparator if the type's `operator<` doesn't exist or doesn't do what you want. You always need to `delete` things that you created with `new`, no matter if you have resource management in mind or not. Omitting `delete` causes memory leaks and can prevent some types from functioning properly. Understood, yes this is making a lot of sense now. Starting to connect the dots. Got it without looking at the solution :) Took over an hour though experimenting. Tried to find an easy std::sort, but just recycled the bubble sort function from last time. using selection_sort #include <iostream> #include <algorithm> void selection_sort(std::string *data, int length){ for(int start_index{0}; start_index<length - 1; ++start_index){ //menampung nilai terkecil char smaller = start_index; for(int current_index{start_index+1}; current_index<length; ++current_index){ if(data[current_index] < data[smaller]) smaller = current_index; } std::swap(data[start_index],data[smaller]); } } int main(int argc, char const *argv[]){ std::cout<<"How many names would you like to enter? "; size_t name_size{}; std::cin>>name_size; std::string *name{new std::string[name_size]}; for(int i{0}; i<name_size; ++i){ std::cout<<"Enter name #"<<i+1<<":"; // std::getline(std::cin,name[i]); std::cin>>name[i]; } std::cout<<"\nHere is your sorted list:\n\n"; selection_sort(name, name_size); //std::sort(name,name+name_size); for(int i{0}; i<name_size; ++i){ std::cout<<"Name #"<<i+1<<':'<<name[i]<<std::endl; } delete[] name; return 0; } 6. This is most confusing as I assumed that we should use the the 2nd line due to "initialize a dynamic array". However, the recommended way is auto *array{ new int[5]{ 9, 7, 5, 3, 1 } }; 7. std::sort I went to Chapter 6.18, 6.4 to look at the std::sort example which used std::sort(std::begin(array), std::end(array)); instead of std::sort(names, names + length); This is most confusing to new students as we would use the first pattern taught to us. The pattern changes here and examples are not consistent with the Quiz. Perhaps, the std::sort(names, names + length); could be highlighted in the std::sort example in 6.18? 8. Test your skills If the intent is to throw a confusing and difficult hoop to jump through, could it be done in a separate final chapter called "Test your skills"? "Test your skills" can have the most intricate patterns and students won't have to go through tutorial hell. 9. Thanks Lastly, thanks for the tutorial. I hope it can get better in the following years. 1. After too many errors, I went to the solution. 2. // Ignore the line feed that was left by std::cin. std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); Some of the steps are not covered. The solution is quite obfuscated. 3. Did not consider include #limits at all. Also, added an unnecessary header #include iterator for std::size. 4. Stack vs Heap Perhaps, it would help to point out that int is on the stack while int* is on the heap? Both are on the RAM but they are on different parts. Static memory for int and dynamic memory for int* It seems that there is a major difference due to memory allocation. Got that from 5. Would you be willing to add a 1 minute Youtube videos in between each line? I get a feeling that there's only so much you can explain with written text. You can't explain C++ tricks, show diagrams or point out complex examples. 2. Lesson S.4.4b and 5.10 3. <iterator> is required for `std::size()`. 4. I don't see how that would be useful. This was mentioned in the previous lesson. 4. I don't see how that would be useful. This was mentioned in the previous lesson. If you search "int* heap" in the search bar, the earliest reference to it is Chapter 6.16 and the most relevant result is Chapter 7.9. If you look at your index, the order is wrong. You teach 6.16 AFTER 6.9a. That is like not declaring the variable first. P.6.9a Dynamically allocating arrays <<<<<----- P.6.10 Pointers and const P.6.11 Reference variables P.6.11a References and const P.6.12 Member selection with pointers and references P.6.12a For-each loops P.6.13 Void pointers P.6.14 Pointers to pointers and dynamic multidimensional arrays P.6.15 An introduction to std::array P.6.16 An introduction to std::vector <<<<<<----- P.6.17 If you look in the comments, there's a 2015 comment that asked the same question. Feedback. If you initialize a dynamic array but you don't reference it. Crash. Error 0x80072000. This results in a peculiar scenario for a newbie as I would write a partial piece of code then debug it. However, if I write the partial piece of code, crash. Arrays conflict with the normal notion of part by part as there must be a reference to the array, else crash. 1. Problem with Normal initialize array std::array arr{ 13, 90, 99, 5, 40, 80 }; Dynamic initialize array std::cout << "How many names would you like to enter ? " << '\n'; std::size_t noOfNames{};//Number of names = Length std::string* array{ new std::string[noOfNames] }; std::cin >> noOfNames;//Get the number of names as an integer std::sort(arr.begin(), arr.end(), greater); std::sort seems to return an error. I read the comments and I think someone else had the same problem. This is a common error. What error? A 0x80070002 error. So, doing this section's quiz question, I had some serious errors getting kicked up, most (not all!) of which seemed to revolve around my use of std::sort. As explained in section 6.4's brief intro to std::sort, I was calling thus: yet in particular this was kicking up "A pointer to a bound function may only be used to call the function" error messages, which I tried (but rather failed) to comprehend. It took me (on a whim) trying without the calls to std::begin() and std::end(), to finally get it to work. But can you help me understand why? And if this is the correct syntax for std::sort, why is it explained differently in 6.4? Thanks very much! `std::begin` and `std::end` only work on built-in arrays and on objects that provide `.begin()` and `.end()` functions or overloads for `std::begin` and `std::end`. Your `nameArray` is neither a built-in array nor an object with the functions mentioned above. It's a simple pointer. `std::begin` and `std::end` can't do anything with a pointer. `std::sort` (And most other standard algorithms) need to know where your container begins and where it ends. That's exactly what you calculated with `nameArray` and `nameArray + numNames` (This was shown in lesson 6.8a for `std::count_if`). Ah. Thanks for that. Despite being told "A dynamic array starts its life as a pointer that points to the first element of the array," I think I hadn't quite clocked that 'a pointer TO an array' was what I had (unwittingly, it seems) created with which made it difficult (read: 'impossible') to recognise that std::begin and std::end were never going to work with it as I'd expected. I THINK I get it now. :-P Cheers! Okay, dynamically allocated arrays are what I needed for that pig latin translator, how's this? piglatin.cpp: funcprotos.h: I'm going to turn it around this time and have you figure out improvements: - What is the difference between `std::size_t` and `size_t`? - Which header did you include to make `size_t` available? - Why is `isVowel()` operating on `std::string`? - What happens when you call `isVowel({})`? - What there be a difference if `isVowel()` used a `switch`-statement? - What happens to your program if the dynamic allocation fails? - What happens when you call Left comments in the code saying what I fixed. On that last one, do you mean std::string *arr{ {} } or std::string arr[]{}? The std::size(arr) doesn't work on dynamically allocated arrays because it's actually std::size(std::string *) and size() doesn't take that argument. If it's a fixed array, it will work because it decays into a pointer when it's passed to the function, in the function call, the compiler just figures out what the value is that it should be sending to the function, at least that's my best guess. piglatin.cpp: > - What is the difference between `std::size_t` and `size_t`? > - Which header did you include to make `size_t` available? Yep > - Why is `isVowel()` operating on `std::string`? Copying/constructing a string was expensive and is confusing to the caller. When is `isVowel("hello")` true? When there is at least 1 vowel in the string? When all letters are vowels? When the word starts with a vowel? The confusion has been removed by changing the parameter to `char`. > - What happens when you call `isVowel({})`? This would have caused undefined behavior, because you can't use `.front()` on an empty string. Changing the parameter to `char` prevents this. > - [Would] there be a difference if `isVowel()` used a `switch`-statement? The `switch`-statement is faster, because the compiler can generate a search tree. When you use the conditional operator or an `if`-statement, the comparisons have to be performed left-to-right. > - What happens to your program if the dynamic allocation fails? Good fix. Without aborting, the other functions would have resulted in undefined behavior, because you'd be passing in `nullptr`. If you're going to abort anyway, you might as well use the throwing version of `new`. When the exception leaves main, a message will be printed and the user can see that they're out of memory. > - What happens when you call I meant exactly the code I wrote. `std::string arr[]{ {} };` is an array with 1 list-initialized `std::string`. Now that I read it again, it would've been clearer to use `std::string arr[1]{};`. This array is not dynamically allocated, so `std::size()` works. Calling `translateWords` with empty strings causes undefined behavior. Cool, thanks! I am able to use 'std::numeric_limits' without #include-ing <limits>. Why is that? Lesson 2.11 Section "Headers may include other headers" You can use the "Include What You Use (IWYU)" tool to find such mistakes. Ok, thanks! Hi, in lesson 6.4, you wrote the code for std::sort like this: But when i attempted it for quiz #1 here an error of 'no matching function' came up, could you help me? You cannot use `begin`/`end` on arrays that have decayed to a pointer. Calculate begin and end using pointer arithmetic Thank you, but i'm still confused as to what kind of arrays can decay to pointers. I see in the 6.4 example the array is fixed but it hasnt been used in an expression so it didnt decay. Is that what it is? Yes. Arrays decay when they are used. `begin` and friends use templates, that's why they can use the array without it decaying. Templates are covered later. When you dynamically allocate an array, it's always a pointer. My solution, Can someone tell me how this program would work, if we wanted to enter more information? So instead of just having the name, maybe name, favorite color, and random age. So the program will ask, how many people? so, lets say 2. Then it would it run like so... "Enter name of one person:" "Enter their favorite color:" then to the next person... "Enter name of next person:" "Enter their favorite color:" then it would just print that information with a random age... Name: Joe Color: Blue Weight 125lbs Name: Mark Color: Green weight: 220lbs Any idea? I've been working on something like this...thanks. Create a `struct Person`. Then create an array of `Person` and fill it in your loop. Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/dynamically-allocating-arrays/
CC-MAIN-2021-17
refinedweb
4,147
65.62
iofunc_mmap() Handle an _IO_MMAP message Synopsis: #include <sys/iofunc.h> int iofunc_mmap ( resmgr_context_t * hdr, io_mmap_t * msg, iofunc_ocb_t * ocb, iofunc_attr_t * attr ); Since: BlackBerry 10.0.0 Arguments: - hdr - A pointer to a resmgr_context_t structure that the resource-manager library uses to pass context information between functions. - msg - A pointer to the io_mmap_mmap() helper function provides functionality for the _IO_MMAP message. The _IO_MMAP message is an outcall from the Memory Manager (a part of the QNX Neutrino microkernel's procnto ). Note that if the Process Manager is to be able to execute from this resource, then you must use the iofunc_mmap() function. io_mmap_t structure The io_mmap_t structure holds the _IO_MMAP message received by the resource; The I/O message structures are unions of an input message (coming to the resource manager) and an output or reply message (going back to the client). The i member is a structure of type _io_mmap that contains the following members: - type - _IO_MMAP. - combine_len - If the message is a combine message, _IO_COMBINE_FLAG is set in this member. - prot - The set of protection bits that procnto would like to have for the memory-mapped file. This can be a combination of. See the required_prot field, below. - offset - The offset into shared memory of the location that the client wants to start mapping. - info - A pointer to a _msg_info , structure that contains information about the message received by the resource manager. - required_prot - The set of permission bits that procnto must have for the memory-mapped file. Typically the difference between prot and required_prot is that prot may specify PROT_WRITE while required_prot omits it. This means that procnto would like to have write permissions on the file, but it's OK if it isn't present. The resource manager can tell whether a new or old procnto is talking to it by looking at the required_prot field. If it's nonzero, it's a new procnto, and the code should pay attention to the field. If required_prot is zero, it's an old procnto, and the code should use prot as the required permissions. The o member of the io_mmap_t structure is a structure of type _io_mmap_reply that contains the following members: - allowed_prot - The allowed protections for the file: PROT_READ is always present, PROT_WRITE is present if the file is opened for writing, and PROT_EXEC is present if the client process that opened the file has execute permissions specified for the file. - offset - Reserved for future use. - coid - A file descriptor that the process manager can use to access the mapped file. - fd - Reserved for future use. Returns: - A nonpositive value (i.e., ≤ 0) - Successful completion. - EROFS - An attempt was made to memory map (mmap) a read-only file, using the PROT_WRITE page protection mode. - EACCES - The client doesn't have the appropriate permissions. - ENOMEM - Insufficient memory exists to allocate internal resources required to effect the mapping. Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/i/iofunc_mmap.html
CC-MAIN-2015-22
refinedweb
499
64.71
Basics of Jinja Template Language Last updated on July 27, 2020 Jinja Template Language is a small set of constructs which helps us to automate the creation of templates. Variable, Expression and Function Call # In Jinja double curly {{ }} braces allows us to evaluate an expression, variable or function call and print the result into the template. For example: Evaluating Expression # Other Python operators like Comparision, Logical and Membership operators are also available inside expressions. Evaluating Variables # We are not limited to just numbers and strings, Jinja templates can also handle complex data structures like list, dictionary, tuple, and even custom classes. In case of an invalid index, Jinja will silently output an empty string. Function call # In Jinja to evaluate a function we simply call it as usual. Attributes and Method # To access attributes and method of an object use the dot( .) operator. Jinja has the following syntax to add single or multiline comments inside the templates: Setting Variables # Inside the template, we can define a variable using the set statement. We define variables to store the result of some complex operation so that it can be reused across the template. Variables defined outside of control structures (discussed below) act as global variables and can be accessed inside any control structure. However, variables created inside control structure act as local variables and are only visible inside the control structure in which it is defined, the only exception to this rule is the if statement. Control Structures # Control structures allow us to add control flow and looping inside the templates. By default, control structures use {% ... %} delimiter instead of double curly braces {{ ... }}. if statement # The if statement in Jinja mimics the if statement in Python and value of the condition determines the flow of the statement. For example: If the value of variable bookmarks evaluates to true then the string <p>User has some bookmarks</p> will be printed. Remember that in Jinja if a variable is not defined it evaluates to false. We can also use elif and else clause just like regular Python code. For example: The control statements can also be nested. For example: In certain cases, it is quite useful to add if statement in a single line. Jinja supports inline if statement but call it if expression because it is created using double curly braces {{ ... }} instead of {% ... %}. For example: {{ "User is logged in" if loggedin else "User is not logged in" }} Here if the variable loggedin evaluates to true then the string "User is logged in" will be printed. Otherwise, the string "User is not logged in" will be printed. The else clause is optional, if not provided, then the else block will be evaluated to an undefined object. {{ "User is logged in" if loggedin }} Here if the loggedin variable evaluates to true then the string "User is logged in" will be printed. Otherwise, nothing will be printed. Just like Python, we can use Comparision, Logical and Membership operators in control structures to create more complex conditions. Here are some examples: In case your conditions are becoming too complex or you simply want to alter the operator precedence, you can wrap your expressions inside the parentheses () as follows: For loop # For loop allows us to iterate over a sequence. For example: Output: <ul> <li>tom</li> <li>jerry</li> <li>spike</li> </ul> Here is how you can iterate over a dictionary: Output: <ul> <li>designation : Manager</li> <li>name : tom</li> <li>age : 25</li> </ul> Note: In Python elements of a dictionary are not stored in any particular order so the output may differ. If you want to retrieve key and value of a dictionary at the same time use items() method as follows. Output: The for loop can also take an optional else clause just like Python, however, its usage is slightly different. Recall that in Python when a for loop is followed by an else clause, the else clause is executed only when for loop terminates after looping over the sequence or when the sequence is empty. It is not executed when the for loop is terminated by the break statement. When else clause is used with the for loop in Jinja, it is executed only when the sequence is empty or not defined. For example: Output: <ul> <li>user_list is empty</li> </ul> Similar to nested if statement, we can also have nested for loop. In fact, we can nest any control structures inside one another. The for loop gives you access to a special variable called loop to track the progress of the loop. For example: The loop.index inside the for loop returns the current iteration of the loop starting with 1. The following table lists the other commonly used attributes of the loop variable. Note: For a complete list visit the documentation. Filters # Filters modify the variables before they are rendered. The syntax of using filters is as follows: variable_or_value|filter_name Here is an example: {{ comment|title }} The title filter capitalizes the first character of every word, so if the variable comment is set to "dust in the wind", then the output will be "Dust In The Wind". We can also chain filters to fine tune the output. For example: {{ full_name|striptags|title }} The striptags filter removes all the HTML tags from the variable. In the above code, striptags filter will be applied first followed by the title filter. Some filters can also accept arguments. To pass arguments to a filter call it like a function. For example: {{ number|round(2) }} The round filter rounds the number to the specified number of digits. The following table lists some commonly used filters. Note: The complete list of built-in filters is available here. Macros # A Macro in Jinja is similar to a function in Python. The idea is to create reusable code by giving it a name. For example: Here we have created a macro named render_posts which takes a required argument named post_list and an optional argument named sep. To use a macro call it as follows: {{ render_posts(posts) }} The macro definition must appear before its use otherwise you will get an error. Rather than sprinkling macros in our templates, it is a good idea to store them in a separate file and then import the file as required. Let's say we have stored all our macros in a file named macros.html inside the templates directory. Now to import macros from macros.html we use import statement as follows: {% import "macros.html" as macros %} We can now refer to macros defined inside macros.html using the macros variable. For example: {{ macros.render_posts(posts) }} The import statement {% import "macros.html" as macros %} imports all the macros and variables ( defined at the top level) defined inside macros.html into the template. Alternatively, we can also import selected names inside the template using the form statement as follows: {% from "macros.html" import render_posts %} When using macros, you will you encounter cases where you would need to pass an arbitrary number of arguments to a macro. Similar to *args and **kwargs in Python, inside the macro you have access to varargs and kwargs. varargs: It captures additional position arguments passed to the macro as a tuple. kwargs: It captures additional keyword arguments passed to the macro as a dictionary. Although, you have access to these two variables inside macro you don't need to explicitly declare them in the macro header. Here is an example: In this case, additional positional argument i.e "apple" is assigned to varargs and additional keyword arguments ( name='spike', age=15 ) is assigned to kwargs. Escaping # By default, Jinja automatically escapes the variable output for security purpose. So if a variable has a string containing HTML like "<p>Escaping in Jinja</p>" then it will be rendered as "<p><p>Escaping in Jinja</p></p>". This will cause the HTML tags to be displayed in the browser instead of interpreted. In case you know that the data is safe and want to render it as it is without escaping, you can use the safe filter. For example: {% set html = <p>Escaping in Jinja</p> %} {{ html|safe }} Output: <p>Escaping in Jinja</p> Applying safe filter repeatedly to a large block of content can be awkward and inconvenient, that's why Jinja provides autoescape statement to escape or unescape large blocks of content. It accepts true or false as an argument to turn on and turn off auto-escaping respectively. For example: Everything between {% autoescape false %} and {% endautoescape %} will be rendered as it is without escaping. If you want to escape some of the elements when auto-escaping is turned off use the escape filter. For example: Including templates # The include statement renders a template inside another template. The include statement is commonly used to render a static section which is repeated throughout the site. Here is the syntax of the include statement: {% include 'path/to/template' %} Let's say we have a simple navigation bar stored in nav.html inside templates directory as follows: To include the navigation bar inside home.html, we use the following code: Output: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <nav> <a href="/home">Home</a> <a href="/blog">Blog</a> <a href="/contact">Contact</a> </nav> </body> </html> Template Inheritance # Template Inheritance is one the most powerful aspects of Jinja Templating. The idea behind template inheritance is somewhat similar to Object Oriented Programming. We start by creating a base template which contains the HTML skeleton and markers that child template can override. The markers are created using the block statement. The child templates uses extends statement to inherit or extends the base templates. Let's take an example: This is our base template base.html. It defines three blocks using the block statement where child templates can fill in. The block statement takes a single argument which is the name of the block. Inside the template, the block name must be unique otherwise you will get an error. A child template is a template which extends the base template. The child template may add, override or leave along the contents of the parent block. Here is how we can create a child template. The extends statement tells Jinja that child.html is a child template and inherits from base.html. When Jinja encounters the extends statement it loads the base template i.e base.html then replaces the blocks of content in the parent template with the blocks of content of the same name in the child template. In case, a block of matching name isn't found in the child template then the block from parent template will be used. Note that in the child template we are only overriding the content block, so the default content from the title and nav will be used while rendering child template. The output should look like this: If we want, we can change the default the title by overriding the title block in the child.html as follows: After overriding a block you can still refer to the content in the parent template by calling super() function. The super() call is generally used when child template needs to add its own content in addition to the content from the parent. For example: Output: That's all you need to know about Jinja templates. In the upcoming lessons, we will use this knowledge to create some great templates. Load Comments
https://overiq.com/flask-101/basics-of-jinja-template-language/
CC-MAIN-2022-40
refinedweb
1,916
62.98
Jesper Harder <address@hidden> writes: > > ,----[ C-h f device-type RET ] > > | device-type is a compiled Lisp function. > > | (device-type &optional DEVICE) > > FWIW, this function comes from w3. > > w3 uses the XEmacs model and therefore supplies `device-type' in a > compatibility library, 'devices.el'. I wish someone would fix w3; those compatibility functions often cause real lossage, not just confusion (though they cause the latter in copious amounts too). [The problem is that w3 doesn't use its own namespace for them, which sometimes causes _other_ packages that test for certain functions to mistakenly think they're running under xemacs! W3 should use `w3-device-type' or something.] -Miles -- `...the Soviet Union was sliding in to an economic collapse so comprehensive that in the end its factories produced not goods but bads: finished products less valuable than the raw materials they were made from.' [The Economist]
http://lists.gnu.org/archive/html/help-gnu-emacs/2002-11/msg00537.html
CC-MAIN-2015-32
refinedweb
146
51.89
tag:blogger.com,1999:blog-1705051721030116110.post105626080339829905..comments2019-05-19T06:24:35.436-07:00Comments on Development Hole: Upload a File to a SharePoint Document Library - Part Itxs8311 would be nice if when uploading it would keep t...It would be nice if when uploading it would keep the same version when the initial file metadata is added.Bruce Lowertag:blogger.com,1999:blog-1705051721030116110.post-5348026118505334772010-09-27T20:32:27.404-07:002010-09-27T20:32:27.404-07:00Earlier in the month I had posted about a problem ...Earlier in the month I had posted about a problem with updating column data in MOSS2010 (where it had worked fine in 2007). The cause was that 2010 requires the doc ID where 2007 was happy with just a doc reference.<br /><br />To fix this, I added a function to get the doc id and then added this to the update xml.<br /><br />The function i added was...<br /><br /> Private Function GetDocID(ByVal s_URL As String) As String<br /> Dim m_sitedataService As New svc_sharepoint_sitedata.SiteData<br /> Dim s_DocPath As String<br /> s_DocPath = Replace(s_URL, Path.GetFileName(s_URL), "")<br /> m_sitedataService.Url = s_DocPath & "_vti_bin/sitedata.asmx"<br /> m_sitedataService.Credentials = m_credentials<br /><br /> Dim s_webId As String = String.Empty<br /> Dim s_listId As String = String.Empty<br /> Dim s_itemId As String = String.Empty<br /> Dim s_bucketId As String = String.Empty<br /><br /> Dim ret As Boolean = m_sitedataService.GetURLSegments(s_URL, s_webId, s_bucketId, s_listId, s_itemId)<br /><br /> Return s_itemId<br /><br /> End Function<br /><br />and then I just added a call to it just before "Dim sb As New StringBuilder()"...<br /><br />Dim DocGUID As String = GetDocID(fileInfo.m_URL)<br /><br />Now we just add the DocGUID to the ID field.<br /><br />Now it all works sweet with SP 2010!<br /><br />Q.Quentinnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-87310738799866283092010-09-27T14:33:29.643-07:002010-09-27T14:33:29.643-07:00On 2007, this code works flawlessly. On a SharePoi...On 2007, this code works flawlessly. On a SharePoint 2010 platform, was having same issues as last poster with failure to update errors. <br /><br />Using the copy service as outlined in the solution on this page:<br /><br /><br />documents are uploaded with properties. Need to figure out how to remove the linked copy flag when viewing the item properties... But the linked solution will get documents up into 2010.jeremynoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-87168858851463461872010-09-05T21:32:53.722-07:002010-09-05T21:32:53.722-07:00Further to my previous post, more correctly, the e...Further to my previous post, more correctly, the error I get is...<br /><br /> "The URL 'Doc Library/899/SJMSCL5EUBQ.pdf' is invalid. It may refer to a nonexistent file or folder, or refer to a valid file or folder that is not in the current Web."<br /><br />If you open Sharepoint you can actually see the file and the path is correct.Quentinnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-9882076120447020762010-09-05T20:54:26.333-07:002010-09-05T20:54:26.333-07:00Thanks for the great code! I have found it works w...Thanks for the great code! I have found it works well when used with a MOSS2007 server. However, when I try to implement it into a MOSS2010 environment I come across a problem. Everything seems to work fine until it comes time to update the metadata within the 'TryToUpload' function. The file uploads fine but when it tries to update the data at 'UpdateListItems' I get the error that the file doesn't exist when in fact it does.<br />Has anyone had this problem? Any clues...PLEASE!!!<br /><br />Thanks everyone.Quentinnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-80466603596179688312010-08-26T12:43:49.682-07:002010-08-26T12:43:49.682-07:00The code works just fine. However, I received an ...The code works just fine. However, I received an error "Could not locate list." <br /><br />Some digging showed me that in your IsMatch method of your list service has this line:<br /><br />return url.Substring(0, m_rootFolder.Length) == m_rootFolder;<br /><br />If the first parameter used in the DocLibHelper.Upload method isn't the same case as the list name, I got an error, so I changed it to this:<br /><br />return url.Substring(0, m_rootFolder.Length)<b>.ToLower()</b> == m_rootFolder<b>.ToLower(); </b><br /><br />which meant I was always comparing the same case. Hope this helps someone.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-4294511821579976982010-08-17T16:29:23.553-07:002010-08-17T16:29:23.553-07:00When uploading a document from CRM to SharePoint, ...When uploading a document from CRM to SharePoint, the first version of the document is 2. This is because versioning is turned on and when you upload the document it is Version 1 and when you update the Meta data it is considered as Version 2. Is there a solution for this issue. I want the version to remain as 1.Vidya few people have noted that they cannot find the ...A few people have noted that they cannot find the Lists object in their ListService object. <br /><br />Error: <i>The type or namespace name 'Lists' does not exist in the namespace 'ListsService' (are you missing an assembly reference?)</i><br /><br />Make sure you add Lists.asmx service as a Web Reference, not a Service Reference. This MSDN article on Web Service Guidelines sheds some light on how to do that. <a href="" rel="nofollow"></a>. Scroll down to Guidelines for Using the ASP.NET Web Services.<br /><br />1. Go to Add Service Reference Dialog.<br />2. Click Advanced... to open Service Reference Settings<br />3. Click Add Web Reference<br />4. In Add Web Reference dialog box, enter your web service url, click green arrow, set your Web Reference name and click Add Reference.<br /><br />3.Malcolmnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-6645999188184329792010-03-12T04:14:15.230-08:002010-03-12T04:14:15.230-08:00Great post... Also agree with the comment about s...Great post... Also agree with the comment about swithing the code to make use of file stream rather than byte array...pwrnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-18055231618740231852010-01-06T07:07:49.895-08:002010-01-06T07:07:49.895-08:00It was bugging out with bigger files, so I switche...It was bugging out with bigger files, so I switched the byte[] to a FileStream derived from File.OpenRead(filepath).. Hope that helps someone else!Tracy, can you help me How upload file from sharepoin...Hi, can you help me<br />How upload file from sharepoint to ms crm 4 annotations for example?<br />I have full url to fileKostya Afendikov! I tried the solution but every time I run I r...Hi! <br />I tried the solution but every time I run I receive a catch that says that it cannot find the list.<br />I have tried different variations of the list but cannot get by the message.<br />I changed the sharepoint location to my own and put in a structure that didn't exist. Other than that there are no changes.<br /><br />Whate else might be wrong.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-75477334825787786682009-08-31T21:52:01.320-07:002009-08-31T21:52:01.320-07:00Hi, I used your file uploading code and it is work...Hi,<br />I used your file uploading code and it is working like a charm in MOSS2007/Win2003 environment. But when I tried the same thing in MOSS2007/Win2008/Vista environment, the Upload function throws "405 Method Not Allowed" error. Is there anything I have to change in the code in order to work with MOSS2007 hosted on Win2008.<br />Thanks<br />NKYenkay! Has anyone had any trouble with file overwrit...Hey! Has anyone had any trouble with file overwrite using this method? I have implemented this technique in my own document provider, however once I've uploaded once, any subsequent uploads do not overwrite. No exceptions are thrown, and I can step through the whole process, however the same file remains in WSS afterwards. How can this be?!Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-24178887943262131392009-06-23T07:35:05.215-07:002009-06-23T07:35:05.215-07:00txs8311, Thanks for your prompt reply. Yes, I am u...txs8311,<br />Thanks for your prompt reply.<br />Yes, I am using the UserProfileService web service. But here I have the same problem as any other web service.<br />I understand what you are trying to explaing here with your code. I already have that line "using CreateUserProfile.UserProfileService;" in my code, but I still get the same error.<br />I am not sure why you are not a compile error while instantiating the "proxy" in line:<br />UserProfileService proxy = new UserProfileService();<br />I am stuck, can you provide some more help.<br />Thanks in advance.<br />ZulluAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-37149181952108344602009-06-22T15:17:57.205-07:002009-06-22T15:17:57.205-07:00Hi Zullu, This looks a bit off topic, but you'...Hi Zullu,<br /><br />This looks a bit off topic, but you're trying to use the UserProfileService web service? <br /><br />If so, take a look at the following code:<br /><br />using System;<br />using System.Collections.Generic;<br />using System.Text;<br />using ConsoleApplication1.CreateUserProfile;<br /><br />namespace ConsoleApplication1<br />{<br /> class Program<br /> {<br /> static void Main(string[] args)<br /> {<br /> UserProfileService proxy = new UserProfileService();<br /> PropertyData[] d = proxy.CreateUserProfileByAccountName("newAccountName");<br /> }<br /> }<br />}<br /><br />I added the namespace ConsoleApplication1.CreateUserProfile with the line "using ConsoleApplication1.CreateUserProfile;"<br /><br />This will include the code that was generated automatically when I added a reference to the web service. If you show all files in the VS solution explorer (use the show all files button at the top) and then expand the reference until you see the code (reference.cs) you'll see the namespace you need to add.<br /><br />Hope this helps.txs8311 txs8311 and Björn, I get the same error as the ...Hi txs8311 and Björn,<br />I get the same error as the "The type or namespace name 'UserProfileService' does not exist in the namespace 'CreateUserProfile.UserProfileService' (are you missing an assembly reference?)"<br /><br />Can you pl elaborate what you meant by looking into the Reference.cs file. I don't think I understood properly.<br />Thanks.<br />ZulluAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-1705051721030116110.post-36155953222587766062009-04-13T06:08:00.000-07:002009-04-13T06:08:00.000-07:00Hi,I tried uploading a document using this class, ...Hi,<BR/>I tried uploading a document using this class, the document get uploaded with no issues. But how can I get the Id of the document uploaded. On the updateRespose i can only see ErrorCode node. No z:row node is returned.Yenkay, if you upload a file where the docu...Interestingly, if you upload a file where the document library does not exist you do not get an error. Something DOES get uploaded because if you then create the library, the url of it has a 1 appended (as if it found a conflicting name). Weird.Jasonnoreply@blogger.com
http://geek.hubkey.com/feeds/105626080339829905/comments/default
CC-MAIN-2019-22
refinedweb
1,917
60.11
imread function not working I am trying to write a basic program in opencv that just displays an image, but imread does not seem to be working.I have libopencv_core.so and libopencv_highgui.so linked to the program and I'm using linux. Here is my code: #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main() { Mat img = imread("test.jpg", 1); if(!img.data)//This if statement is triggered { cout<<"Error!\n" return -1; } namedWindow("Test", CV_WINDOW_AUTOSIZE); imshow("Test", img); waitKey(0); return 1; } Thank you try: if ( img.empty() )instead and make sure this 'test.jpg' exists at the very same folder you start your program i think you have to put semicolon (;) after cout<<"Error!\n" I have check this code work OK.
https://answers.opencv.org/question/15225/imread-function-not-working/
CC-MAIN-2019-35
refinedweb
131
78.96
This is your resource to discuss support topics with your peers, and learn from each other. 07-28-2010 01:55 PM Hello rcmaniac25! Yes,,, i have same opinion, i made some jokes. But my result did not reach that expected, as I had mentioned, I can change the wallpaper, but slows down if I get rolling several times trackwhell up and down, repeatedly changing the focus from the button, then the application becomes slow. My question is whether this case the change background bitmap, there is a good practice to manipulate a background of screen, remembering that in my testing, I manipulated the brackground using invokeLater and runnable and where within the method did change the background screen by: getMainManager().setBackground(background); getMainManager().invalidate(); It´s make the screen to lock or slow showing the ampulet. Any recomendations in this case? Regards, Rampelotti. 07-28-2010 02:52 PM Though I haven't tried anything out yet, remember, "cancel" is your friend. Since you are going for a fading transition you have to start the transition when it gets to the proper element, then if it goes to a different element you need to cancel the previous transition and start on the next one. If you have a single global variable (again with the single listener idea) that defines the "current transition progress" you can then say "OK, new transition. Cancel (stop) the old one, then start the new one at the previous location so it doesn't have to cycle through the entire transition again" Just a theory, I have some GUI ideas for some apps I'm working on, this is one of the ideas so I want to work on I need to get a few other things done first. On your invokeLater code, the problem is that it will always back-up if too many items get queued too fast. It might be better to make a custom Background, do the above mentioned code, and grab the event lock yourself instead of invokeLater just so things speed up and you aren't waiting for the queue to get to your element. 07-28-2010 04:03 PM Can you show me a sample? Regards, Rampelotti 07-28-2010 04:23 PM You'll have to give me a little bit, busy right now. My last post was (at least to me) scatter brained a little but if you can grasp what I was trying to convey you might be able to figure it out yourself. 07-28-2010 06:09 PM Here is a bit of code, that demonstrates how I think you can do (b) every fast. Yes I know the backgrounds are a bit naff, and to be honest, I think you could probably do all the painting in paint, rather than do what I do once onto the Bitmap which would use a lot less memory, but this is the fastest way. You will also note that this processing calls paint directly...... Tested in 4.2.1 Pearl 8100 and 4.6.1 Curve 8520. import net.rim.device.api.system.*; import net.rim.device.api.util.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; public class TestBitmapScreen extends MainScreen { private Bitmap [] _backgrounds = new Bitmap [5]; private int [] _backgroundColors = new int [] { 0x00FF0000, 0x00FFFF00, 0x0000FF00, 0x0000FFFF, 0x000000FF }; private String [] _menuItems = new String [] { "Agenda", "Sessions", "Getting Around", "Speakers", "Sponsors" }; private int _currentBackground = 0; private int _unfocusedButtonColor = 0x00808080; private int _focusedButoonColor = 0x00FF00FF; public TestBitmapScreen() { super(); Graphics g; Font boldFont = this.getFont().derive(Font.BOLD); int buttonHeight = boldFont.getHeight(); int buttonWidth = 200; int ButtonStartX = Display.getWidth() - buttonWidth; for ( int i = 0; i < _backgrounds.length; i++ ) { _backgrounds[i] = new Bitmap(Display.getWidth(), Display.getHeight()); g = new Graphics(_backgrounds[i]); g.setColor(_backgroundColors[i]); g.fillRect(0, 0, Display.getWidth(), Display.getHeight());); } } } protected void paint(Graphics graphics) { graphics.drawBitmap(0, 0, Display.getWidth(), Display.getHeight(), _backgrounds[_currentBackground], 0, 0); } protected boolean navigationMovement(int dx, int dy, int status, int time) { if ( dy > 0 ) { // scroll down if ( _currentBackground < _backgrounds.length-1 ) { _currentBackground++; Graphics g = this.getGraphics(); this.paint(g); // this.invalidate(); } } else if ( dy < 0 ) { // scroll up if ( _currentBackground > 0 ) { _currentBackground--; Graphics g = this.getGraphics(); this.paint(g); // this.invalidate(); } } return true; } } Need to think about (a) now. 07-29-2010 08:21 AM Hello peter_strange! It´s wonderfull, i don´t thinked this solution. Wow, I'm trying to understand up this moment how it´s work, because in my humble opinion, i thinking that i paint the background, i was thinking that i needed invalidate every component of screen, i don´t understand how you can paint the bitmap entire screen and did not hide the menu, because the area of bitmap should be painted above the menu, but in this solution yout bitmap is painted under the menu. Can you explain to me how it works? And you have any document to explain the GUI comportment? Regards, Rampelotti 07-29-2010 09:03 AM There is no menu. Each bitmap is a complete screen shot, including the 'menu'. The menu is included in the Bitmap, the entire bitmap is written to the screen. This is the code that updates the 'background' and paints on top of it, the 'menu:); } Sorry, I have not found a good source for the standard GUI processing, let alone this sort of stuff. Experience and lots of playing round required. One other thing, you should really use the commented out invalidate() lines, and remove the lines: Graphics g = this.getGraphics(); this.paint(g); These lines may cause you grief later. Invalidate() should not. I doubt you will notice the performance difference. . 07-30-2010 07:56 AM Thanks for reply peter_strange! Your explain was great. I has a wrong idea about graphics, i thinking that when i used the graphics to draw anything i needed redraw everything every time... Well i need to change my mind Now we have no idea to item (a) You help me a lot peter! Regards, Rampelotti; 07-30-2010 07:56 AM Phase 2, fade in and out. Here is bit of grubby code Very grubby. Shows you how you can do it. But really not pretty. I don't have time to pretty it up. Play with this and see if you can figure out how it works. I am not sure the WES app does this, and, in addition, Screen transitions in OS 5.0 might be able to do it anyway. Not sure, still writing pre OS 5.0 code for the most part. Have fun. import net.rim.device.api.system.*; import net.rim.device.api.util.*; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; public class TestBitmapScreen extends MainScreen { private Bitmap _currentScreen = null; private Bitmap _oldScreen = null; private int [] _coloursToUse = new int [] { // 16 colours, used as a 4 x 4 grid 0x00800000, 0x00FF0000, 0x00FF8000, 0x00FFFF00, 0x0080FF00, 0x0000FF00, 0x0000FF80, 0x0000FFFF, 0x000080FF, 0x000000FF, 0x00000080, 0x00800080, 0x00808080, 0x0080FF80, 0x008080FF, 0x00FF8080 }; private int _focusColor = 0x00FFFFFF; private int _currentFocus = 0; private int _oldFocus = -1; protected int _alpha = 255; private int _screenWidth; private int _screenHeight; private int _gridWidth; private int _gridHeight; private FadeThread _fadeThread; public TestBitmapScreen() { super(); _oldScreen = new Bitmap(Display.getWidth(), Display.getHeight()); _currentScreen = new Bitmap(Display.getWidth(), Display.getHeight()); _currentFocus = 0; _screenWidth = Display.getWidth(); _screenHeight = Display.getHeight(); _gridWidth = _screenWidth/4; _gridHeight = _screenHeight / 4; paintBitmap(_currentScreen, _currentFocus); } public void paintBitmap(Bitmap paintThis, int focusSquare) { Graphics g = new Graphics(paintThis); for ( int x = 0; x < 4; x++ ) { for ( int y = 0; y < 4; y++ ) { // paint one square of our 4 x 4 pattern int colourIndex = y * 4 + x; if ( focusSquare == colourIndex ) { // We are focused on this square g.setColor(_focusColor); } else { g.setColor(_coloursToUse[colourIndex]); } g.fillRect(x*_gridWidth, y*_gridHeight, _gridWidth, _gridHeight); } } } protected void paint(Graphics graphics) { graphics.setGlobalAlpha(255); graphics.drawBitmap(0, 0, Display.getWidth(), Display.getHeight(), _currentScreen, 0, 0); if ( _alpha < 255 ) { int oldFocusY = _oldFocus/4; int oldFocusX = (_oldFocus - (oldFocusY*4)); int currentFocusY = _currentFocus/4; int currentFocusX = (_currentFocus - (currentFocusY*4)); graphics.setGlobalAlpha(255-_alpha); graphics.drawBitmap(oldFocusX*_gridWidth, oldFocusY*_gridHeight, _gridWidth, _gridHeight, _oldScreen, oldFocusX*_gridWidth, oldFocusY*_gridHeight); graphics.drawBitmap(currentFocusX*_gridWidth, currentFocusY*_gridHeight, _gridWidth, _gridHeight, _oldScreen, currentFocusX*_gridWidth, currentFocusY*_gridHeight); graphics.setGlobalAlpha(_alpha); graphics.drawBitmap(oldFocusX*_gridWidth, oldFocusY*_gridHeight, _gridWidth, _gridHeight, _currentScreen, oldFocusX*_gridWidth, oldFocusY*_gridHeight); graphics.drawBitmap(currentFocusX*_gridWidth, currentFocusY*_gridHeight, _gridWidth, _gridHeight, _currentScreen, currentFocusX*_gridWidth, currentFocusY*_gridHeight); } } protected boolean navigationMovement(int dx, int dy, int status, int time) { int increment = 0; if ( dy > 0 ) { // scroll down increment = 4; } else if ( dy < 0 ) { // scroll down increment = -4; } else if ( dx > 0 ) { // scroll right increment = 1; } else if ( dx < 0 ) { // scroll left increment = -1; } if ( increment != 0 ) { _oldFocus = _currentFocus; _currentFocus = (_currentFocus + increment + _coloursToUse.length) % _coloursToUse.length ; // swap screen buffer Bitmap tempBitmap = _oldScreen; _oldScreen = _currentScreen; _currentScreen = tempBitmap; paintBitmap(_currentScreen, _currentFocus); startNewFadeThread(); } return true; } private void startNewFadeThread() { if ( _fadeThread != null ) { _fadeThread.cancel(); } _fadeThread = new FadeThread(this); _alpha = 0; _fadeThread.start(); } private class FadeThread extends Thread { Graphics _gragphics = null; TestBitmapScreen _ourScreen; int _alpha = 0; private volatile boolean _cancelled = false; public FadeThread(TestBitmapScreen ourScreen) { _ourScreen = ourScreen; _gragphics = _ourScreen.getGraphics(); } public void run() { long startTime = System.currentTimeMillis(); long finishTime = startTime + 1023; long currentTime = startTime; while ( currentTime < finishTime && !_cancelled ) { try { Thread.sleep(10); } catch (Exception e) { } if ( !_cancelled ) { currentTime = System.currentTimeMillis(); _alpha = (int) ((currentTime - startTime)/4); paintIt(); } } if ( !_cancelled ) { _alpha = 255; paintIt(); } } public void cancel() { _cancelled = true; } private void paintIt() { _ourScreen._alpha = this._alpha; _ourScreen.invalidate(); } } } 07-30-2010 10:15 AM Very thanks! It´s a matter of fact the OS 5.0 have more things to increase development and facilities for our lives I´ll test and after post here the results.... Regards, Rampelotti
https://supportforums.blackberry.com/t5/Java-Development/Components-like-WES-2010-application/m-p/555596/highlight/true
CC-MAIN-2017-13
refinedweb
1,621
55.64
Tut 9. Sounds. Things a bit quiet? Sounds and Music add alot of atmos to a map. In mapping terms, Sounds and Music are different things. Music is not 'heard' in the map as such. It is like the music in a movie. Sounds are localised and have a position in the map and are louder the nearer the Player is to them. Sounds need to be created in a similar way to objects,etc. If you intend using lots of them, make a seperate file. Name it mysounds.py or sonidos.py (to keep it in its native language. ) Yes, there is a source file Sounds.py . Exec the file in cfg.py as before. This is the code to create sounds: snd_bang1=Bladex.CreateSound("..\\..\\sounds\\golpe-arma-escudo.wav","SoundBang1") The filepath to the sound file in the Sounds folder is included in the code. There are a lot of sound files and most of them have Spanish names, but you soon figure it out. (golpe = hit for example). What happens after you have created the sound? Nothing . You have to play it with a function call: This code is usually put in a function to correspond with an event. The first three arguments are the map coords for the focus of the sound. The last 0 is the number of times the file will be played, in this case once. (put 1 and you get 2 bangs. ). Some sounds are looped so that they can play continuously. For a looped sound (wind, waterfall, fire, etc) put -1. Sometimes you want a sound to play at the Player position. You may not know where exactly the Player may be. You can 'get' the current Player position (and anything else for that matter) with this: snd_bang1.Play(charpos[0],charpos[1]charpos[2],0) You might be wondering why all the[]s have appeared. Why not just put charpos. Well, the variable charpos has three values stored. You have to unpack them. So charpos[0] acesses the first value (the X coord), etc. You could do it like this: snd_bang1.Play(x,z,y,0) Which is probably neater. There is usually more than one of doing things in Python. Sounds have many Attributes. Some I am not sure exactly the purpose of. The useful ones are: snd_bang1.MinDistance=500 snd_bang1.MaxDistnce=50000 Which are self explanatary. (I am not sure whether sounds get any louder if you set the Volume greater than 1.0) There is also Pitch, Which can be useful to vary sounds slightly. There is a function that allows you to play sounds at random intervals. snd_crow1.PlayPeriodic() It includes two extra args, 20,8. The sound will play at a random interval somewhere between 20 and 8 seconds. Set these values to your own preferences. Music. The backgroud music is all defined in a file 'MusicEvents.py'. This is a key file and must have that name for savegame integrity. Exec it as usual in cfg.py. # for .wav files Bladex.AddMusicEventADPCM("Atmos24","..\\..\\sounds\\ATMOSFERA24.wav",1.0,1.0,1.0,1.0,0,-1) # for mp3s Bladex.AddMusicEventMP3(....rest is the same There are 6 args follwing the filepath. In practice you only need pay attention to the last one. Like Sounds it controls the number of times the file is played. 0 for once, -1 continuous. You start the music with this: this call is usually contained in a function. To stop whatever music is playing: You usually have to 'kill' whatever music is playing before starting a new track. CombatMusic. You can assign music to enemies that starts to play when they go into Combat mode. Use the same MusicEvents.py file but: DMusic.AddCombatMusic("Ork1",..\\..\\sounds\\combate-hard.wav,400,1.0,1.0,1.0,1.0) You can assign it to individual enemies or a whole Kind. I haven't quite figured all the args yet, but the first is the priority. If you have lots of enemies in a group, set this value slightly lower for each one so that they don't all try to play their music at once. If there was a piece of background music playing when you started fighting the Ork, it will not resume after he is dead. His combat music will stop and there will be silence. I made a little routine to restore the music (if any). In DefFuncs: def ChangeMusic(music): Bladex.KillMusic() Bladex.ExeMusicEvent(music) global CurrentMusic CurrentMusic=music #then, start all music with: ChangeMusic("Atmos24") A word on global variables. If you need to access a variable within the body of a function, you must declare it as a global or it will not be recognised. With this func you can change the music at any time and the identity of the music is stored in the CurrentMusic var. Then if you happen to have to inerrupt the music for any reason, you can restore it with: global CurrentMusic Bladex.KillMusic() if CurrentMusic != "": Bladex.ExeMusicEvent(CurrentMusic) # to clear the var if necessary def StopMusic(): global CurrentMusic Bladex.KillMusic() CurrentMusic="" This func is most likely to be called after the death of an enemy. Then, whatever music was playing when you started the fight will carry on after enemy is dead. For this you have to tap into his ImDead function. I'll come to that later. You can either use the Sounds library, or you can make your own. To use your own stuff, just alter the filepath to your own file: "..\\..\\Maps\\MyMap\\coolsound1.wav" ---------------------------------------------- big truck. Glad you like them, but don't spirit them away too soon as they sometimes need de-bugging.
https://www.moddb.com/tutorials/level-editing-scripting-by-prospero-part-9
CC-MAIN-2021-31
refinedweb
951
77.53
- Code: Select all from datetime import datetime today = datetime.now().date() #def createFile(): path = "C:\Users\bgbes\Documents\Brent\ParsePractice\Test " + str(today) + ".txt" f = open(path, 'w') f.write('Hello') f.close() Here is the code. - Code: Select all Traceback (most recent call last): File "C:/Users/bgbes/Documents/Ben/Python_tut/createFile.py", line 8, in <module> f = open(path, 'w') IOError: [Errno 22] invalid mode ('w') or filename: 'C:\\Users\x08gbes\\Documents\\Ben\\ParsePractice\\Test 2013-05-09.txt' There is the error message. All I'm trying to do is create a file and save it to that path, but I can't get it to work.
http://www.python-forum.org/viewtopic.php?p=3521
CC-MAIN-2014-52
refinedweb
110
53.07
I want to use the Hosts file to locate schema for validation. The Hosts file (C:\Windows\System32\etc) will locate xsd schema files on a LAN server for development purposes. This gives me a alias mechanism for XML namespace redirection. If the host file on a client machine has the entry; 192.168.1.12 XML-srv Will the following schema locator attribute work? xsi: I have tryed the validator in XMLSpy (on the client machine) with the above configuration and it fails to load the schema from the server. Since the XMLSpy code is using MSXML, will MSXML use the Hosts file to resolve the schema locator? shawnk Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?142937-Using-Hosts-file-to-locate-schema-for-validation&p=424609
CC-MAIN-2014-42
refinedweb
128
64.61
I am not sure if "clamping" is the correct terminology for this, however I really don't know what else to call it. Suppose we wanted to limit an integer to stay within some arbitrary range, like 0-50. This can be easily achieved by testing the current value with an if statement and assigning the maximum or minimum value accordingly. However, what is the fastest way to keep the Integer at its maximum value or minimum value? As easy as var normalized = Math.Min(50, Math.Max(0, value)); As of performance: public static int Max(int val1, int val2) { return (val1>=val2)?val1:val2; } That's how it's implemented in .NET, so it's unlikely you can implement it even better.
http://www.dlxedu.com/askdetail/3/4cb98d8aa346dbdb1c450023abe15972.html
CC-MAIN-2018-47
refinedweb
124
57.37
! (More advice on this) - Showing actual code is useful. For code longer than a line or two, use the pastebin: - Django has very good documentation. Make sure you've checked it! - Try searching in Trac. - Can't join the IRC channel without registering with nickserv? What's this? See here. - General questions about IRC or Freenode? Try the Freenode FAQ. - Don't ask to ask, just ask! Python questions How do I learn Python if I'm new to programming? How do I learn Python if I'm not new to programming? - - - Are there any books on Python? Yes. What's this about Python Path? Django is? Troubleshooting General problem-solving advice: Test the things you think are true until you find the one that isn't. "It doesn't work!" or "I got an error!" If you want good help you'll need to give a little more information. Keep in mind that we probably know little if anything about your project, your level of experience with Python and Django, etc. Did it work before? Or is this something you're trying for the first time? Does it raise an error? Die silently? Give unexpected output? If you want help with an error, try to give us 1) the code that produced the error and 2) the error traceback itself. When asking for help, make sure you describe 1) what you did, 2) what you expected to happen, and 3) what actually happened. Pasting your code is often helpful. Don't forget to set the syntax when you paste so that the proper colorizing is applied -- that makes it easier for us to read your stuff. The Django debug page has a handy button for automatically sharing traceback code. My media/static files (CSS, images, etc.) aren't showing up. Django doesn't serve static media automatically (exception: admin app running under the dev server). If you're running the development server, read this: If you're running Apache, read this: Confusingly, though the MEDIA_* settings in your settings.py file refer to your media files, not the Admin app's media files, the default path for Admin app media ( ADMIN_MEDIA_PREFIX) is set to "/media/". Many Django users change this to "/admin_media/" or "/adminmedia/" to reduce potential confusion.) - restart the webserver (yes, even if you're using runserver) How to do Stuff How do I create a subclass of an existing model? If you're using model inheritance (aka model subclassing), make sure you've read the documentation and understand the difference between the abstract base class and multi-table inheritance options. The latter can be confusing to newcomers because an instance of a parent class will also contain, on an attribute named after a child class, that same object represented as an instance of the child class. Got that? An established mechanism for adding additional information to Django User objects without subclassing is known as "profiles"; you can read about it in the Definitive Guide. For an important alternatve viewpoint on model subclassing, see:. I want to have some code run when the server/application starts. How do I do that? Both mod_python and FastCGI are structured in such a way that there's no such thing as "application startup" or "server startup"; the best solution is to place your "startup" code somewhere that's guaranteed to be imported early on in the request/response cycle (the __init__.py file of your project, or of a specific application you're using, can be a good place, because Python will execute code found there the first time it has to import the module; just be aware that referencing the same module in different ways, say by doing from myproject.myapp import foo in one place, and from myapp import foo in another, will cause that code to be executed once for each different way you import Which runs faster, X or Y? This is a tempting question to ask in hopes of getting a quick answer on the "best" way to do something. Unfortunately, the answer is generally "profile your app and see". Performance tuning always starts with a baseline. If you haven't measured current performance to get a baseline, you aren't in a position to do much with the answer to the question anyway. You can learn more about Python's handy profiling tools in the Python documentation..
https://code.djangoproject.com/wiki/IrcFAQ?version=94
CC-MAIN-2017-26
refinedweb
732
64.81
Originally posted here on GitHub AWS - The YAML way Motivation - I want to manage AWS infrastructure with YAML - I want to use Kubernetes RBAC for authorization - I want to be able to defines rules to govern my cloud resources But why? Why not :) How? - For (1), there's AWS Controllers for Kubernetes (ACK) or maybe Crossplane - For (2), it's quite straight forward. If we can express AWS resources using Kubernetes CRDs, then it's done. - For (3), I'm thinking Kyverno or OpenPolicyAgent. Let's do it Setup the env I will skip the part where you setup AWS CLI and an EKS cluster Suppose that is all set and done. If not, follow the brief instructions below to setup a new EKS cluster. The easiest way IMO is to use eksctl from Weaveworks. aws ec2 create-key-pair --region ap-southeast-1 --key-name my-yaml-eks-key eksctl create cluster \ --name my-yaml-eks \ --region ap-southeast-1 \ --with-oidc \ --ssh-access \ --ssh-public-key my-yaml-eks-key \ --managed Wait for a bit for the cluster to be provisioned. There will be 2 CloudFormation stacks being provisioned so it might take awhile. If something goes wrong (disconnection, etc..), you can check with this command below eksctl utils describe-stacks --region=ap-southeast-1 --cluster=my-yaml-eks 2021-10-18 22:35:28 [ℹ] eksctl version 0.70.0 2021-10-18 22:35:28 [ℹ] using region ap-southeast-1 2021-10-18 22:35:29 [ℹ] setting availability zones to [ap-southeast-1a ap-southeast-1b ap-southeast-1c] 2021-10-18 22:35:29 [ℹ] subnets for ap-southeast-1a - public:192.168.0.0/19 private:192.168.96.0/19 2021-10-18 22:35:29 [ℹ] subnets for ap-southeast-1b - public:192.168.32.0/19 private:192.168.128.0/19 2021-10-18 22:35:29 [ℹ] subnets for ap-southeast-1c - public:192.168.64.0/19 private:192.168.160.0/19 2021-10-18 22:35:29 [ℹ] nodegroup "ng-5c441b7d" will use "" [AmazonLinux2/1.20] 2021-10-18 22:35:29 [ℹ] using EC2 key pair %!q(*string=<nil>) 2021-10-18 22:35:29 [ℹ] using Kubernetes version 1.20 2021-10-18 22:35:29 [ℹ] creating EKS cluster "my-yaml-eks" in "ap-southeast-1" region with managed nodes 2021-10-18 22:35:29 [ℹ] will create 2 separate CloudFormation stacks for cluster itself and the initial managed nodegroup 2021-10-18 22:35:29 [ℹ] if you encounter any issues, check CloudFormation console or try 'eksctl utils describe-stacks --region=ap-southeast-1 --cluster=my-yaml-eks' 2021-10-18 22:35:29 [ℹ] CloudWatch logging will not be enabled for cluster "my-yaml-eks" in "ap-southeast-1" 2021-10-18 22:35:29 [ℹ] you can enable it with 'eksctl utils update-cluster-logging --enable-types={SPECIFY-YOUR-LOG-TYPES-HERE (e.g. all)} --region=ap-southeast-1 --cluster=my-yaml-eks' 2021-10-18 22:35:29 [ℹ] Kubernetes API endpoint access will use default of {publicAccess=true, privateAccess=false} for cluster "my-yaml-eks" in "ap-southeast-1" 2021-10-18 22:35:29 [ℹ] 2 sequential tasks: { create cluster control plane "my-yaml-eks", 2 sequential sub-tasks: { 4 sequential sub-tasks: { wait for control plane to become ready, associate IAM OIDC provider, 2 sequential sub-tasks: { create IAM role for serviceaccount "kube-system/aws-node", create serviceaccount "kube-system/aws-node", }, restart daemonset "kube-system/aws-node", }, create managed nodegroup "ng-5c441b7d", } } 2021-10-18 22:35:29 [ℹ] building cluster stack "eksctl-my-yaml-eks-cluster" 2021-10-18 22:35:30 [ℹ] deploying stack "eksctl-my-yaml-eks-cluster" Once it's done. Make sure the cluster is accessible Setup Crossplane At first, I plan to use ACK but then I remember a friend of mine talked about Crossplane the other day so I want to give it a try. Bonus point, it works with multiple cloud providers :) I'm going to use Helm so make sure you have it installed. Simply follow the official installation instructions on Crossplane website here. As of this post, 1.4.1 is the latest chart version. kubectl create namespace crossplane-system helm repo add crossplane-stable helm repo update helm install crossplane --namespace crossplane-system crossplane-stable/crossplane --version 1.4.1 NAME: crossplane LAST DEPLOYED: Mon Oct 18 23:05:25 2021 NAMESPACE: crossplane-system STATUS: deployed REVISION: 1 TEST SUITE: None NOTES: Release: crossplane Chart Name: crossplane Chart Description: Crossplane is an open source Kubernetes add-on that enables platform teams to assemble infrastructure from multiple vendors, and expose higher level self-service APIs for application teams to consume. Chart Version: 1.4.1 Chart Application Version: 1.4.1 Kube Version: v1.20.7-eks-d88609 Check the status helm list -n crossplane-system kubectl get all -n crossplane-system Also, make sure to install the Crossplane CLI. curl -sL | sh Setup Crossplane provider for AWS apiVersion: pkg.crossplane.io/v1 kind: Provider metadata: name: provider-aws spec: package: crossplane/provider-aws:alpha After the provider is ready, apply the following next. You need to do this in 2 steps because otherwise, ProviderConfig kind is unknown. apiVersion: v1 stringData: config: | [default] aws_access_key_id = <your-aws-access-key-id> aws_secret_access_key = <your-aws-secret-access-key> kind: Secret metadata: creationTimestamp: null name: aws-credentials --- apiVersion: aws.crossplane.io/v1beta1 kind: ProviderConfig metadata: name: aws-provider-config spec: credentials: source: Secret secretRef: namespace: crossplane-system name: aws-credentials key: config Check the status of the provider kubectl get providers Let's try to create some resources on AWS Let's do a S3 bucket first. Make sure you do a random bucket name so that it won't conflict with an existing bucket. apiVersion: s3.aws.crossplane.io/v1beta1 kind: Bucket metadata: name: test-bucket-1923981293819238 namespace: default spec: providerConfigRef: name: aws-provider-config forProvider: locationConstraint: ap-southeast-1 acl: private After a few seconds, the resource status will change to Ready and Synced. So that's cool. What's next? Let's trying to use OPA or Kyverno to set some rules for our newly created resources. Setup Kyverno I'm gonna go with Kyverno here. No particular reason. I just feel OPA is too mainstream. The concept with OPA is similar. You can take it as homework for your lab session. Let's install Kyverno with Helm helm repo add kyverno helm repo update helm install kyverno-crds kyverno/kyverno-crds --namespace kyverno --create-namespace helm install kyverno kyverno/kyverno --namespace kyverno Now, let's write a simple policy. Say, we don't want to allow creating S3 bucket anywhere except in ap-southeast-1 region. apiVersion: kyverno.io/v1 kind: ClusterPolicy metadata: name: allow-s3-ap-southeast-1-only annotations: pod-policies.kyverno.io/autogen-controllers: none policies.kyverno.io/title: Allow creating S3 bucket in ap-southeast-1 only policies.kyverno.io/subject: Bucket policies.kyverno.io/description: >- Allow creating S3 bucket in ap-southeast-1 only spec: validationFailureAction: enforce background: true rules: - name: s3-in-ap-southeast-1-only match: resources: kinds: - Bucket validate: message: "Using any location other than `ap-southeast-1` is not allowed" pattern: spec: forProvider: locationConstraint: "ap-southeast-1" Now, let's try to create a S3 bucket in us-east-1 region. You will be blocked by the admission controller. # bad-s3.yaml apiVersion: s3.aws.crossplane.io/v1beta1 kind: Bucket metadata: name: test-bucket-091289310923801928309123 namespace: default spec: providerConfigRef: name: aws-provider-config forProvider: locationConstraint: us-east-1 acl: private kubectl create -f bad-s3.yaml Now, the policy we have here is very simple but you can do all kind of stuff with Kyverno cluster policy. It would be a cool weekend hack to convert all rules you have currently to Kyverno cluster policy. That sounds like tons of fun :) Conclusion I'm not going to tell you should start doing this but it's a feasible way of managing infrastructure at small scale. Also with the release of AWS Cloud Control API, the resources model is very close with the Kubernetes resources model now. I'm expecting ACK to get much much better. Have fun hacking AWS :) Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/aws-builders/aws-the-yaml-way-3kgh
CC-MAIN-2021-49
refinedweb
1,388
54.12
The Content Translation tool makes it easier to create new Wikipedia articles from other languages. You can now start translations from your Contributions link, where you can find articles missing in your language. Screenshot by Runa Bhattacharjee, licensed under CC0 1.0 Since it was first introduced three months ago, the Content Translation tool has been used to write more than 850 new articles on 22 Wikipedias. This tool was developed by Wikimedia Foundation’s Language Engineering team to help multilingual users quickly create new Wikipedia articles by translating them from other languages. It includes an editing interface and translation tools that make it easy to adapt wiki-specific syntax, links, references, and categories. For a few languages, machine translation support via Apertium is also available. Content Translation (aka CX) was first announced on January 20, 2015, as a beta feature on 8 Wikipedias: Catalan, Danish, Esperanto, Indonesian, Malay, Norwegian (Bokmal), Portuguese, and Spanish. Since then, Content Translation has been added gradually to more Wikipedias – mostly at the request of their communities. As a result, the tool is now available as a beta feature on 22 Wikipedias. Logged-in users can enable the tool as a preference on those sites, where they can translate articles from any of the available source languages (including English) into these 22 languages. Here is what we have learned by observing how Content Translation was used by over 260 editors in the last three months. Translators Number of users who enabled this beta feature over time on Catalan Wikipedia. Graph by Runa Bhattacharjee, CC0 1.0 To date, nearly 1,000 users have manually enabled the Content Translation tool — and more than 260 have used it to translate a new article. Most translators are from the Catalan and Spanish Wikipedias, where the tool was first released as a beta feature. Articles Articles published using Content Translation. Graph by Runa Bhattacharjee, CC0 1.0 Articles created with the Content Translation tool cover a wide range of topics, such as fashion designers, Field Medal scholars, lunar seas and Asturian beaches. Translations can be in two states: published or in-progress. Published articles appear on Wikipedia like any other new article and are improved collaboratively; these articles also include a tag that indicates that they were created using Content Translation. In-progress translations are unpublished and appear on the individual dashboard of the translator who is working on it. Translations are saved automatically and users can continue working on them anytime. In cases where multiple users attempt to translate or publish the same article in the same language, they receive a warning. To avoid any accidental overwrites, the other translators can publish their translations under their user page — and make separate improvements on the main article. More than 875 new articles have been created since Content Translation has been made available — 500 of which were created on the Catalan Wikipedia alone. Challenges When we first planned to release Content Translation, we decided to monitor how well the tool was being adopted — and whether it was indeed useful to complement the workflow used by editors to create a new article. The development team also agreed to respond quickly all queries or bugs. Complex bugs and other feature fixes were planned into the development cycles. But finding the right solution for the publishing target proved to be major challenge, from user experience to analytics. Originally, we did not support publishing into the main namespace of any Wikipedia: users had to publish their translations under their user pages first and then move them to the main namespace. However, this caused delays, confusion and sometimes conflicts when the articles were eventually moved for publication. In some cases, we also noticed that articles had not been counted correctly after publication. To avoid these issues, that original configuration was changed for all supported sites. A new translation is now published like any other new article and in case an article already exists or gets created while the translation was being done, the user is displayed warnings. New features Considering the largely favorable response from our first users, we have now started to release the tool to more Wikipedias. New requests are promptly handled and scheduled, after language-specific checks to make sure that proposed changes will work for all sites. However, usage patterns have varied across the 22 Wikipedias. While some of the causes are outside of our control (like the total number of active editors), we plan to make several enhancements to make Content Translation easily discoverable by more users, at different points of the editing and reading workflows. For instance, when users are about to create a new article from scratch, a message gives them the option to start with a translation instead. Users can also see suggestions in the interlanguage link section for languages that they can translate an article into. And last but not least, the Contributions section now provides a link to start a new translation and find articles missing in your language (see image at the top of this post). In coming months, we will continue to introduce new features and make Content Translation more reliable for our users. See the complete list of Wikipedias where Content Translation is currently available as a beta feature. We hope you will try it out as well, to create more content Runa Bhattacharjee, Language Engineering, Wikimedia Foundation by Andrew Sherman at 08 April 2015 05:10 PM
http://www.w3.org/International/planet/
CC-MAIN-2015-18
refinedweb
906
51.28
11886/behaviour-of-increment-and-decrement-operators-in-python I you want to increment or decrement, you typically want to do that on an integer. Like so: b++ But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. So you have to reassign. Like this: b = b + 1 Or simpler: b += 1 Which will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it. In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop. down voteaccepted ++ is not an operator. It is ...READ MORE You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE AND - True if both the operands ...READ MORE Python has no unary operators. So use ...READ MORE can you give an example? READ MORE if you google it you can find. ...READ MORE suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE can you give an example using a ...READ MORE There are 4 types of dictionary Empty Integer Mixed Dictionary with ...READ MORE In cases when we don’t know how ...READ MORE OR
https://www.edureka.co/community/11886/behaviour-of-increment-and-decrement-operators-in-python
CC-MAIN-2019-22
refinedweb
249
76.93
US20030099237A1 - Wide-area content-based routing architecture - Google PatentsWide-area content-based routing architecture Download PDF Info - Publication number - US20030099237A1US20030099237A1 US10/295,036 US29503602A US2003099237A1 US 20030099237 A1 US20030099237 A1 US 20030099237A1 US 29503602 A US29503602 A US 29503602A US 2003099237 A1 US2003099237 A1 US 2003099237A1 - Authority - US - United States - Prior art keywords - content - vcn - routing - tag - Prior art date - Legal status (The legal status is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the status listed.) - Granted Links - 235000008694 Humulus lupulus Nutrition 0 description76 aggregation Effects 0 description 2 - 238000004458 analytical methods Methods 0 claims description 9 - 239000002585 base Substances 0 description 1 - 230000006399 behavior Effects 0 description 7 - 238000009739 binding Methods 0 description 14 - 230000027455 binding Effects 0 description 19 - 238000004422 calculation algorithm Methods 0 claims description 11 - 239000000969 carrier Substances 0 description 1 - 239000003795 chemical substance by application Substances 0 description 3 - 238000007635 classification algorithm Methods 0 description 1 - 238000004891 communication Methods 0 description 2 - 238000007906 compression Methods 0 description 1 - 239000000470 constituents Substances 0 description 1 - 238000010276 construction Methods 0 description 1 - 235000014510 cookies Nutrition 0 abstract description 3 - 239000011162 core materials Substances 0 claims description 10 - 230000000875 corresponding Effects 0 abstract claims description 9 - 238000000354 decomposition Methods 0 description 1 - 230000003247 decreasing Effects 0 description 1 - 230000001934 delay Effects 0 description 1 - 230000001419 dependent Effects 0 description 6 - 238000009826 distribution Methods 0 description 8 - 230000000694 effects Effects 0 description 5 - 238000005538 encapsulation Methods 0 claims description 6 - 238000005516 engineering processes Methods 0 abstract description 3 - 230000002708 enhancing Effects 0 description 1 - 239000000284 extracts Substances 0 description 2 - 239000000727 fractions Substances 0 claims description 6 - 238000009963 fulling Methods 0 description 1 - 235000019580 granularity Nutrition 0 claims 1 - 230000012010 growth Effects 0 description 1 - 230000001965 increased Effects 0 description 2 - 230000000977 initiatory Effects 0 description 2 - 239000010410 layers Substances 0 claims description 11 - 239000011133 lead Substances 0 description 3 - 239000010912 leaf Substances 0 description 4 - 230000013016 learning Effects 0 description 2 - 235000009808 lpulo Nutrition 0 description 15 - 239000011159 matrix materials Substances 0 description 8 - 239000002609 media Substances 0 description 2 - 238000000034 methods Methods 0 abstract claims description 50 - 239000000203 mixtures Substances 0 description 6 - 230000001343 mnemonic Effects 0 description 1 - 238000005192 partition Methods 0 claims description 3 - 235000014594 pastries Nutrition 0 description 4 - 230000037361 pathway Effects 0 abstract description 3 - 230000000737 periodic Effects 0 claims 1 - 230000002265 prevention Effects 0 description 1 - 230000001737 promoting Effects 0 description 1 - 230000002829 reduced Effects 0 claims 1 - 230000001603 reducing Effects 0 description 1 - 230000003362 replicative Effects 0 description 1 - 230000004044 response Effects 0 description 1 - 238000007493 shaping process Methods 0 description 2 - 238000000638 solvent extraction Methods 0 claims description 2 - 230000003068 static Effects 0 description 1 - 238000007619 statistical methods Methods 0 description 2 - 238000003860 storage Methods 0 claims description 21 - 230000002123 temporal effects Effects 0 description 2 - 235000010384 tocopherol Nutrition 0 description 3 - 235000019731 tricalcium phosphate Nutrition 0 description 3 - Content networking is an emerging technology, where the requests for content accesses are steered by “content routers” that examine not only the destinations but also content descriptors such as URLs and cookies. In the current deployments of content networking, “content routing” is mostly confined to selecting the most appropriate back-end server in virtualized web server clusters. This invention presents a novel content-based routing architecture that is suitable for global content networking. In this content-based routing architecture, a virtual overlay network called the “virtual content network” is superimposed over the physical network. The content network contains content routers as the nodes and “pathways” as links. The content-based routers at the edge of the content network may be either a gateway to the client domain or a gateway to the server domain whereas the interior ones correspond to the content switches dedicated for steering content requests and replies. The pathways are virtual paths along the physical network that connect the corresponding content routers. The invention is based on tagging content requests at the ingress points. The tags are designed to incorporate several different attributes of the content in the routing process. The path chosen for routing the request is the optimal path and is chosen from multiple paths leading to the replicas of the content. Description - The hyper-growth of the Internet along with the emergence of several business-critical applications that heavily rely on the Internet have increased the load on its infrastructural services. Some of the crucial Internet services for applications include facilities to access content, support for efficiently transporting content and the ability to discover and access services. Caching and replication are two traditional strategies that may be employed to improve Internet services. These strategies can be implemented in two different ways: (a) on demand by the clients (content or service requesters) or (b) by the servers (content or service providers). [0001] - On-demand caching by clients is a well established technique that is commonly used in the Internet. Simplicity is one of the advantages of this technique. By reducing the net load imposed by an application on the Internet infrastructure, this technique attempts to improve the overall performance. In this scheme, the service providers do not have direct control over the caching decisions. As business critical applications are deployed over the Internet, it is becoming necessary for the service providers to ensure that the clients are receiving service at a satisfactory level to preserve brand equity and customer loyalty. [0002] - This issue has prompted a flurry of activities in the area of server-initiated caching and replication. One emerging technology in this area is content-aware networking. In content-aware networking, a new generation of routers specifically designed to address the unique requirements of Web traffic are used. These “content-based” routers have the ability to route TCP or UDP flows based on the URL and cookie in the payload. This ability allows the assignment of requests to one of various servers depending on the specific content requested. The previous generation of routers were able to route incoming packets based on the destination IP, protocol ID, and transport port number. Under this scenario the router cannot differentiate, for example, between a CGI script request or a streaming audio request, both of which use TCP port 80 but have very different quality of service (QoS) requirements. Content-based routers provide flexibility in defining policies for prioritizing traffic and for balancing load and content among servers so that Service Level Agreements can be met. [0003] - Content networking technologies can be deployed in several ways to improve a user's experience on the Internet. The first approach is the construction of virtual web servers, where a collection of servers or server clusters appear as one server. This approach can be generalized to arrive at the second approach where virtual web sites are constructed from one or more geographically dispersed data centers that appear as one domain name. [0004] - In the first approach [25], a content router is interposed between the client and server, i.e., a request should pass through the content router. The content router examines the payload contained in the request packet and chooses an appropriate destination. In this mode of deployment, the content router is used as a load balancer for the back-end servers and the content router should be all knowing to make optimal decisions. In the second approach [27], nameservers may be used to select the most appropriate “server site” depending on the geographical locations of the clients and servers and network and server loadings. The first approach has the disadvantage of lack of scalability and a single point of failure and the second approach is inefficient in handling portions of a site (i.e., the hosting site cannot be partitioned on granularity of the documents, the whole site needs to be accessed or replicated). [0005] - In essence, content routing involves both locating and accessing content. Locating content includes content discovery on the network. Accessing content typically requires identifying a network path with the desired quality of service parameters and setting up sufficient resources along the path. The Intentional Naming System (INS) [26] presents a resource discovery and routing system based on the description of the services. This method is less scalable than the hierarchical name-space provided by the URLs and also the variable length of names would lead to expensive route resolution at each name-based router. The Name Based Routing Protocol (NBRP) [16] use a two-phase approach, similar to the current data access paradigm in the Internet, where variable length content names are resolved to addresses before the actual content is being exchanged. [0006] - The Content Addressable Network (CAN) [24] presents a highly distributed hash table architecture that can be implemented on the Internet. The main idea is to create a virtual coordinate space of multiple dimensions and hash a key on to this space. This is highly scalable routing architecture, however, content placement in the coordinate space becomes location dependent. In a similar approach, the Pastry system [2] is an overlay network of nodes where each node is assigned a randomly generated 128-bit identifier to denote the node's position in a circular nodeid space. Given a message with a key, a Pastry node routes the message to a node whose identification number, called nodeid, is numerically closest to the key. The routing metric involved is the number of IP routing hops. Pastry is decentralized system and is a highly scalable routing mechanism. The Service Level Routing [17] framework provides a general architecture for accessing and discovering services and content on the Internet. The service level routing is performed by service level routers (SLRs) posing as ingress and and egress routers between clients and the servers and is very efficient in mapping individual flows onto virtual networks. The content routing protocol presented [6] uses a Content Routing Protocol (CRP) based on the URL decomposition of data objects. It constructs and maintains a namespace tree by identifying the protocol, network location, and individual paths for the contents. This method is highly suitable for compressing large number of content names into smaller inverted URL tree form. [0007] - Currently, the most popular and widely deployed technique on the Internet is the Domain Name System (DNS) [11, 9]. It uses a distributed database maintained and stored across a hierarchy of nameservers. The nameservers in DNS are used to map mnemonic names to network locations. A DNS-based routing technique is a routing scheme that uses DNS name resolution service to map a request on to a network location and then routes the request to that location. The DNS uses a manually delegated name space that is partitioned in domains and subdomains. Each domain is administered by an authoritative nameserver. The clients and the hosting servers will query their own local nameserver for name resolution. Name servers will either reply to a query or refer the query to an higher level nameserver. Currently, a number of content distribution overlay networks use the DNS for redirecting user requests and perform load balancing among the content hosting servers. A recent study [5] identifies two types of Content Distribution Networks (CDNs), using the DNS redirection techniques. The final results of the study, however, reveals that in average case situations, response times do not improve by using the DNS lookups for a new server. Yet another study [13], reveals that the CDNs using DNS do not select the best server in a consistent manner. A recent study [3] shows that a server chosen through DNS-based name resolution is not necessarily the optimal server. More clearly, a server selected by this technique is not always close to a client. As a result, the hosting server chosen to be close to the client's local nameserver is not necessarily the closest to the client. This study also suggests that to improve the performance of the DNS protocol, it is necessary to carry additional information to identify the requesting client. [0008] - The following references disclose subject matter which are relevant to the present invention, the disclosure of which is incorporated herein by reference. [0009] - [1] A. Anastasiadi and S. Kapidakis. A Computational Economy for Dynamic Load Balancing and Data Replication. In 1[0010] st International Conference on Information and Computation Economies, pages 166-180, October 1998. - [2] A. Rowstron and P. Druschel. Pastry: Scalable, distributed object location and routing for large-scale peer-to-peer systems. In 18[0011] th IFIP/ACM International Conference on Distributed Systems Platform (Middleware '01), pages 329-350, November 2001. - [3] A. Shaikh, R. Tewari, and M. Agrawa. On the Effectiveness of DNS-based Server Selection. In [0012] IEEE INFOCOM, volume 3, pages 1801-1810, April 2001. - [4] B. Davie and Y. Rekhter. [0013] MPLS: Technology and Applications. Morgan Kaufmann Publishers, San Diego, Calif., 2000. - [5] B. Krishnamurthy, C. Wills, and Y. Zhang. On the Use and Performance of Content Distribution Networks. In [0014] Proceedings of ACM SIGCOMM Internet Measurement Workshop, August 2001. - [6] B. S. Michel, K. Nikoloudakis, P. Reiher, and L. Zhang. URL Forwarding and Compression in Adaptive Web Caching. In [0015] IEEE INFOCOM, volume 2, pages 670-678, March 2000. - [7] D. Black. Differentiated Services and Tunnels, October 2000. [0016] - [8] D. Farinacci, T. Li, S. Hanks, D. Meyer, and P. Traina. Generic Routing Encapsulation (GRE), March 2000. [0017] - [9] G. Kessler and S. Shepard. A Primer On Internet and TCP/IP Tools and Utilities, March 1997. [0018] - [10] G. Malkin. RIP Version 2 Protocol Analysis, November 1994. [0019] - [11] J. Postel. Domain Name System Structure and Delegation, March 1994. [0020] - [12] J. Moy. OSPF Version 2, April 1998. [0021] - [13] K. L. Johnson, J. F. Carr, M. S. Day, and M. F. Kaashoek. The Measured Performance of Content Distribution Networks. In [0022] Computer Communications, volume 24(2), pages 202-206, May 2001. - [14] K. Nichols, S. Blake, F. Baker, and D. Black. Definition of the Differentiated Services Field (DS Field) in the IPv4 and IPv6 Headers, December 1998. [0023] - [15] M. Day, B. Cain, G. Tomlinson, and P. Rzewski. A Model for Content Internetworking (CDI), November 2001. [0024] - [16] M. Gritter and D. R. Cheriton. An Architecture for Content Routing Support in the Internet. In [0025] USENIX Symposium on Internet Technologies and Systems, March 2001. - [17] N. Anerousis and G. Hjalmtysson. Service Level Routing on the Internet. In [0026] IEEE Globecom, volume 1b, pages 553-559, December 1999. - [18] N. Freed and N. Borenstein. Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types, November 1996. [0027] - [19] P. Mockapetris. Domain Names-Concepts and Facilities, November 1987. [0028] - [20] S. Blake, D. Black, M. Carlson, E. Davies, Z. Wang, and W. Weiss. An Architecture for Differentiated Services, December 1998. [0029] - [21] S. Brown. [0030] Implementing Virtual Private Networks. McGraw Hill, Berkeley, Calif., 1999. - [22] S. Herzog. RSVP Extensions for Policy Control, January 2000. [0031] - [23] S. Kent and R. Atkinson. Security Architecture for the Internet Protocol, November 1998. [0032] - [24] S. Ratnasamy, P. Francis, M. Handley, and R. Karp. A Scalable Content-Addressable Network. In [0033] ACM Conference on Applications, Technologies, Architectures and Protocols for Computer Communications, pages 161-172, August 2001. - [25] V. Pai, M. Aron, G. Banga, M. Svendsen, P. Druschel, W. Zwaenepoel, and E. Nahum. Locality-Aware Request Distribution in Cluster-based Network Servers. In 8[0034] th ACM Conference on Architectural Support for Programming Languages and Operating Systems, pages 205-216, October 1998. - [26] W. Adjie-Winoto, E. Schwartz, H. Balakrishnan, and J. Lilley. The Design and Implementation of an Intentional Naming System. In 17[0035] th ACM Symposium on Operating Systems Principles (SOSP '99), pages 186-201, December 1999. - [27] W. Tang, F. Du, M. W. Mutka, L. M. Ni, and A. Esfahanian. Supporting Global Replicated Services by a Routing-Metric-Aware DNS. In 2[0036] nd International Workshop on Advanced Issues of E-Commerce and Web Based Information Systems, pages 67-74, June 2000. - The following U.S. patent references have been identified in a search in this field. [0037] # Patent Date Pub. Patent Name 6363319 Mar. 26, 2002 Constraint-based route selection using biased cost 6430618 Aug. 6, 2002 Method and apparatus for distributing requests among plurality of resources 6216173 Apr. 10, 2001 Method and apparatus for content processing and routing 6256675 Jul. 3, 2001 System and method for allocating requests for objects and managing replicas of objects in a network 6052718 Apr. 18, 2001 Replica routing 6058423 May 2, 2000 System and method for locating resources in a distributed network 5968121 Oct. 19, 1999 Method and apparatus for representing and applying network topological data 6006264 Dec. 19, 1999 Method and system for directing a flow between client and a server 5812768 Sep. 22, 1998 Method and apparatus for redirecting a user for a new location on the world wide web using relative universal resource locators 5511208 Apr. 23, 1996 Locating resources in computer networks having cache servers nodes 5251205 Oct. 10, 1993 Multiple protocol routing 4914571 Apr. 3, 1990 Locating resources in a computer network - FIG. 1 shows the virtual content network. The physical network consists of two client and two server sites. The client sites are connected to the server sites through the VCN. [0038] - FIG. 2 shows the tagging process in a CER. The client requests received are parsed and tagged at the CER. The tag contains information regarding the content and the also the application requirements. An probable tag format is shown in FIG. 7. [0039] - FIG. 3 shows the routing process in a CSR. The tag used to encapsulate network packets is used to route the packets. [0040] - FIG. 4 shows the matrix created to classify contents based on their popularity within the VCN. The content equivalence classes are created based on this classification. [0041] - FIG. 5 shows the algorithm which is used to create the content equivalence classes. [0042] - FIG. 6 shows the sequence in which temporary and the content-based tags are created and managed. [0043] - FIG. 7 shows a probable format for the content-header which is used to encapsulate network packets. [0044] - FIG. 8 shows the namespace tree that is used to store the content names and the corresponding tags. [0045] - FIG. 9 shows the different approaches used for routing by the traditional routing techniques and by the invention. [0046] - FIG. 10 shows an example for distributing tag information within the VCN. [0047] - FIG. 11 shows an example for steering requests or routing requests from ingress to egress CERs. [0048] - FIG. 12 shows the method used by VCN to store the namespace tree by creating groups of CERs. Each CER group will hold the entire namespace tree in distributive fashion. [0049] - FIG. 13 shows the entire process for routing in the VCN. [0050] - FIG. 14 shows a probable list of structural attributes that are used to characterize content. [0051] - FIG. 15 shows a probable list of semantical attributes that are used to characterize content. [0052] - FIG. 16 shows the different types of content and their field codes. [0053] - FIG. 17 shows a probable list of different end-data types which currently in use. [0054] - Routing is a process of providing a path for client requests to the host which can serve the request. The source and the destination addresses contained inside the network packet holding the request are used to route the packet towards a server host. [0055] - The requested host may be overloaded with a very large number of requests or reside in a network which is congested due to very high traffic. In such a case, the client may have to wait for a long time. To avoid such situations and serve the clients better, the content providers replicate their contents across the Internet. To redirect the client requests to these replicated hosting sites, connection providers came up with a number of routing procedures for directing client requests to servers which can serve the request in the best possible manner at that instant. [0056] - However, with the exponential growth of Internet and the corresponding increase in the number of users, the existing routing architectures were not always capable of handling the high volumes of client requests suitably. It was conjectured that in order to maintain the quality of service for very high volumes of client requests it is necessary to identify the network condition and the properties of the content requested and use this information in addition to the source-destination addresses to redirect the requests to the best performing server hosts. [0057] - Content routing is a process which routes requests based on the properties of the content requested and the network condition. In the current deployments, content routers parse network packets to identify the properties of the contents held in the packets and use the information to find the best path to a server. However, these processes suffer overhead from repeated parsing of the packets at each router. To solve this problem, naming systems were developed that use name resolvers to map a request to a location serving the requested content. But such content routing schemes often lead to high volumes of content descriptions, used for name resolution, that are difficult to manage or lack the complexity to maintain the consistency of network performance. This made it necessary to fine-tune the content routing procedures that can avoid such problems. [0058] - This invention presents a content routing architecture that solves the above problems. The invention employs a content characterization scheme that makes it possible to identify and partition large volumes of dissimilar content. The content characterization scheme makes it possible to determine the properties of content available on the Internet, their resource requirements and their behaviour in accordance to the applications requesting the content. Content aggregations created by this scheme are much easier to manage than the current content routing models. [0059] - The invention creates virtual overlay networks called Virtual Content Network (VCN) that utilize content characterization schemes to map the client requests to the corresponding best performing content hosting site. The overlay network will have Content Edge Routers (CERs) that act as gateways to the content providing servers and also to the clients. The content hosting sites will advertise their data to the CERs who create the content tags that are used as redirections for the client requests. The content tags are distributed among the Content-based Switching Routers (CSR) which form the core of the VCN. The CERs and CSRs are connected by the Content-based Switching Paths (CSPs) which constitutes a network with maximum connectivity between nodes and low transmission costs. The CERs and CSRs will maintain a content routing hash table which holds the tag, the list of possible next hops and the performance metrics used for routing. [0060] - In order to avoid overloading the content routers with all the content tags formed by the VCN, the tags are stored in a distributed fashion through out the VCN. When a CER receives a client request, it will resolve the request to form a tag for the request. A wrapper will be created to encapsulate the content tag and the original request. The tag will be matched against the content routing table and the encapsulation is forwarded to the best next hop which will match the tag to the next best hop in its content routing table. This way the request will travel through the VCN to the egress CER that is closest to the best performing server promoting the request and along the path that is considered optimal at that instant. The egress CER will remove the wrapper and forward the request to the serving host. The result from the server is returned to the client using same path as the request. The optimality of the path will depend on the metrics specified by the application requesting the content at the ingress point. [0061] - The overlay network represents a fast path or a bypass network comprising of content-aware routing elements connected by quality of service (QoS) aware logical paths. The overlay network uses a simple hash table matching procedure, within the core of the network, to route a request to the most healthy server host. At lower layers, the overlay network uses MPLS as a carrier mechanism to implement the content routing method. [0062] - This invention introduces a Protocol Independent Content Switching (PICS) architecture that is suitable for content aware networking in very-large scale geographically distributed networks. In the PICS architecture, several client and server sites are interconnected through a Virtual Content Network (VCN). The client sites contain the eventual consumers of the content that is managed by the VCN. The VCNs themselves can be networked to build larger networks. The client and server sites connect to the VCN using gateways that are content routers. Because the content is first examined by these routers, and they are at the edge of the VCN, we refer to these routers as the content edge routers (CERs). In our architecture, a client or server site can connect via multiple CERs to the VCN. Allowing multiple CERs per site precludes a single point of failure and provides an opportunity for enhanced load balancing among the content hosting servers. The CERs encapsulate the packets using a content header. The content header contains a content-based tag that is used to uniquely identify a content within the VCN. The VCN core has content-based switching routers (CSRs) to steer the content requests from the ingress (i.e., client side) CER to the egress (i.e., server side) CER based on the tags in the content header. The CSRs are simple switches that support a single forwarding component (i.e., algorithm for tag-based forwarding). The CER, on the other hand, are also responsible for characterization and classification of content. [0063] - An example deployment of PICS is illustrated in FIG. 1. It shows two client sites Client-[0064] 1 and Client-2 connecting to the server sites Server-A and Server-B through a VCN. Server-A is connected to the VCN through two CERs whereas Server-B is connected through a single CER. Each of the client sites, Client-1 and Client-2 are also connected to the VCN through a single CER. The VCN consists of several CSRs that are connected by sequences of content switched paths (CSPs) or “pathways.” The CSPs interconnect the CSRs and also connect the CERs to the CSRs. - The CSPs are virtual paths that are created when the VCN is initialized. As client and server sites enter and depart the VCN, the corresponding CSPs may be created and removed, respectively. The CSPs are used to “forward route” the content requests to the appropriate server site and to “reverse route” the content back to the “requesting” client site. [0065] - Server Sites [0066] - The server sites hold the content that is requested by the clients. The simplest server site can be a CER and an attached server that serves the corresponding content. In the general case, multiple CERs can act as front-ends to the servers that are in the site. The servers can be either origin servers or surrogate servers. An origin server holds the original copy of the content, i.e., if there are no replication of content this server will have the only copy. A surrogate server is a server that “rents” its resources so that content from origin servers can be replicated on it. The owner of the origin server that is referred to as the content provider is responsible for “paying” the rent for the surrogate server. By using a computational economy [1] based scheme for replicating content among the origin and surrogate servers it is possible to increase the server side resources for content that are popular and reduce the dedicated resources as the popularity decreases. [0067] - Therefore, in the PICS architecture, the requested content can be delivered either by an origin server or a surrogate server. The VCN does not differentiate between surrogate and origin servers. The server selection algorithm is built into the forward routing process. [0068] - Client Sites [0069] - The client sites have the clients that are requesting content. Typically a client site may have a single CER connecting it with the VCN. However, in some situations it may be useful to have multiple CERs. Some advantages of such configurations include lack of single point of failure and opportunity for traffic shaping within the VCN. Depending on the local routing policies, the CERs can be allocated traffic according to the quality of service (QoS) considerations. [0070] - Virtual Content Network [0071] - The VCN is a graph with the CERs and CSRs as the nodes and the CSPs as the edges. The VCN provides a Content Delivery Network [15] for the server sites to efficiently distribute their content. The VCNs may be deployed using a “peer model” similar to that used in Virtual Private Networks [21]. This model assumes the existence of VCN service providers who host the service. The client and server sites that need “speedy” content delivery would subscribe to the VCN by having content routing enabled gateways (i.e., CERs as gateways) and by connecting such gateways to the VCN core. The different VCN service providers could be connected among themselves to provide a larger virtual network. [0072] - Content Edge Router (CER) [0073] - As mentioned above, the CERs are at the “edges” of the VCN and the client and server sites. When a request for content is generated from a client site, it reaches the client side CER. The CER parses the packet carrying the request and if the content is handled by the VCN, then it identifies the content and tag it. The tag is generated by a combination of the content derived and the policy-based information. FIG. 2 illustrates the overall tagging process in the CERs. The process is discussed in detail in later part of this chapter. [0074] - A CER can be connected by multiple CSPs to the core of the VCN. Therefore, for the content that is handled by the VCN, the CERs should make initial routing decisions as to which core CSR should handle the request next. Each CER has a content-based routing table that is used by the CER for determining the routes. The information can be disseminated across the VCN by either flooding the routing information towards all CERs and maintaining a consistent route image throughout the entire VCN or operate on an on-demand basis. The on-demand approach provides the high activity CERs with more up-to-date route information. [0075] - Content-Based Switching Router (CSR) [0076] - The CSRs form the core of the VCN. Similar to the CERs, the CSRs also maintain content-based routing tables. However, the information contained in the CSR routing tables are different than the information found in the CER routing tables. The CER routing tables also contain the content value (e.g., the URL or cookie value) in addition to the tags generated from the content. The content value is necessary for the CER to perform the content-to-tag mapping. The CSRs use the content-based routing tables to steer the requests towards the appropriate server side CER. FIG. 3 shows the routing process in the CSRs. [0077] - Content-Based Switched Path (CSP) [0078] - The CSPs interconnect the CERs and CSRs to form the VCN. A CSP is similar to a label switched path (LSP) in the Multi-Protocol Label Switching (MPLS) [4]. CSPs can be implemented using frame relay circuits, ATM circuits, IP-in-IP tunnels, generic routing encapsulation (GRE) tunnels [8], or IPSec [23] tunnels. [0079] - IP-in-IP and GRE tunnels can be subject to data spoofing. Some malicious router that is not an end-point of the tunnel could inject packets into the tunnel. Additional packet filters may be used to solve this problem resulting in increased overhead and complexity. Using IPSec tunnels is another way to solve this problem. However, the “key” management used by IPSec to authenticate packets adds cost to the data transmission. [0080] - To provide QoS, all tunneling mechanisms rely on services such as IP differentiated services (Diff-Serv) [20, 7]. When leased lines, frame relay circuits, or ATM circuits are used, stricter guarantees can be given for QoS than those possible with tunnel-based CSPs. One of the advantages of tunnel-based CSPs is that they can be used more widely. If stricter QoS guarantees are essential for the data traffic, then the routing algorithms may constrain such traffic to the appropriate portions of the network. [0081] - Content Characterization and Classification for Content-Based Routing [0082] - Content Characterization [0083] - Content characterization is a process that identifies the key attributes of content which can be used to generate an accurate description of the content and its resource requirements from the perspective of content-based routing and delivery mechanism. The primary motivation is to use this description to discover and access content. This invention identifies a possible list of content attributes that can be used to profile a content from the perspective of content-based routing. Some of the attributes identified are used to describe a content classification and a tagging strategy that is used in the content-based routing scheme. [0084] - To distinguish a content uniquely, it is necessary to understand the structure and semantics of data. The structural attributes and their values are directly dependent on the content while the semantic attributes relate to the behaviour of the application that accesses the content, i.e., the intended usage of the data by the requesting application. For example, an application may use the FTP protocol to download a large video clip for off-line viewing. Another application may access the same video clip for online viewing through a “media player” that requires real-time data transfer capabilities with QoS attributes. The routing schemes should be able to deduce this difference in service. [0085] - The invention intends to create a content profile a priori to the routing process. Such a profile is used to locate the content and also allows the routing protocol to infer those characteristics that directly affects the content delivery mechanism (e.g., bandwidth required for delivery). In a delivery network, such a profile should also surmise a content provider's relative status with respect to the other providers using the CDN services. Again, a content routing process, in effect, is triggered by an application agent requesting the content. At the time of request initiation, the agent specificies some rules for content access, like the QoS parameters like Diff-Serv. The routing system interfaced with the agent should ensure the requested QoS while delivering the content. To ensure that all these requirements of the content are met, in the characterization scheme, the content attributes are grouped in two distinct classes. The first class of attribute values are known prior to the routing process and can be used to create a content description, a priori, which is then used to discover the content on a network. The second class of attributes are initialized only at the time a request for the content is submitted and is used for accessing the content. A combination of these attibutes will decide the network resources that should be allocated for a request. More specifically, these classes can be defined as follows: [0086] - Structural Attributes: These are the properties of the content that impact the amount of computation and/or communication resources needed for handling the content and they are invariant of the requesting application or the user. [0087] - Semantical Attributes: These are the properties of the content that impact the amount of computation and/or communication resources needed for handling the content and they are dependent on the requesting application or the user. Their values depend on various conditions that are imposed at the time the content is being requested. [0088] - FIG. 14 shows a representative set of the structural attributes that are relevant for describing content. Structural attributes are further classified into four categories, where each category is used to define a definite set of structural properties for the content. In our content-based routing, some values from each category are used to describe the content. The physical attributes describe the properties of the content that are shared between the file system and the network. The name-based attributes are used to label the content for identification and location purposes. The names may be chosen in various ways. Some names may have components of the location embedded in them, e.g., URLs. While other names such as filenames may be arbitrarily chosen. The end data type attributes refer to the content formats. Although these formats are relevant to the end applications, these formats are independent of the applications and may have impact on the way the content could be handled by the network. The popularity attributes gives the spatial and temporal “interest” for the given content among the user population. The demand imposed by the content on the network may be indirectly depend on the popularity attributes. The spatial popularity refers to the current demand for the content in a specific portion of the VCN. The temporal popularity refers to the global demand across the VCN for the content over a specific time period. [0089] - FIG. 15 shows a representative set of semantic attributes. The semantic attributes can be further classified into four different categories with each category describing a definite class of resource requirements for the content and the application requesting the content. The access attributes define the requirements of the applications that access the content. These attributes may determine some of the service measures associated with or required by the content. For example, whether a content is of streaming type and its bit-rate characteristics may determine its bandwidth requirements. The quality of service (QoS) attributes defines the amount of network resources needed to support the application's access of the content. While the access attributes define an application's “intentions” from the application perspective, the QoS attributes define the same intentions from the network perspective. The end data type attributes are used to differentiate static and dynamic contents. Dynamic content is assembled on-demand based on inputs from the user or the accessing application. [0090] - The main idea to group the contents using their variable and non-variable properties is due to the intention to create aggregates (or groups) of contents with identifiable properties. A combination of some of the variable and non-variable attributes is used to create the aggregations and enable our content-based routing system to learn about the contents and their resource requirements. This a learning process for the routing model. Some of the variable content attributes are used to relate the contents to the forwarding algorithm built into our content-based routing scheme to implement suitable traffic shaping policies. Using such a scheme, the routing process in the content aware network is partially accomplished by setting up virtual path segments during the learning process. The remaining portion of the routing process may be done by switching the content requests and replies across the virtual path segments using some “content-based tag” that is generated from the content-aggregate attribute values. [0091] - Content Classification [0092] - Content classification is a process of grouping documents into classes such that the expected resource requirements for handling the documents within a class are similar. These classes are referred as Content Equivalence Classes (CECs). The resource requirements for handling documents include the resources used for storage and processing purposes and resources used for transporting purposes. The storage and processing resources are determined by the structural attributes of the content while the resources for transporting the content are determined by the semantic attributes of the content. The structural and semantic attributes are discussed in Section. A CEC will inherit the attribute values from its constituent documents. A CEC is identified by a tag that is derived from the attribute values of the CEC. This tag is used for discovering and accessing each individual document that constitutes the CEC. [0093] - The motivation to use content groups and content-derived tags is to compress the namespace that is used by the routing system for locating and accessing content. In traditional routing schemes, the routing is performed based on addresses with a pre-defined format and length, i.e., the size of the address space is fixed. These routing schemes are, however, completely location dependent. The main idea behind content-based routing is to liberate content access and discovery from the “original” location that holds or owns the content. In general, to achieve this the content-routing schemes base their routing on a set of attributes that describe the content. Mostly, some form of content-name that is not dependent on the actual location is used for content-routing (e.g., URL of the content). One of the major challenges with a routing scheme based on content-naming is that the namespace can be very large. However, in practice, the number of distinct content names that are handled by a content-based routing system is a very small fraction of the total namespace. In our content-based routing scheme, we use the attribute values of the CECs to generate fixed-length tags. By grouping multiple contents in a single CEC, we actually bind the specifications of multiple contents in one description (i.e., one name can be used to identify multiple contents). Since each CEC has distinct attribute values, the tags will always be unique within the VCN, and also the total number of tags will be much less than the actual number of individual documents. Further, the tag can be used by the content routers to infer about a content i.e., the routers do not have to be all knowing about the contents for making an optimal routing decision. [0094] - The content classification process of the invention includes two phases. In the first phase, the resource requirements for storage and processing are identified and the CECs are created. This process is usually performed when a content is first introduced in the VCN. It can also be repeated when the configuration of the VCN changes. During this phase, a portion of the tag is derived that is used to discover content. We call this portion of the tag as the primary tag. The remaining portion of the tag, called the secondary tag, is derived during the second phase of the classification process. The second phase identifies the values for the semantic attributes of content at the time a client submits a request to the VCN. The semantic attribute values are used to select an appropriate path from the client to the server. The secondary tags may also be used by the CERs/CSRs to partition the set of all possible requests for the same content into disjoint subsets. From a forwarding point of view, all requests within a subset will be treated in the same way by the content routers in the VCN. [0095] - The first phase of content classification process can be performed in two ways similar to the differentiated services: (a) behavior aggregate (BA) and (b) multifield (MF). In the BA, the content owner is cognizant of the content behavior (e.g., demand) of the content to specify how the content should be handled. Typically, the content owners would request the VCN to handle their content as a class by itself. The tag assignment, however, is performed by the VCN. For example, a suitable pricing scheme and service level agreements for the content management service that is beyond the scope of this document may be used to prevent a customer from denying services to other customers. In the MF, the content owner is not cognizant of the content behavior but wishes to use the VCN for faster content delivery. In this case, the VCN performs content classification using the scheme described below. [0096] - In the content-based routing scheme, during the first phase, the CERs use the structural attributes to describe a content's storage and processing resource requirements. These are (a) content size that indicates the storage space required at the surrogate servers, (b) the type of content e.g., streaming or non-streaming, audio/video or text, (c) popularity of the document containing the content (i.e., the number of times the document was requested with respect to other documents available in the VCN), and (d) the minimum network-based resources (e.g., bandwidth) and the time required to deliver a content (this is considered only in case of streaming contents). These attributes provide the most generic description about what is being transported across the network. Statistical analysis of the Internet traffic provides all the attribute information required for classification of content. [0097] - One may think about the first phase as a procedure of partitioning the set of all possible documents that the VCN can handle into a finite number of disjoint subsets, called CECs, where each subset holds a finite number of documents of similar type and having similar storage space requirements. Storage space requirement gives the measure of how much storage space should be allocated to contents with respect to their popularity within the routing domain. We group together all contents that require similar storage space and are of similar type. Each CEC is identified by a tag that is unique within the VCN. Client requests are marked by the tag which is used to identify the CEC (and in turn the hosting server) holding the content requested by the client. From the routing point of view, all client requests that have the same tag are handled in the same way by a CER or CSR as compared to other requests with different tags (e.g., requests with similar tags require similar resources). [0098] - Next, the process for creating the CECs is described. We assume that the VCN being an overlay network, will cover portions of several autonomous systems (AS) which make up the Internet. Our classification algorithm uses the popularity of the contents within each AS as a rank estimation factor to measure the amount of storage resources required by each document. This is done by constructing a document-AS matrix A where each row of the matrix corresponds to a document hosted by the VCN and each column corresponds to an AS which is part of the VCN. The matrix elements represent the relative storage space required for each document as per its popularity level within each AS, i.e., [0099] - matrix A m×n =[a ij] - where m denotes the number of documents hosted by the VCN and n denotes the number of AS(s) which are part of the VCN and a[0100] ij is the ratio and popularity of the document i in AS j such that 0<i≦m and 0<j≦n. We call aij as the relative weight for document i in AS j. In effect, the relative weight scale will determine the storage space requirements of each content relative to other contents in the VCN. In practice, local and global weights are applied to increase/decrease the popularity of documents within each AS. Specifically, - where s[0101] i,t is the size of the document i and which is of type t, {overscore (s)}t is the approximate size of all documents which are of same type t as the document i, L(i, j) is the local weight representing the popularity of the document i in AS j, and G(i) is the global weight representing the subscription level of the document i (more specifically, the subscription level of the content-provider hosting the document i) within the VCN. The value {overscore (s)}t is tuned by the VCN administrator while configuring the VCN at the setup time. This parameter is used mainly to differentiate between the different types of contents, like an HTML document or a movie document, such that sufficient storage space is allocated to a document in relation to other documents of the same type. - As mentioned earlier, all the CERs in the VCN create groups among themselves. The matrix A is computed and maintained by each group of CERs. Each server-side CER informs each of the CER groups about the new contents that are introduced to the VCN. The CER groups generate the matrix A, create the CECs and their corresponding tags. This method reduces the overall processing load for each of the CERs and distribute the load across the network. The namespace tree comprising the content-to-tag bindings are maintained by each of the CER groups. Moreover, at times of failure each CER group acts as a backup for other CER groups. [0102] - It should be noted that until now the relative weight (a[0103] ij) values were calculated on a per document basis. This becomes a computationally intensive process for a very large number of documents. Instead, we first create groups of documents and calculate the relative weights for each group. The CECs are composed of these groups of documents. This reduces the size of the matrix A and also improves the processing efficiency. For example, we can create a group of documents using the URL prefix. This URL prefix identifies a directory containing some number of documents. We consider all the documents in this directory as a single content entity during content classification. The sum of the sizes of each of the documents in the directory is the total size of the content entity and an average of the total popularity of all the documents in the directory for a particular AS represents the local weight for the content entity. - The invention introduces a pair of tunable parameters while creating the CECs: low (l[0104] b) and high (hb) bounds to limit the total amount storage space required for each CEC. The total storage space for a CEC is the sum of the storage spaces for each data objects in the CEC. Higher bound hb depicts the maximum amount of storage capacity that can be allocated to a CEC and lower bound lb depicts the minimum amount of storage resources that should be allocated for a CEC. The lb and hb values are chosen suitably by the VCN administrator at the time of VCN setup for proper functioning of the routing protocol. Surpassing hb may create a single CEC that contains all the documents hosted by the VCN. Instead, it is more efficient to create smaller content groups and distribute the groups across the VCN. This helps in (a) managing the available storage space at the surrogates more efficiently, (b) store the contents as per their popularity in different sections of the network, and (c) allow an even distribution of the client requests across the VCN. The replication algorithm, which is beyond the scope of this thesis, will use the CECs to create copies of the contents (i.e., all contents in a CEC are copied at the same surrogates). The number of copies for each CEC and their storage location will, however, be determined by the relative weight (i.e., aij) of the CEC. - In the second phase, the semantic attributes are used to identify the delivery requirements that are imposed at the time a client requests a content. The values of the semantic attributes are used to create the secondary tags. The primary and secondary tags are together used to tag a request packet. The semantic attibutes that are used in our scheme are (a) the QoS attribute and the (b) access attributes. The QoS attributes can be explicitly mentioned by a service level agreement like Diff-Serv. The intended usage of the requesting application are also included while creating the secondary tags. This is identified by the protocol number mentioned in the IP header of the request packets. When a client-side CER (ingress CER) receives a request packet, it will parse the packet to identify the content being requested and also identify any specific resource requirements that are explicitly mentioned in the packet. An examination of the TOS (type of service) field, also called DS (Diff-Serv)field, [14] reveals any per-hop behaviour (PHB) specified for the packet. In case no PHB is mentioned, the protocol field identifies the protocol being used by the requesting application. The ingress CER uses a pre-defined code to describe the protocol in the secondary tag. The invention uses a 8-bit long secondary tag to define a PHB or any other specific services being requested. [0105] - Content-Based Tags [0106] - Temporary Tags [0107] - Most of the information that are used for content classification and tag generation are obtained from the statistical analysis of the VCN traffic. The traffic analysis process is handled distributively by the CER groups in the VCN. This analysis will generate a detailed report on the usage and characteristics of content attributes. This is, however, a time consuming process and is repeated infrequently. As a result, when a new content is introduced to the VCN, it may not be assigned a tag based on its attributes immediately. This is mainly because no information will be available for the new content from the last traffic analysis. To cope with this problem, temporary tags are introduced. [0108] - Each group of CER will maintain a pool of free tags (i.e., tags with no content bindings). When a new content is introduced to a CER, it chooses a free tag maintained by its group of CERs and creates a new content-name to tag binding using the free tag. The tag chosen from the pool of free tags to create a new content to tag binding is called the temporary tag. More specifically, the primary portion of the tag will contain the temporary tag and the secondary tag will be created when a request for the content is submitted to the VCN. This content name to temporary tag binding is pushed to all the CER groups in the VCN. All client requests for the new content will be routed based on the temporary tag assigned to the content. Once a temporary tag is assigned to a new content, the VCN will start collecting traffic information for the new content. During the next cycle of content classification process a content-based tag will be assigned to the content with a temporary tag. The content-based tag is derived from the content's new attribute values. The temporary tag is returned to the free pool of tags. FIG. 6 shows the sequence in which the temporary and the content-based tags are generated and managed. The forwarding algorithm will always give priority to all contents with content-based tags over the contents with temporary tags. [0109] - Tag Format [0110] - As mentioned earlier, the content tags are created based on the values of the CEC attributes and have a primary and a secondary portion. The primary portion is created during phase-I of the CEC creation process by the server-side CERs. The secondary portion of the tag is created during phase-II by the client-side CERs. The primary portion is used to locate the content while the secondary portion is used for accessing the content. In effect, a combination of the primary and the secondary tag portions will be used to select a suitable path from the client to an appropriate hosting site. A 32-bit tag is attached as a content header to encapsulate the IP packets before pushing the packets into the VCN. The encapsulation is somewhat similar to that used by MPLS. Those links which cannot include the content header in the link layer header (e.g. Ethernet), the content header is carried in a shim header between the link and network layers (layer 2 and layer 3 of the OSI model). For links like ATM and Frame Relay, the content header can be carried inside the layer 2 (i.e., the link layer). The format of the content header is shown FIG. 7. [0111] - The 24-bit primary tag is the content-based name that is used to identify a content. The primary tag comprises of a 2-bit type field, 2-bit content format (CF) field, 12-bit size field and a 8-bit priority field. [0112] - The type field is used to distinguish between the different types of content that is being delivered. The FIG. 16 shows the different values for the type field. Streaming content identifies all audio/video data objects and non-streaming content refers to all text or application data and multimedia objects like images. Temporary field identifies that the tag assigned to the content is temporary. In case of a temporary tag, the CF, size and priority fields are replaced by the temporary tag. This means that the temporary tag can be of maximum 22 bits. The reserved field indicates future usage. [0113] - The 2-bit CF field will identify the end data type of the content. FIG. 17 gives a probable list of different end data types as defined by [18]. The list shows an example of how end data types can be specified for different types of content. This list can be altered, by adding or removing any end data types, by the discretion of the VCN administrator. [0114] - The size field represents the size of the CEC in the VCN. It is obtained by mapping the CECs onto divisions representing different sizes. Each division represents a range of document sizes in bytes and is identified by a 12-bit number i.e., we define 2[0115] 12 or 4096 divisions and each division defines a range of bytes. The CECs are mapped to one of the divisions based on the CEC size which is the average size of all the documents in the CEC. - The priority field represents the popularity of a CEC in the VCN. The CEC popularity is given by the average popularity of all the documents in the CEC. Similar to the size field, the priority field is also represented by a set of divisions (2[0116] 8 or 64 divisions) with each division identifying a range of values. - The secondary tag consists of the 8-bit CoS (class of service) field. This will indicate the intended usage of the content or the service level agreement policies e.g., Diff-Serv. The intended usage is identified by the protocol number of the requesting application. A pre-defined list managed by the VCN administrator will provide a CoS field value for the different protocol numbers. The Diff-Serv class of services mentions the differentiated services that is to be provided to the client request. The CoS value identifying intended usage is always greater than the 6-bit codepoint value (codepoint identifies the standardized per hop behaviors in Diff-Serv). [0117] - As mentioned earlier, all the CERs will create groups among themselves to hold the entire namespace for all the documents hosted by the VCN. We represent the namespace in form of a tree. FIG. 8 shows such a tree. The leaves of the tree hold the primary portions of the content-derived tags and the higher levels of the tree holds some part of the URLs to identify the documents. A client-side CER, upon receiving a request will parse the request to identify the document requested. It will then walk down the namespace tree to identify the tag assigned to the document. Once, the primary tag is identified the CER will generate the secondary tag for the request. Once the whole tag is generated the routing process is initiated. [0118] - Modes of Operation [0119] - The invention describes various operating modes for PICS. Before presenting the different modes, the fundamental differences between the existing routing approaches and PICS approach are examined. [0120] - A content accessing scheme should optimally implement the following two major functions to ensure efficient usage of the resources and to enhance the content delivery performance to the client. [0121] - Server selection: selects the site and the server within the site that serves the requested content. [0122] - Path selection: selects the path along which the selected server delivers the content to the clients. [0123] - Most of the existing content accessing approaches proceed in two phases: (a) resolution of a location-based name to obtain an IP address that specifies the destination host and (b) access the content from the destination host using the IP address. This process is illustrated in figure FIG. 9([0124] a). In the current Internet, the server selection is exclusively handled by the name resolution phase. The path selection is performed in the second phase and is determined by the traditional Internet routing protocols such as Open Shortest Path First (OSPF) [12] and Routing Information Protocol (RIP) [10]. In case QoS constraints should be met by the selected path, we can use Resource Reservation Setup Protocol (RSVP) [22] or Differentiated Services (Diff-Serv) [20]. - Recently, several content-based name resolution schemes have been proposed. These schemes differ from traditional name resolvers such as Domain Name Server (DNS) [19] in that they use a highly distributed “flat” resolver network. The request for resolution is routed through the flat resolver network using the content that is being requested. One of the advantages of this approach is that the name resolution may take into consideration fast varying parameters such as server load. The dissemination of such parameters may be localized to the nearby name resolvers. [0125] - Another alternative is to unify the server and path selection processes. The PICS scheme proposed here splits the name resolution into two phases. In the first phase, a content-based identifier (typically a location-based name but can be any other set of content attributes) is resolved to a fixed format tag. In the second phase, the tag is further resolved using a highly distributed “flat” routing network to reach the eventual server for the content. Depending on which mode of PICS operation is selected, the path for delivering the content back to the client is also selected by this process. This process is illustrated in FIG. 9([0126] b). - Below two different modes of PICS operations are described. The first mode is referred to as the Route Push Method (RPM). In this method, the content-based routes are pushed from the server-side CERs, which are the eventual destinations of any request, towards the client-side CERs. The second mode is referred to as the Route Push and Pull Method (RPPM). In this method, the content-based routes are disseminated by a combination of push and pull-based schemes. In both the methods, we assume that the reverse flow that carries the data from the server to the client follows the same path that was traversed by the request. [0127] - Route Push Method [0128] - As mentioned previously, the VCN consists of CERs at its edge and CSRs at its core. The VCN can be considered as a highly distributed content router where the request for content enters the VCN via a client-side CER and is routed by the CSR network towards a server-side CER that can lead to the server with “best” performance. The server-side CER then delivers the request to the best server. [0129] - In this method, the server-side CERs receive advertisements from the hosting servers that are connected to them. The advertisements may contain some characterization of the content hosted at the servers (typically a content name) and utilization of the servers. The server-side CERs use a “tagging function” (content classifier) that takes the advertisements as arguments to derive content-based tags. [0130] - The tagging function may be implemented at the server-side CER as a tree-walking process that uses a namespace tree to bind a content-name to a tag. The binding process may use information from the content characterization schemes as explained in the next section. Once a server-side CER binds a content-name to a tag, two processes should take place: (a) dissemination of the tag and the corresponding content “serving” performance at the CER into the VCN, and (b) dissemination of the tag and content-name bindings to other CERs so that they could reuse the tags. [0131] - The tags formed by the server-side CERs are used to form a content-based route entry containing the (a) content tag and (b) effective server utilization index at the CSRs within the VCN. [0132] - The tag dissemination is done in a “feed-forward” manner along a tree like structure with a server side CER initiating the distribution and acting as the root of the tree, the CSRs form the intermediate layers of the tree and the client side CERs form the leaves of the tree. Multiple Tag Distribution Trees (TDTs) may be formed in this way and may have common CSRs at different levels for the different trees. The advantage of such a scheme is that almost all the information available at the input layer, comprising of different server side CERs, will be available at the output layer, comprising client side CERs, and also provide multiple paths for each tag disseminated through the VCN. Routing table at each content router holds the content tags, the next hops for the tags and a route factor. Since there can be multiple paths for each tag, the route factor reflects the condition of each path. [0133] - FIG. 10 shows two TDTs with CER-A as the root of TDT[0134] 1 and CER-B as the root of TDT2. CSR-1 is at the first level with respect to TDT1 and at the second level with respect to TDT2. CER-1 and CER-2 form the leaf nodes of the two TDTs. Loop prevention algorithms are used to detect and prevent any loops among the content routers due to the tag-based routing. When a client request arrives at a client side CER (CER-A), a content tag that is derived from the content name is bound to the request. The CER-A examines its content-based routing table to obtain a possible next hop. A “route factor” associated with the next hops is used to select the best performing next hop. Once a request is pushed into the VCN, it is routed towards the destination (server-side CER) by the CSRs using the content tag, i.e., the content name or any other information is not examined by the CSRs. - The server side CER forwards the request towards the best performing hosting server. Due to route propagation delays, the request routing will be based on progressively accurate information, i.e., as the request nears the destination it will be routed using more current information. [0135] - The data from the server is delivered to the client along the path that was traversed by the request. The route factors that were used to choose the next hops when the request was steered through the VCN are dependent on the network status and capacity as well. By computing the route factors appropriately, it may be possible to give probabilistic network QoS to the requests. FIG. 11 illustrates the request steering and data forwarding in an example VCN. The client request initiates from CER-[0136] 1 and flows through the VCN to the CER-A. The return path is the same as the forward path and it is used to deliver the content to the client. - The CERs may be grouped together such that a group maintains a single namespace tree. In each group, a CER holds a portion of the tree and maintains a pointer to the CER in the group that maintains the remaining portion of the tree. It should be noted that the group of CERs maintain a single namespace tree. Therefore, when a request reaches a CER it uses the appropriate CER within the group to resolve the content name to the tag and then injects the tagged request into the VCN. [0137] - Route Push and Pull Method [0138] - In the RPM, once a content-name to tag binding is created, it is pushed to all CER groups. Therefore, a group of CERs is supposed to know about a content-name to tag binding if the content with the given content-name is managed by the VCN. This approach may not be scalable unless the VCN is restricted to manage a reasonably small number of different contents. In this case it may be best to choose the most popular set of content to be managed by the VCN. [0139] - The RPPM, on the other hand, provides a flexible scheme that enables the VCN to handle much larger numbers of content-name to tag bindings. In this method, the CER groups are organized into a virtual hierarchy as shown in FIG. 12. The leaves of the hierarchy have physical CERs and the interior nodes of the hierarchy have virtual CERs (VCERs). A VCER may be implemented using one physical CER or a group of physical CERs. [0140] - The CERs examine the content requests that pass through them. With a virtual hierarchy such as the one presented above, it is possible to perform different types of traffic analysis. This analysis could be used to determine several traffic characteristics including (a) surges in demand, (b) relative demand of the different content, and (c) security violations and intrusions. [0141] - With the statistical information obtained through traffic analysis, we can determine the relative popularity of the various content handled by the VCN. This information is used to map the content-name to tag binding information onto the virtual hierarchy. The idea is to map the content-name to tag bindings for the highly popular content onto the physical CERs. More precisely, each group of inter-operating CERs should know about all the content in the “popular” set. Therefore, for a content in the popular set, there will be a maximum of one “miss” while resolving the content-name to a tag. The miss could happen at the ingress CER. In case of a miss at the ingress CER, a “hit” is certain, for popular content, at the next CER pointed by the namespace tree at the ingress CER. We refer to this timely processing of popular content as “fast mode” processing. [0142] - The less popular content are mapped onto the VCERs such that the least popular ones are mapped only at the root of the hierarchy. When a request for a less popular content (managed by a VCER) arrives at a CER, it will miss at the ingress CER and at the group level. The virtual hierarchy will be traversed to find the content-name to tag binding for this content. The resolution time increases as the content-name to tag binding information is held further up in the VCER tree. This is referred to as the “slow mode” processing. As the popularity of a content increases, the RPPM “pulls” the content-name to tag binding information down the hierarchy, thus decreasing the resolution time for subsequent accesses for the particular content. [0143] - The pulling of the content-name to tag binding information down the VCER tree creates only temporary copies of the binding information. When the surge in popularity subsides, the copies are deleted. Therefore, pulling the binding information down the hierarchy effectively moves the content processing from slow to fast mode. As the popularity for a document decreases, the content processing returns to the slow mode. [0144] - Initially, a content to temporary tag binding will be maintained at the lowest level of the VCER tree. Once the VCER tree starts receiving traffic analysis reports about the demand for the contents with temporary tags, the temporary tags will be pushed up or pulled down according to the demand across the different hierarchies on the VCER tree. [0145] - PICS Forwarding Algorithm [0146] - The forwarding algorithm used by the routing components of the VCN is based on the content-based tag and the routing fractions generated by the VCN. A routing fraction (RF) refers to the load status of a path between any two routing components (e.g., CSR and CER). A content hosting server site (S) will frequently update it's neighbor CER(s) with a RF that indicates the server's most current load status. The receiving CER will include the load status of the CSP, along which it received the status update, to the RF value received from the server site. The CER will then distribute the updated RF value to its neighbor CSR(s) and CER(s). This way, the RF value received at a client-side CER will indicate the condition of an entire path (i.e., sequence of CSPs) from the server S to itself. Each of the content hosting sites in the VCN will generate such a status update packet. Each of the CSR/CER(s) will maintain an RF table to store the RF values received from all its neighbors. The RF table will be updated very frequently. FIG. 13 illustrates the PICS forwarding process. [0147] - Each CSR and CER (specifically CER groups) will also maintain a routing table, where each entry contains a tag component and a probable next hop for the tag. The next hop will be a neighbor CER or a CSR, or a content hosting server. The forwarding algorithm which uses the RF values for the neighbors to make routing decision works as follows. When an ingress CER receives a request packet, it will encapsulate the request packet with an appropriate tag obtained from a VCER tree. The ingress CER will use its routing table to find the possible next hops for the tag used to encapsulate the request packet. It will choose the next hop with the best RF value and forward the encapsulated packet to that next hop. A CSR on receiving an encapsulated packet will extract the tag from the encapsulated packet and use it as an index to select the possible next hops from the routing table. Again, next hop with the best RF value is chosen and the CSR will forward the encapsulated packet to the next hop. An egress CER will receive an encapsulated packet, extract the tag and find the best next hop from the routing tables. If the next hop selected is a content hosting site, the encapsulation (i.e., the tag) is stripped off and the original packet is forwarded to the server. If the next hop is a CER or CSR, the encapsulated packet is forwarded to the next hop. A combination of the primary tag and secondary tag will identify the resource requirements of the requested content. The RF value from the RF table at a router will identify whether enough resources are available for delivery of the content along a CSP. [0148] Claims (15) 1. A method for directing packets of data based on their content in a telecommunications network, wherein the physical network comprises a plurality of clients, a plurality of servers for supplying content and a plurality of content aware routers for directing communications over the network; wherein content represents the payload carried in the packets; the method comprising: providing a content intelligent overlay network that is a Virtual Content Network (VCN) created on top of the physical network; wherein the overlay network and a digest of the content is used to select a preferred path for the packets and the physical network layer is used to transfer the packets from one end to other end of the path; wherein the Virtual Content Network (VCN), acts as a distributed virtual content router and is transparent to the users; wherein the VCN is sparser than the underlying physical network and is formed by content edge routers (CERs) placed at the edge and the content switching routers (CSRs) in the core of the VCN; and wherein the CERs and CSRs are connected using logical content switching paths (CSP). 2. The method according to claim 1 including a method in which all contents hosted by the VCN with similar characteristics are grouped together to create sets referred to as Content-Equivalence Class (CEC) in which the CECs allow handling of large volumes of data by creating content aggregates; wherein the method comprises the steps: (a) identification and describing content attributes where the attributes are classified as structural and semantical attributes of the contents and the attributes are used to characterize and classify the contents hosted by the VCN and create the CECs for these contents and where all CECs are unique within the VCN i.e. each CEC will have a unique set of attribute values; (b) implementing a tagging function to create a fixed sized content-derived tag that is used to identify each CEC where the tag is derived based on the attribute values of each CEC and each tag is unique within the VCN and is used to route packets within the VCN; and (c) disseminating the tags within the VCN either at periodic intervals or on-demand. 3. The method according to claim 2 wherein each content-derived tag actually corresponds to a finger-print for the content that is requested by the packet and represents a single or a set of servers that hosts the content; the destination of a packet (or a flow) is chosen from this set of servers during routing. 4. The method according to claim 2 including encapsulation of request packets using the content derived tags by attaching the content derived tag as a content header to the request packets, where the encapsulated packets are then pushed into the VCN and the tag in the content header is used to route the packets. 5. The method according to claim 2 including replacement of the normal IP routing table with the content-derived tag routing table at the content routers within the VCN where each content router within the VCN maintains routing tables to hold the content derived tags for content being hosted by the VCN. 6. The method according to claim 2 including calculating the routing fractions from the load condition of the hosting servers and the condition of the path leading to the servers from any point in the VCN where the tag routing tables will contain the tags and the routing fractions, where the tags are used to select a set of servers and the routing fraction is used to find the best path to the best server and where a routing algorithm uses the tags to identify the requests and route the packets towards the ‘best’ destination. 7. The method according to claim 2 wherein contents are classified using attributes which allow access to portions of a content hosting site at variable granularities i.e. it is possible to partition/replicate content hosting sites using different attribute values of the content hosted by the sites and no longer requires simplistic information like the domain or locational information of the site for partitioning or replication. 8. The method according to claim 2 wherein request packets are tagged using content derived tags so as to eliminate the round-trip time involved for resolving (i.e., mapping) a request on to a specific server and so that the latency for content discovery is reduced. 9. The method according to claim 2 wherein the routing decision by the CSRs within the VCN core use the content-derived tags so as to eliminate the time required to parse the request packet repeatedly at each CSR along the routing path to make a routing decision. 10. The method according claim 2 wherein the CECs and the content-derived tags are created by the CERs prior to the routing process by the steps; (a) content characterization wherein identification of the structural and semantical attributes of content; (b) content classification wherein the content attributes are used to classify content and create the CECs for each autonomous system (AS) in the Internet. 11. The method according to claim 2 including a routing algorithm called Protocol Independent Content Switching (PICS) that uses the content-derived tags to route packets; wherein the methods of operation of PICS include: (a) a route push method wherein the content-based routes i.e., the tags are pushed from the server side CERs to all the client-side CERs wherein all CERs and CSRs know about all the tags maintained by the VCN; (b) a route push and pull method wherein the content-based routes are disseminated and maintained in a distributive manner in the VCN by using a virtual content edge router (VCER). 12. The method according to claim 2 wherein the tags within the VCN are maintained in a distributive manner by using the content edge router VCER, where (a) the virtual content edge router consists of physical CERs placed in a tree-like fashion; (b) the lowest level of CERs of the VCER tree maintain tags for the most popular contents, the topmost level maintain tags for the least popular contents while the intermediate VCER levels handle contents of intermediate popularity. 13. The method according to claim 2 wherein the popularity of the contents is changed dynamically by: (a) the VCER tree is used to define a fast and slow mode of routing. (b) in the fast mode tags for all most popular contents are stored at the lowest level of the tree and in the slow mode, all less popular contents are stored in the higher levels of the tree. (c) the tags are pulled down or pushed up the tree as the popularity of the contents change. 14. The method according to claim 2 wherein the selection of the route is facilitated by: (a) obtaining information about the contents hosted by sites who wish to use the VCN for content delivery (i.e., content providers subscribe to the VCN); (b) performing analysis of the Internet traffic for these contents; (c) maintaining the content and corresponding tag information at the edge of the VCN. 15. The method according to claim 4 wherein the content header is used to encapsulate the data packets so as to include the content storage and resource requirements in the content-derived tags in a digest form and this information is used by the CERs and CSRs to make routing decisions. Priority Applications (2) Applications Claiming Priority (1) Publications (2) Family ID=23294064 Family Applications (1) Country Status (2) Cited By (200) Families Citing this family (23) Citations (16) - 2002 - 2002-11-14 CA CA 2411806 patent/CA2411806A1/en not_active Abandoned - 2002-11-15 US US10/295,036 patent/US7339937B2/en not_active Expired - Fee Related
https://patents.google.com/patent/US20030099237A1/en
CC-MAIN-2019-43
refinedweb
13,762
51.38
. 1. SKiDL pip install skidl License: MIT Dave Vandenbout‘s tool creates schematics entirely in text. Or more correctly, describes them as a netlist file. Using Python objects, you instantiate components, connect the pins, and (optionally) check for errors. At first, this method might seem somewhat limiting. For simple schematics that get turned into a PCB, SKiDL enables a shortcut. There are some seemingly intricate designs which are merely connecting multiple ASICs. In that case, is a graphical schematic necessary? Regardless of which use model fits you, having SKiDL in your back pocket of electronics Python tricks seems like a good idea. 2. PySpice pip install pyspice License: GPLv3(*) (License covers the PySpice Module, but not the underlying engine you pick.) Need to simulate a circuit or part of one? There are plenty of simulation options available. You could use the Falsted Simulator, LTSpice, KiCad, ngspice, Quacs, or xyce. And yet, even with those, there is another option: PySpice. PySpice provides the interface to circuit simulators like Ngspice or Xyce. PySpice is more than just a ngspice wrapper. Although, you could treat it as such. Before using this electronics Python module, you need to have an understanding of SPICE and how the engine you pick works. 3. Pint makes Units Easy pip install pint License: BSD If you’re doing engineering math, keeping track of units can be cumbersome. While not specific to electronics, Pint is one of the best Python engineering modules. It simplifies manipulating physical quantities. Many of the examples are around other physics disciplines. Pint handles electronics quantities just fine. Here’s an example calculating with Ohm’s law. from pint import UnitRegistry ureg = UnitRegistry() # Ohm's law example resistance = 5.0 * ureg.ohm current = 2.5 * ureg.milliampere voltage = (resistance * current).to('volt') # default unit print(voltage.to('volt')) # easier to read print(voltage.to('millivolt')) # result: # 0.0125 volt #12.5 millivolt As the example shows, Pint is more than an engineering notation handler. The parser does need some help when doing calculations with different units. As you can see in the Ohm’s Law example, I need to tell it my result is in volts. However, it is a small price to pay to make handling prefixes straightforward and readable. 4. NumPy pip install numpy License: BSD import numpy as np a = np.arange(15).reshape(3, 5) print (a) The example I used for Pint is simple algebra. When you need to work with linear algebra, Fourier transforms, and array objects, it is time to install NumPy. Recently I did some work with the Zynq development board. Like most computer vision examples, all of the Zynq’s relied on NumPy. The about-page for NumPy says it can store generic data in a multi-dimensional container, like a database. Long story short, if you’re doing anything above basic math, you need to consider using NumPy. Also, Pint works just fine with NumPy objects! Even though I wanted to focus on Python engineering modules, I did want to point out this page. It has 10 additional modules expanding beyond NumPy. So if you’re doing anything science or engineering related, you may want to consider some of these modules. And since most math needs plotting, you need to check out the next electronics Python module. 5. Matplotlib – Graph Plotting pip install matplotlib License: PSF Engineering and plotting go hand-in-hand. Matplotlib provides extensive visualization capabilities to any math or engineering based Python program. If you’re familiar with MatLab, you’ll be at home with Matplotlib. An additional benefit is that it is tied tightly into Juypter Notebook, for easy documentation Here is a sine wave example. import numpy as np import matplotlib.pyplot as plot # Get x values of the sine wave time = np.arange(0,10,0.1) amplitude = np.sin(time) plot.plot(time, amplitude) # text labels plot.title('Sine wave') plot.xlabel('Time') plot.ylabel('Amplitude = sin(time)') # Generate the grid/axes plot.grid(True, which='both') # Generate the actual data plot plot.axhline(y=0, color='k') # Display plot plot.show() 6. Jupyter Notebook pip install jupyter License: Modified BSD Okay, this last one is not “just” a module. Jupyternotebook (or Juypter if you mispell it like I do) is a fantastic engineering notebook tool. Here is the shortest way I can describe it: Google Docs + Python. Jupyter runs a local web service on your machine. It creates notebook pages that combine rich-text, python code, and binary objects. In a single in-line page, you can write some instructions on how to perform a test, the code used to test it, and have the results. Even better, libraries like matplotlib integrate with Jupyter. Oh, if it wasn’t clear before, you can execute Python code inline. Before, I mentioned a notebook page could contain a Python code block. Clicking on that block and hitting shift-enter causes the code to execute. For an example of how this amazing tool works, check out the Pynq video review I made. I briefly show how it works there. Later, I plan to come back and do some more in-depth coverage on Jupyter. In the meantime, I have been experimenting with using it to replace, or at least augment, Evernote. At this point, I like the idea of taking raw notes in Jupyter and then exporting the “final” version to Evernote. To keep my notebooks in sync, I keep the data files in a Dropbox folder. If you install Jupyter, you can download and use this notebook file. It contains the Ohm’s Law example from the Pint section above. Just keep in mind, you’ll need to have Python and Pint installed for the shift-enter trick to work. 7. and 8. Twitter Mentions for Python Engineering Modules Last, but not least, I wanted to mention two tools mentioned by Twitter followers. Both of these are modules I heard about from other people. However, I have not spent much time experimenting with them yet. I am including them because I trust who sent them to me. PCBmodE from @BoldPort PCBmodE uses Inkscape as its drawing GUI to create PCBs. If you have ever seen any of BoldPort’s beautiful projects, you have seen the output of PCBmodE. I2cdesvice from @Gadgetoid If you’re developing I2C devices, i2cdevice may help to keep track of the register addresses. It isn’t intended to be a tool used with production I2C code. Instead, it is a development tool to help develop production code. Conclusion When I started putting this list together, I had three electronics python modules in mind. As I started diving into all of the modules I learned about over the past year, the list more than doubled. I suspect that I might have missed a few key engineering Python modules. If so, let us all know what you recommend installing in the comments below. Long comments, URLs, and code tend to get flagged for spam moderation. No need to resubmit. ALL comments submitted with fake or throw-away services are deleted, regardless of content. Don't be a dweeb.
https://www.baldengineer.com/7-python-engineering-modules.html
CC-MAIN-2021-17
refinedweb
1,191
67.86
signal - signal management Synopsis Description Return Value Errors Examples Application Usage Rationale Future Directions See Also #include <signal.h> void (*signal(int sig, void (*func)(int)))(int); Use of this function is unspecified in a multi-threaded process. The signal() function chooses one of three ways in which receipt of the signal number sig is to be subsequently handled. If the value of func is SIG_DFL, default handling for that signal shall occur. If the value of func is SIG_IGN, the signal shall be ignored. Otherwise, the application shall ensure that func points a: signal(sig, SIG_DFL);. If the signal occurs as the result of calling the abort(), raise(), kill(), pthread_kill(), or sigqueue() function, the signal handler shall not call the raise() function. standard library other than one of the functions listed in Signal Concepts . Furthermore, if such a call fails, the value of errno is unspecified. At program start-up, the equivalent of: signal(sig, SIG_IGN); is executed for some signals, and the equivalent of: signal(sig, SIG_DFL); is executed for all other signals (see exec). If the request can be honored, signal() shall return the value of func for the most recent call to signal() for the specified signal sig. Otherwise, SIG_ERR shall be returned and a positive value shall be stored in errno. The signal() function shall fail if:The following sections are informative. None. The sigaction() function provides a more comprehensive and reliable mechanism for controlling signals; new applications should use sigaction() rather than signal(). None. None. Signal Concepts , exec() , pause() , sigaction() , sigsuspend() , wait .
http://www.squarebox.co.uk/cgi-squarebox/manServer/usr/share/man/man3p/signal.3p
crawl-003
refinedweb
258
54.73