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
Welcome to the DNN Community Forums, your preferred source of online community support for all things related to DNN.In order to participate you must be a registered DNNizen I have an ASP.NET website, when I deployed it on my machine, it's giving me an error saying: "CS0246: The type or namespace name 'DotNetNuke' could not be found (are you missing a using directive or an assembly reference!?)". can someone please help me resolve this error. Quick response would be appreciated. DNN Digest is our monthly email newsletter. It highlights news and content from around the DNN ecosystem, such as new modules and themes, messages from leadership, blog posts and notable tweets. Keep your finger on the pulse of the ecosystem by subscribing.
http://www.dnnsoftware.com/forums/threadid/532068/scope/posts/the-type-namespace-could-not-be-found-are-you-missing-a-using-directive-or-an-assembly-reference-
CC-MAIN-2018-22
refinedweb
125
64.41
A cycle in a directed graph exists if there's a back edge discovered during a DFS. A back edge is an edge from a node to itself or one of the ancestors in a DFS tree. For a disconnected graph, we get a DFS forest, so you have to iterate through all vertices in the graph to find disjoint DFS trees. C++ implementation: #include <iostream> #include <list> using namespace std; #define NUM_V 4 bool helper(list<int> *graph, int u, bool* visited, bool* recStack) { visited[u]=true; recStack[u]=true; list<int>::iterator i; for(i = graph[u].begin();i!=graph[u].end();++i) { if(recStack[*i]) //if vertice v is found in recursion stack of this DFS traversal return true; else if(*i==u) //if there's an edge from the vertex to itself return true; else if(!visited[*i]) { if(helper(graph, *i, visited, recStack)) return true; } } recStack[u]=false; return false; } /* /The wrapper function calls helper function on each vertices which have not been visited. Helper function returns true if it detects a back edge in the subgraph(tree) or false. */ bool isCyclic(list<int> *graph, int V) { bool visited[V]; //array to track vertices already visited bool recStack[V]; //array to track vertices in recursion stack of the traversal. for(int i = 0;i<V;i++) visited[i]=false, recStack[i]=false; //initialize all vertices as not visited and not recursed for(int u = 0; u < V; u++) //Iteratively checks if every vertices have been visited { if(visited[u]==false) { if(helper(graph, u, visited, recStack)) //checks if the DFS tree from the vertex contains a cycle return true; } } return false; } /* Driver function */ int main() { list<int>* graph = new list<int>[NUM_V]; graph[0].push_back(1); graph[0].push_back(2); graph[1].push_back(2); graph[2].push_back(0); graph[2].push_back(3); graph[3].push_back(3); bool res = isCyclic(graph, NUM_V); cout<<res<<endl; } Result: As shown below, there are three back edges in the graph. One between vertex 0 and 2; between vertice 0, 1, and 2; and vertex 3. Time complexity of search is O(V+E) where V is the number of vertices and E is the number of edges.
https://riptutorial.com/algorithm/example/22140/detecting-a-cycle-in-a-directed-graph-using-depth-first-traversal
CC-MAIN-2021-39
refinedweb
368
54.97
- 20 Seconds - 8 Seconds - 5.93 Seconds - 5.09 Seconds - 4.23 Seconds - 2.94 Seconds - 1.57 Seconds - Results - Other Things To Try - References Contents How I Made My Ruby Project 10x Faster This post is about how I got a 10x speedup for my ruby gem contracts.ruby. contracts.ruby is my project to add code contracts to Ruby. Here's what it looks like: Contract Num, Num => Num def add(a, b) a + b end Now, whenever add is called, the parameters and return value will get checked. Cool! 20 seconds This weekend I benchmarked this library and found that it has abysmal performance: user system total real testing add 0.510000 0.000000 0.510000 ( 0.509791) testing contracts add 20.630000 0.040000 20.670000 ( 20.726758) This is after running both functions 1,000,000 times on random input. So adding contracts on a function results in a massive (40x) slowdown. I dug into why. 8 seconds I got a big win right away. When a contract passes, I call a function called success_callback. The function is completely empty. Here's the full definition: def self.success_callback(data) end That's something I had put in "just in case" (yay futureproofing!). Turns out, function calls are very expensive in Ruby. Just removing this call saved me 8 seconds! user system total real testing add 0.520000 0.000000 0.520000 ( 0.517302) testing contracts add 12.120000 0.010000 12.130000 ( 12.140564) Removing a lot of other extraneous function calls took me to 9.84 -> 9.59 -> 8.01 seconds. This library is already more than twice as fast! Now things get a little more complex. 5.93 seconds There are multiple ways to define a contract: lambdas, classes, plain ol' values, etc. I had a big case statement that checked to see what kind of contract it was. Based on the type of contract, I would do different things. I saved some time by changing this to an if statement, but I was still spending unnecessary time going through this decision tree every time the function was called: if contract.is_a?(Class) # check arg elsif contract.is_a?(Hash) # check arg ... I changed this to go through the tree once, when the contract is defined, and build lambdas: if contract.is_a?(Class) lambda { |arg| # check arg } elsif contract.is_a?(Hash) lambda { |arg| # check arg } ... Then I would validate an argument by passing it into this pre-calculated lambda, bypassing the branching logic completely. This saved me another 1.2 seconds. user system total real testing add 0.510000 0.000000 0.510000 ( 0.516848) testing contracts add 6.780000 0.000000 6.780000 ( 6.785446) Pre-computing some other if statements saved me almost another second: user system total real testing add 0.510000 0.000000 0.510000 ( 0.516527) testing contracts add 5.930000 0.000000 5.930000 ( 5.933225) 5.09 seconds Switching out .times for .zip saved me almost another second: user system total real testing add 0.510000 0.000000 0.510000 ( 0.507554) testing contracts add 5.090000 0.010000 5.100000 ( 5.099530) Turns out, args.zip(contracts).each do |arg, contract| is slower than args.each_with_index do |arg, i| which is slower than args.size.times do |i| .zip spends unnecessary time copying and creating a new array. And I think .each_with_index is slower because it just yields to .each in the background, so it involves two yields instead of one. 4.23 seconds Now we're getting into some nitty-gritty stuff. The way the contracts library works is, for every method, a new method is added using class_eval (classeval is faster than definemethod). This new method contains a reference to the old method. When the new method is called, it checks the arguments, then calls the old method with the arguments, then checks the return value, and then returns the return value. All of this happens with two method calls to the Contract class: check_args and check_result. I eliminated these two method calls and did the checks right in the new method instead. This got me another .9 seconds: user system total real testing add 0.530000 0.000000 0.530000 ( 0.523503) testing contracts add 4.230000 0.000000 4.230000 ( 4.244071) 2.94 seconds Earlier I had explained how I was creating lambdas based on the type of Contract and then using those to check arguments. I switched this out to generate code instead, which would then get eval'd when I used class_eval to create my new method. An awful hack! But it avoided a bunch of method calls and saved me another 1.25 seconds: user system total real testing add 0.520000 0.000000 0.520000 ( 0.519425) testing contracts add 2.940000 0.000000 2.940000 ( 2.942372) 1.57 seconds Finally, I changed how I called overridden method. My earlier approach was using a reference: # simplification old_method = method(name) class_eval %{ def #{name}(*args) old_method.bind(self).call(*args) end } I changed it to use alias_method: alias_method :"original_#{name}", name class_eval %{ def #{name}(*args) self.send(:"original_#{name}", *args) end } This bought me a crazy 1.4 seconds. I have no idea why alias_method is so fast...I'm guessing because it skips a method call as well a call to .bind. user system total real testing add 0.520000 0.000000 0.520000 ( 0.518431) testing contracts add 1.570000 0.000000 1.570000 ( 1.568863) Results We managed to get from 20 seconds to 1.5 seconds! Is it possible to do better than this? I don't think so. I wrote this test script that shows that a wrapped add method will be 3x as slow as a regular add method, so these numbers are really good. But it's only 3x as slow because the method is so simple that more time is spent in calling the method. Here's a more realistic example: a function that reads a file 100,000 times: user system total real testing read 1.200000 1.330000 2.530000 ( 2.521314) testing contracts read 1.530000 1.370000 2.900000 ( 2.903721) Very little slowdown! And I think most functions will see very little slowdown...the add function is an outlier. I decided not to use alias_method because it pollutes the namespace and those aliased functions would show up everywhere (documentation, auto-complete for IDEs, etc). Some takeaways: - Method calls are very slow in Ruby! I enjoy making my code very modular and reusable, but it might be time for me to start inlining more code. - Benchmark your code! Removing a simple unused method took me from 20 seconds to 12 seconds. Other things to try Method combinators One feature that didn't make it into Ruby 2.0 was method combinators, which would have allowed you to write class Foo def bar:before # will always run before bar, when bar is called end def bar:after # will always run after bar, when bar is called # may or may not be able to access and/or change bar's return value end end This would've made it easier to write decorators, and might have been faster too. keyword old Another feature that didn't make it into Ruby 2.0, that would have allowed you to reference an overwritten method: class Foo def bar 'Hello' end end class Foo def bar old + ' World' end end Foo.new.bar # => 'Hello World' redefining a method with redef This one got rejected by Matz who said: To eliminate alias_method_chain, we introduced Module#prepend. There's no chance to add redundant feature in the language. So if redef is a redundant feature, maybe prepend could be used to write a decorator? Other implementations So far, all of this has been tested on YARV. Maybe Rubinius would allow me to optimize more? References - 6 Optimization Tips for Ruby MRI When monkey patching a method, can you call the overridden method from the new implementation? If you are already using contracts.ruby, upgrade to v 0.2.1to see the speedup.
http://adit.io/posts/2013-03-04-How-I-Made-My-Ruby-Project-10x-Faster.html
CC-MAIN-2017-51
refinedweb
1,359
76.42
Every morning I have to copy yesterday’s file, paste it as today’s file, refresh a PowerQuery via a macro and save the file with today’s date. I’m beginning to learn Python and I have found a way to copy and paste the file with today’s date. Because I want it to run with no actual file name constraints, I want the code to be able to select the most recently modified file, which would be always be yesterday’s file, copy it with today’s date in the file name, refresh the PowerQuery and run the macro. My code so far is a simple copy paste of the folders but I’d like to insert functions to have: import shutil original = r"C:UsersnameDesktop9.13.2021 - Daily Item Record.xlsm" target = r"C:UsersnameDesktop9.14.2021 - Daily Item Record.xlsm" shutil.copyfile(original, target) The above involves changing the dates every day. Instead, I’d like to have the original file path be the most recent file in the directory and the target file be the copy with today’s date. Answer This should work: import os import shutil import time my_dir = "C:\Users\nameDesktop\" # A dictionary for storing the files files_dict = {} # Put the creation time and the path for each file in the directory into files_dict for f in os.listdir(my_dir): file = my_dir + f file_createdtime = os.path.getctime(file) files_dict[file_createdtime] = file # Get the most recently created file most_recent_file = files_dict[max(files_dict)] # Copy and rename the file shutil.copy(file, os.path.dirname(file) + time.strftime("\%m.%d.%Y - Daily Item Record.xlsm")) In the for loop, I create a dictionary of each file’s creation time and path. The max() function returns the highest value in an iterable sequence (in this case, the dictionary). In the code below, it returns the creation date for the most recently created file, which I can use to get the file path from the dictionary and put it in most_recent_file. In the last line, I copy the file with a new name in the format 09.13.2021 - Daily Item Record.xlsm using the time.strftime() function. See the python documentation for more information on time.strftime. Basically what it does is replace certain patterns in the given string with certain units of time. Here, it replaces "%m" with the current month number, "%d" with the current day of the month, and "%Y" with the current year. If you have any questions or something wasn’t right, let me know!
https://www.tutorialguruji.com/python/python-copy-most-recent-file-in-folder-with-todays-date-and-execute-macro-found-in-file-closed/
CC-MAIN-2021-43
refinedweb
424
71.85
Templates are the entry point for the CubicWeb view system. As seen in Discovering possible views, there are two kinds of views: the templatable and non-templatable. Non-templatable views are standalone. They are responsible for all the details such as setting a proper content type (or mime type), the proper document headers, namespaces, etc. Examples are pure xml views such as RSS or Semantic Web views (SIOC, DOAP, FOAF, Linked Data, etc.), and views which generate binary files (pdf, excel files, etc.) To notice that a view is not templatable, you just have to set the view’s class attribute templatable to False. In this case, it should set the content_type class attribute to the correct MIME type. By default, it is text/xhtml. Additionally, if your view generate a binary file, you have to set the view’s class attribute binary to True too. Templatable views are not concerned with such pesky details. They leave it to the template. Conversely, the template’s main job is to: Look at cubicweb.web.views.basetemplates and you will find the base templates used to generate (X)HTML for your application. The most important template there is TheMainTemplate. A page is composed as indicated on the schema below : The sections dispatches specific views: header: the rendering of the header is delegated to the htmlheader view, whose default implementation can be found in basetemplates.py and which does the following things: - inject the favicon if there is one - inject the global style sheets and javascript resources - call and display a link to an rss component if there is one available it also sets up the page title, and fills the actual header section with top-level components, using the header view, which: - tries to display a logo, the name of the application and the breadcrumbs - provides a login status area - provides a login box (hiden by default) left column: this is filled with all selectable boxes matching the left context (there is also a right column but nowadays it is seldom used due to bad usability) contentcol: this is the central column; it is filled with: - the rqlinput view (hidden by default) - the applmessages component - the contentheader view which in turns dispatches all available content navigation components having the navtop context (this is used to navigate through entities implementing the IPrevNext interface) - the view that was given as input to the template’s call method, also dealing with pagination concerns - the contentfooter footer: adds all footer actions You can overload some methods of the TheMainTemplate, in order to fulfil your needs. There are also some attributes and methods which can be defined on a view to modify the base template behaviour: You can also modify certain aspects of the main template of a page when building a url or setting these parameters in the req.form: There are also the following other standard templates:
https://docs.cubicweb.org/book/devweb/views/basetemplates.html
CC-MAIN-2018-34
refinedweb
482
54.97
Created on 2008-07-25 15:26 by Antoine d'Otreppe, last changed 2012-02-26 02:58 by eric.araujo. This issue is now closed. When trying to do something like "functools.update_wrapper(myWrapper, str.split)" I got this error message: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "Aspyct.py", line 175, in beforeCall _stickAdvice(function, theAdvice) File "Aspyct.py", line 90, in _stickAdvice functools.update_wrapper(theAdvice, function) File "/usr/lib/python2.5/functools.py", line 33, in update_wrapper setattr(wrapper, attr, getattr(wrapped, attr)) AttributeError: 'method_descriptor' object has no attribute '__module__' I think what you want is functools.update_wrapper(myWrapper, str.split, ('__name__', '__doc__')) The problem actually has to do with trying to use update_wrapper on a method instead of a function - bound and unbound methods don't have all the same attributes that actual functions do. >>> import functools >>> functools.WRAPPER_ASSIGNMENTS ('__module__', '__name__', '__doc__') >>> functools.WRAPPER_UPDATES ('__dict__',) >>> def f(): pass ... >>> class C: ... def m(): pass ... >>> set(dir(f)) - set(dir(C.m)) set(['func_closure', 'func_dict', '__module__', 'func_name', 'func_defaults', '__dict__', '__name__', 'func_code', 'func_doc', 'func_globals']) Is an exception the right response when encountering a missing attribute? Given that the error can be explicitly silenced by writing "functools.update_wrapper(g, str.split, set(functools.WRAPPER_ASSIGNMENTS) & set(dir(str.split)))", I'm inclined to think the current behaviour is the correct option. Since this is an issue that doesn't come up with the main intended use case for update_wrapper (writing decorators), and since it can be handled easily by limiting the set of attributes copied to those the object actually has, I'm converting this tracker item to an enhancement request asking for a shorter way of spelling "ignore missing attributes" (e.g. a keyword-only flag). Thank you for considering this report :) Another possibility would be for methods to also get the __name__ and __module__ attributes. I don't see any counter-indication to it. IMO,. If. It fails because classmethods don't have a __module__ attribute, as commented upon elsewhere in this issue. To fix this, you'd either have to either pass in an `assigned` parameter to the `wraps` function, or swap the order of decorator application (i.e. `classmethod(magic(hello))`). This seems arbitrary and unnecessarily complex; skipping over a missing __module__ should be just fine. Mixing `functools.wraps` and `classmethod` is a relatively common use case that should be as simple as possible. I've attached a trivial patch which just ignores missing "assigned" attributes. The patch should come with an unit test (in Lib/test/test_functools.py). New patch included, with a test case. I had wanted to check the classmethod __module__ thing directly, but that proved to be elusive, since the classmethod gets the __module__ attribute if the module is '__main__', and you can't delete that attribute. My test just tries to assign another attribute which doesn't exist. I just tried to copy the style of the rest of the module, lmk if there are any problems. In your test, the more common convention is to use assertFalse(foo) instead of assert_(not foo). I think it would be better to test with some of the real world examples given in this issue: str.split, and a functools.partial object. As an extra data point: we just hit this problem in Django ticket #13093 (). In our case, a decorator was using wraps(); however, that decorator was breaking when it was used on a class with a __call__ method, because the instance of the class doesn't have a __name__ attribute. We've implemented the proposed workaround (i.e., check the attributes that are available and provide that tuple as the assigned argument), but I don't agree that this should be expected behavior. wraps() is used to make a decorated callable look like the callable that is being decorated; if there are different types of callable objects, I would personally expect wraps() to adapt to the differences, not raise an error if it sees anything other than a function. True, some attributes (like __doc__) won't always be correct as a result of wrapping on non-vanilla functions -- but then, that's true of plain vanilla functions, too. A decorator wrapping a function can fundamentally change what the wrapped function does, and there's no guarantee that the docstring for the wrapped function will still be correct after decoration. Patch.) To Evan Klitzke (eklitzke): This code _should not_ work. [Unbound] classmethod object is not a method or a function, it is even not a callable; it is a descriptor (returning callable). So, it cannot be wrapped or decorated in such way. If you want something like this to work, you probably should place @classmethod on the upper level (in other words, apply classmethod after all other decorators): @classmethod @magic def hello(cls): print '%r says hello' % (cls,) Is there anyone who can provide this issue with a bit of TLC as it's almost the 2nd birthday? That would be me :) In line with the 'consenting adults' philosophy and with the current behaviour causing real world problems, I'll accept this RFE and check it in soon. Implemented in r84132 (not based on this patch though). Shouldn't this be fixed in 2.7 as well? It's a bug, it's in the wild, and it's causing people to do ugly (and maybe not 100% reliable) things like Well, Nick judged that this was not a bug per se, but rather a request for enhancement, thus it was only committed to 3.3.
https://bugs.python.org/issue3445
CC-MAIN-2018-34
refinedweb
928
54.02
Data can take many shapes and forms - and it's oftentimes represented as strings. Be it from a CSV file or input text, we split strings oftentimes to obtain lists of features or elements. In this guide, we'll take a look at how to split a string into a list in Python, with the split()method. Split String into List in Python The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace. Let's take a look at the behavior of the split()method: string = "Age,University,Name,Grades" lst = string.split(',') print(lst) print('Element types:', type(lst[0])) print('Length:', len(lst)) Our string had elements delimited with a comma, as in a CSV (comma-separated values) file, so we've set the delimieter appropriately. This results in a list of elements of type str, no matter what other type they can represent: ['Age', 'University', 'Name', 'Grades'] Element types: <class 'str'=""> Length: 4 </class> Split String into List, Trim Whitespaces and Change Capitalization Not all input strings are clean - so you won't always have a perfectly formatted string to split. Sometimes, strings may contain whitespaces that shouldn't be in the "final product" or have a mismatch of capitalized and non-capitalized letters. Thankfully, it's pretty easy to process this list and each element in it, after you've split it: # Contains whitespaces after commas, which will stay after splitting string = "age, uNiVeRsItY, naMe, gRaDeS" lst = string.split(',') print(lst) This results in: ['age', ' uNiVeRsItY', ' naMe', ' gRaDeS'] No good! Each element starts with a whitespace and the elements aren't properly capitalized at all. Applying a function to each element of a list can easily be done through a simple for loop so we'll want to apply a strip()/ trim() (to get rid of the whitespaces) and a capitalization function. Since we're not only looking to capitalize the first letter but also keep the rest lowercase (to enforce conformity), let's define a helper function for that: def capitalize_word(string): return string[:1].capitalize() + string[1:].lower() The method takes a string, slices it on its first letter and capitalizes it. The rest of the string is converted to lowercase and the two changed strings are then concatenated. We can now use this method in a loop as well: string = "age, uNiVeRsItY, naMe, gRaDeS" lst = string.split(',') lst = [s.strip() for s in lst] lst = [capitalize_word(s) for s in lst] print(lst) print('Element types:', type(lst[0])) print('Length:', len(lst)) This results in a clean: ['Age', 'University', 'Name', 'Grades'] Element types: <class 'str'=""> Length: 4 </class> Split String into List and Convert to Integer What happens if you're working with a string-represented list of integers? After splitting, you won't be able to perform integer operations on these, since they're ostensibly be strings. Thankfully, we can use the same for loop as before to convert the elements into integers: string = "1,2,3,4" lst = string.split(',') lst = [int(s) for s in lst] print(lst) print('Element types:', type(lst[0])) print('Length:', len(lst)) Which now results in: [1, 2, 3, 4] Element types: <class 'int'=""> Length: 4 </class> Split String into List with Limiter Besides the delimiter, the split() method accepts a limiter - the number of times a split should occur. It's an integer and is defined after the delimiter: string = "Age, University, Name, Grades" lst = string.split(',', 2) print(lst) Here, two splits occur, on the first and second comma, and no splits happen after that: ['Age', ' University', ' Name, Grades'] Conclusion In this short guide, you've learned how to split a string into a list in Python. You've also learned how to trim the whitespaces and fix capitalization as a simple processing step alongside splitting a string into a list.Reference: stackabuse.com
https://www.codevelop.art/python-split-string-into-list-with-split.html
CC-MAIN-2022-40
refinedweb
687
55.58
Example: Find ASCII value of a character public class AsciiValue { public static void main(String[] args) { char ch = 'a'; int ascii = ch; // You can also cast char to int int castAscii = (int) ch; System.out.println("The ASCII value of " + ch + " is: " + ascii); System.out.println("The ASCII value of " + ch + " is: " + castAscii); } } Output The ASCII value of a is: 97 The ASCII value of a is: 97 In the above program, character a is stored in a char variable, ch. Like, double quotes (" ") are used to declare strings, we use single quotes (' ') to declare characters. Now, to find the ASCII value of ch, we just assign ch to an int variable ascii. Internally, Java converts the character value to an ASCII value. We can also cast the character ch to an integer using (int). In simple terms, casting is converting variable from one type to another, here char variable ch is converted to an int variable castAscii. Finally, we print the ascii value using the println() function.
https://www.programiz.com/java-programming/examples/ascii-value-character
CC-MAIN-2022-40
refinedweb
168
61.77
Ticket #12957 (closed defect: worksforme) libpng error when trying to use pygame with png files Description I've got a MacBook Pro (core 2 duo, 2GB RAM) and I use MacPorts (well, it was darwin ports awhile ago) to install python, pygame and stuff like that. I checked when I first got it, and my project (nathancheckers) seemed to run fine at the time. Now, about a year later, it fails with the following error, which I can't figure out. $ ./nathancheckers.py Traceback (most recent call last): File "./nathancheckers.py", line 26, in ? from nc_display import * File "/Users/nathan/nathancheckers/tags/1.5/nc_display.py", line 82, in ? set_theme() File "/Users/nathan/nathancheckers/tags/1.5/nc_display.py", line 33, in set_theme global g_board; g_board = l(j('themes',theme,'g_board.png')) pygame.error: Failed loading libpng12.dylib: dlopen(libpng12.dylib, 2): image not found I've manually checked that the png image it wants still exists in the same location it always had. I've upgraded MacPorts (sudo port -d selfupdate) and everything in it including libpng and pygame to the latest versions (sudo port -v upgrade outdated). The .dylib file for libpng even exists: $ locate libpng12.dylib /opt/local/lib/libpng12.dylib Any ideas? nathancheckers is open source. You can download the full source and everything here (the "linux" download is the full source tarball): Any ideas??? Change History comment:2 Changed 6 years ago by ryandesign@… - Owner changed from macports-dev@… to ryandesign@… - Cc nathan.stocks@…, ryandesign@… added - Milestone set to Port Bugs comment:3 Changed 6 years ago by ryandesign@… - Status changed from new to closed - Resolution set to worksforme There was yet another version of libpng available (@1.2.22). After upgrading to it AND rebooting, the libpng issue has disappeared.
http://trac.macports.org/ticket/12957
CC-MAIN-2013-20
refinedweb
296
66.23
Hello! does anybody have any clue how to create a railhand in Revit using Rhino.Inside? It throws an error that doesnt allow me to generate the railhand thanks in advance Hello! does anybody have any clue how to create a railhand in Revit using Rhino.Inside? It throws an error that doesnt allow me to generate the railhand thanks in advance Hello Rickson, thanks for the help, it seems to be a work around, only, if you could tell me how to translate it to python. I have little understanding of C#… as far as I understood I need to add the RhinoInside.Revit.Rhinoceros.InvokeInHostContext. Nevertheless something is missing cause I added up to the code but still not working. thanks in advance! I don’t think you need that. I believe it needs doc railing type.id level.id curves as iList[ElementId]() i’ll see if i can get something working, learning here myself. Ok, got this to work, barely… the curve to List[Curve] to List[CurveLoop] is certainly not the ideal way. Hopefully a py pro will comment with the right way. RiR-CreateRailing_Py.gh (9.4 KB) import clr clr.AddReference('System.Core') clr.AddReference('RhinoInside.Revit') clr.AddReference('RevitAPI') clr.AddReference('RevitAPIUI') clr.AddReference('System') from System.Collections.Generic import List clr.ImportExtensions(RhinoInside.Revit.Convert.Geometry) # active Revit verison REVIT_VERSION = Revit.ActiveUIApplication.Application.VersionNumber #) curves = List[DB.Curve]() curves.Add(Curve.ToCurve()) clc = DB.CurveLoop.Create(curves) # create and start the transaction t = DB.Transaction(doc, 'Create Railing') t.Start() try: railing = DB.Architecture.Railing.Create(doc, clc, Type.Id, Level.Id) t.Commit() except Exception as txn_err: # if any errors happen while changing the document, an exception is thrown # make sure to print the exception message for debugging show_error(str(txn_err)) # and rollback the changes made before error t.RollBack() edit (you probably want to throw the data dam back in there or it will create again and throw an error) hello Rickson, Thanks a lot for the effort! It is really nice from you to spend some time on my issue. Nevertheless I am not sure why i continue having the same problem thant I had with my code. maybe a third person can try your code and say if for him/her works, cause maybe there is something wrong with my revit. Cheers. Igperma, I believe the error is due to creating another instance on top of the previous. If i open up a clean file, select railing type and level then activate i get no errors, if i change the radius, reactivate it works fine. If i hit a GH refresh it throws the warning (still creating the object) No worries, they are adding in a Railing by Curve component on the next release…
https://discourse.mcneel.com/t/rhino-inside-create-railing-revit-api-python/108328
CC-MAIN-2020-40
refinedweb
467
57.67
unity 6.8 candidate segfaults on "app expose" with low gfx mode Bug Description - run the current ppa version - open several nautilus dialog - click on nautilus in the launcher stacktrace: #0 0xb7548f90 in ?? () from /lib/i386- No symbol table info available. #1 0xb4838cee in memmove (__len=806243456, __src=0x3c73f2f0, __dest=<optimized out>) at /usr/include/ No locals. #2 drisw_update_ dPriv = <optimized out> st_ctx = <optimized out> pipe = 0x8945500 transfer = 0xc4f94f0 map = 0xc65a670 "\321\332\ x = 52 y = 7 w = 201560864 h = 2 line = 1 cpp = <optimized out> #3 0xb483a373 in dri_set_tex_buffer2 (pDRICtx=0x8945450, target=3553, format=8410, dPriv=0xc59ae78) at dri_drawable.c:234 ctx = 0x8945470 drawable = 0xc5468d8 pt = 0xb392b90 #4 0xb4fdfe40 in drisw_bind_ gc = 0x8945368 pcp = 0x8945368 base = 0xb44d178 pdraw = 0xb44d178 psc = <optimized out> #5 0xb4fb7c77 in __glXBindTexIma gc = <optimized out> #6 0xb594b1f7 in operator()<void (*)(_XDisplay*, long unsigned int, int, int*), boost:: No locals. #7 operator()<long unsigned int> (this=<optimized out>, a1=<optimized out>) at /usr/include/ No locals. #8 boost:: f = <optimized out> #9 0xb595df97 in operator() (a0=14680574, this=0xb596e690 <(anonymous namespace) No locals. #10 compiz: No locals. #11 0xb5949897 in TfpTexture: No locals. #12 0xb594a197 in TfpTexture::enable (this=0xc453598, filter= No locals. #13 0xb594f8a6 in GLWindow: filter = GLTexture::Fast #14 0xb246f8a2 in unity:: wTransform = {m = {0.000884839741, 0, 0, 0, -0, -0.0011797864, -0, -0, 0, 0, 1, 0, -0.420898438, 0.399739593, -0.866025388, 1}} __for_range = @0xa0c0b74: {<std:: #15 0xb24730a0 in unity:: scale_win = 0xc0000 ss = 0x4d state = 1014231792 #16 0xb276c361 in ScaleWindow: curr = 0 #17 0xb276bec1 in PrivateScaleWin lastAttrib = {opacity = 65535, brightness = 65535, saturation = 65535, xScale = 1, yScale = 1, xTranslate = 0, yTranslate = 0} wTransform = {m = {0.000884839741, 0, 0, 0, -0, -0.0011797864, -0, -0, 0, 0, 1, 0, -0.478372395, 0.42808187, -0.866025388, 1}} sAttrib = {opacity = 65535, brightness = 65535, saturation = 65535, xScale = 1, yScale = 1, xTranslate = 0, yTranslate = 0} scaled = <optimized out> status = <optimized out> #18 0xb59507f1 in GLWindow::glPaint (this=0xbe71748, attrib=..., transform=..., region=..., mask=0) at /build/ rv = <optimized out> curr = 1 #19 0xb24729a1 in unity:: wAttrib = {opacity = 65535, brightness = 65535, saturation = 65535, xScale = 1, yScale = 1, xTranslate = 0, yTranslate = 0} tray_xids = @0xbfbb2270: {<std:: #20 0xb59507f1 in GLWindow::glPaint (this=0xbe71748, attrib=..., transform=..., region=..., mask=0) at /build/ rv = <optimized out> curr = 0 #21 0xb5950b15 in PrivateGLScreen w = 0x9ced500 offXY = {mX = 0, mY = 0} pl = {<std:: tmpRegion = {priv = 0xc01f718} vTransform = {m = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}} #22 0xb5951502 in GLScreen: sTransform = {m = {0.0009765625, 0, 0, 0, -0, -0.00130208337, -0, -0, 0, 0, 1, 0, -0.5, 0.5, -0.866025388, 1}} #23 0xb2f08f42 in WallScreen: status = <optimized out> #24 0xb59513f5 in GLScreen: rv = <optimized out> curr = 7 sTransform = {m = {1, -0, 0, 3.36311631e-44, 9.10844002e-44, 1.04256606e-42, 1.86518554e-33, -2.21552909e-08, -1.12423595e-06, -1.47500396e-05, -1.46212196, -2.16116476e-08, 8.59318697e-34, -0, 0, -1.11386612e-06}} #25 0xb2b8e0d9 in PrivateAnimScre #26 0xb59513f5 in GLScreen: rv = <optimized out> curr = 4 sTransform = {m = {4.14087633e-32, -1.46212482, 1.12103877e-44, 1.07619722e-42, -0.5, 0.5, -0.866025388, -1.13993774e-05, 1.00121462e-31, 1.40129846e-45, 3.36311631e-44, -1.19440165e-05, 7.97240252e-33, 0, 2.24207754e-44, -1.19465267e-05}} #27 0xb276ba36 in PrivateScaleScr No locals. #28 0xb59513f5 in GLScreen: rv = <optimized out> curr = 1 sTransform = {m = {1.00121556e-31, 1.28547581e-33, 1.2855456e-33, -1.13993774e-05, 1.00121556e-31, 1.28547581e-33, 1.2855456e-33, -1.04427281e-05, 0, 1.00121556e-31, 1.31640012e-33, -1.45164304e-05, 8.59248902e-34, -1.47484243e-05, -1.46215391, -1.45156673e-05}} #29 0xb247e6c8 in unity:: ret = <optimized out> force = false #30 0xb59513f5 in GLScreen: rv = <optimized out> curr = 0 sTransform = {m = {1.40129846e-45, -1.46216679, 1.50463277e-36, 3.76158192e-37, 1.12103877e-44, -1.47484243e-05, 8.69773249e-34, -1.47484243e-05, 9.910433e-32, -1.46218681, 8.91888706e-34, -1.45161148e-05, -1.46217442, 8.59245228e-34, 9.910433e-32, -1.45163312e-05}} #31 0xb593f8c7 in PrivateGLScreen identity = {m = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}} output = 0x8908410 oldFbo = 0x0 useFbo = true tmpRegion = {priv = 0xa1f9148} alwaysSwap = 176 fullscreen = 48 #32 0xb597d061 in CompositeScreen No locals. #33 0xb2f05d31 in WallScreen::paint (this=0x8b03230, outputs=..., mask=5) at /build/ No locals. #34 0xb597d08d in CompositeScreen curr = 0 #35 0xb597ec11 in CompositeScreen timeDiff = <optimized out> dpy = <optimized out> mask = 5 d = <optimized out> outputs = {<std:: tv = {tv_sec = 1349177922, tv_usec = 578032} #36 0xb5980160 in operator() (p=<optimized out>, this=0x893f7e8) at /usr/include/ No locals. #37 operator()<bool, boost:: No locals. #38 operator() (this=0x893f7e8) at /usr/include/ No locals. #39 boost:: f = 0x893f7e8 #40 0xb7736853 in CompTimer: No symbol table info available. #41 0xb7736911 in CompTimeoutSour No symbol table info available. #42 0xb7736a01 in sigc::internal: No symbol table info available. #43 0xb7735b8f in CompTimeoutSour No symbol table info available. #44 0xb7256071 in Glib::Source: No symbol table info available. #45 0xb71589e3 in g_main_ No symbol table info available. #46 0xb7158d80 in ?? () from /lib/i386- No symbol table info available. #47 0xb71591db in g_main_loop_run () from /lib/i386- No symbol table info available. #48 0xb7257513 in Glib::MainLoop: No symbol table info available. #49 0xb76ecb8a in compiz: No symbol table info available. Related branches - Łukasz Zemczak: Approve on 2012-10-02 - Marco Trevisan (Treviño): Approve on 2012-10-02 - Diff: 12 lines (+1/-1)1 file modifiedplugins/unityshell/src/unityshell.cpp (+1/-1) What does "low gfx mode" mean in this context? @Albert: see lp #1046497 "Unity through llvmpipe is slow" and https:/ This is not new to 6.8... Thank you for taking the time to report this bug and helping to make Ubuntu better. This particular bug has already been reported and is a duplicate of bug 1055. oh, it is new, downgrading unity to the quantal version fixes the issue (the stacktrace looks the same but the issue in this bug is happening every time with the steps of the description and the same steps work with 6.6): Hmm, seems fixed some time ago, so going to mark the main Unity task as such as well and remove the milestone. Status changed to 'Confirmed' because the bug affects multiple users.
https://bugs.launchpad.net/unity/+bug/1060148
CC-MAIN-2019-04
refinedweb
1,049
71.95
Hello, I'm starting a project that contains an iOS and Android apps. These apps should be properly localized and we have chosen Vernacular to achieve this localization. General question: 1) Is there any other cross-platform method/framework out there? I had been playing around with Vernacular for less than a day, and even when it seems cool and promises to work fine, it lacks documentation and examples out there. Vernacular specific: 1) How do you add vernacular to your project? I'm working on the iOS portion and -after compiling vernacular solution- I could add Vernacular.Catalog.dll as a reference to both my Core and iOS applications. Is this the right way to do it? I would love to see a vernacular component. 2) Can I run vernacular in a mac? I haven't found how (I'm a newbie mac user). I could run it on my pc only. Thanks, R. Rasiel- Re: your Vernacular specific questions... 1) Yes, you simply add the .NET Vernacular.Catalog.dll as a Reference in your project. Ofcourse, you'll need to make sure that you are using Vernacular; in the project. You will then need to call the platform-specific catalog implementation: For iOS, this will likely happen the the FinishedLaunchingmethod of your AppDelegate. Now you can call Vernacular.Catalog.GetString("YourString", "YourComment"); 2) I'm running Vernacular on Mac OS X without issue. You'll need to rename Vernacular.exe to vernacular and make sure you have proper permissions to run it ( sudo chmod a+x vernacular). You will likely also want to add it your .bash_profile PATH and write shell scripts or msbuild scripts to automate the process, but it works great when you get things setup. I'm using localization in the PCL project using .resxfiles. I've been working this way several months and it's pretty easy and completely cross-platform. One single localization file for all the platforms. Check out this tutorial for more info. I've tweaked this solution a little, but it worked out of the box pretty well. @danb thanks for your response. I ended up using Vernacular and I forgot to post the results back here (my bad, somehow this thread was never replied and I forgot about it). @GuillermoGutierrez I remember seeing the satellite assembly support but I gave it a tried and never made it to work. (Never found pointers as the blog post you included here though). I have a 2 level PCL in my app, one PCL which is used not only by my mobile apps, but also by the web app, in that PCL I put .resx resources I intended to use everywhere, however I could never use them in iOS. I will give it another try. While investigating on Vernacular, I learned that .resx are very limited, things like gender and plurals are not supported naturally. It is not fun to have 2 sets of resources, and a lot of duplicates as I have now between my .resx and Vernacular, but I haven't found the time to clean this mess as focused as I'm in new features.
https://forums.xamarin.com/discussion/comment/36959/
CC-MAIN-2021-25
refinedweb
526
66.94
Develop your first simple neural network using TensorFlow in Python In this tutorial, you will learn about TensorFlow and how to use it to create a simple neural network. TensorFlow in Python was created by Google to enable us to create high functioning algorithms. It serves as a foundation library for deep learning programmers. TensorFlow eases learning and creating a process for programmers. Which is why it is an ideal platform to learn how to develop your first neural network. The easiest way to understand what a neural network is, to create one from scratch. In this article, you will get a basic understanding of what a neural network is and the easiest way to create one using TensorFlow. But, what is a neural network? A neural network is roughly based on how the human brain works. Our brain is made up of infinite neurons that are all connected to one another. They pass information through these connections and ultimately help us in our day to day life. For example, this is a picture of a bird at an extremely low resolution. But our brain has absolutely no difficulty in recognising it as a bird: If you were to write a program, that takes in a picture and tells you what the picture is of, the task can be quite difficult. But, this is where machine learning and neural networks kick in and make the task easier for you. So let’s learn how to make a neural network that can recognise different items of clothing. What a neural network consists of: - An input layer - A hidden layer - An output layer - Weights between the layers - A deliberate activation function for every hidden layer There are multiple types of neural networks, but we will learn how to create the easiest one – that transfers data from front to back. The architecture of the neural network we will create: - Our images essentially come in 28 by 28 pixels – so that means that there will be 28 rows and 28 columns. Principally transferring all this data into one neuron is difficult and it doesn’t work very well. So, what most people do is ‘flatten the data’. - Flattening the data means – taking an interior array and combining them all. For example: rather than having an array like this [[1],[2],[3]] we will have it like [1, 2, 3] this. - After flattening the data, we will get an array of the size of 784 pixels (28 x 28 = 784). This will serve as the input to the neural network. - Output layer – our output is going to be a number between 0-9. So, we will have 10 neurons – each representing one of the different digits (0, 1, 2, 3….9). So how this essentially works is suppose we input an image of an apple – then all the classes it is made up of will be lit up a certain amount. Then our neural network will choose the one with the highest probability and return the output respectively. - Moving onto our hidden layers – we could technically train our program to work with only two layers (the input layer and the output layer). But if we choose to work with only 2 layers – it restricts the activities we can do. To overcome that, we add a hidden layer between the input and output layer. We can usually arbitrarily pick the number of neurons in our hidden layer but it’s a good practice to decide that based on the percentage of the input layers. So, for example, we will choose 128 neurons for our hidden layer. So, what will happen now is that the input will be fully connected to the hidden layer and the hidden layer in turn will be connected to all the neurons in the output layer. - What we want our hidden layer to do is, recognise patterns in our input image. Then based on the highest probability choose one of the neurons in the output. Lets start the coding: import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt data = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = data.load_data() class_names = [‘T-shirt/top’, ‘Trouser’, ‘Pullover’, ‘Dress’, ‘Coat’, ‘Sandal’, ‘Shirt’, ‘Sneaker’, ‘Bag’, ‘Ankle boot’] train_images = train_images/255.0 test_images = test_images/255.0 #keras.Sequential creates the layers and defines the order in which they need to be present in model = keras.Sequential([ keras.layers.Flatten(input_shape=(28,28)), keras.layers.Dense(128, activation=”relu”), keras.layers.Dense(10, activation=”softmax”) ]) model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=7) prediction = model.predict(test_images) #the next set of code is to first show the input and then the prediction for i in range(7): plt.grid(False) plt.imshow(test_images[i], cmap=plt.cm.binary) plt.xlabel(“Actual: ” + class_names[test_labels[i]]) plt.title(“Prediction” + class_names[np.argmax(prediction[i])]) plt.show() Examples of input: There it is, this is one of the easiest and quickest ways to develop a simple neural network using TensorFlow in Python.
https://valueml.com/your-first-simple-neural-network-using-tensorflow-in-python/
CC-MAIN-2021-25
refinedweb
844
54.93
As Atomic CSS (also known as Functional CSS) has been gaining in popularity, some confusion has occurred about similar related terms. The goal of this article is to clarify this terminology. There are other projects that use the term Atomic, including Atomic Web Design by Brad Frost. Atomic CSS is a completely separate concept from these. Let's start by defining Atomic CSS: Atomic CSS is the approach to CSS architecture that favors small, single-purpose classes with names based on visual function. There are different ways to write Atomic CSS (see variations below). One example would be this: .b: <!-- Programmatic Atomic CSS Example --> <div class="Bgc(#0280ae) C(#fff) P(20px)"> Lorem ipsum </div>! No support for CSS Grid in Atomizer yet. Thanks for nice article! We’re quite fond of atomic CSS too, and since we moved to it, I never looked back. Here is our take on subject: Ekzo, where atomic approach meets BEM methodology. It’s worth to check Ekzo in context of Kotsu, since this starter kit better shows basics and usage approaches. I must note that in my experience atomic CSS might be painful choice for large projects if website doesn’t use good templating language and doesn’t encapsulate everything into components. It might seem like very repetitive, with long, hard to understand class attributes scattered all over the place. In component-based approach all this “CSS” logic always carried with component. So, if you need to change something, you just edit atomic classes in that component, and magic happens. Not to parrot what others say on this topic, but how is this much different from inline styling? The naming convention describes individual CSS properties, with no context to the situation it’s being used in. Classnames describing their values is asking for trouble when it comes to future maintenance (as you mention in the black:navy example). It sounds like design changes require a mass find/replace operation on the HTML side instead of the CSS side, unless I’m understanding this concept wrong? Won’t this system also cause excessive front end strain in interactive scenarios where elements may be animated, styled based on state, or require specific responsive behaviour? Unless I’m missing something, this feels like a big step backwards. My favorite discussion of how this is different than inline styles can be found in a discussion on Tachyons, a popular Atomic CSS project: Inline CSS has extremely high specificity, doesn’t support @ rules, pseudo selectors, or pseudo elements. Atomic doe author somewhat similarly to Inline styling however. Correct. You’ll find no semantic class names here (unless you’ve setup some helper classes). It may seem counter-intuitive at first blush; but it’s actually quite the opposite. The black: navyexample was an example of what NOT to do. Immutability is foundational to a working Atomic setup. Future maintenance is essentially nonexistent with Atomic on the CSS side of the fence. In the markup, you simply change which classes you need to make whatever you’re working on to look differently. As for the global replacement, this hasn’t been my experience at all… especially not when using Atomic inside of front-end frameworks like React where I just need to change the Atomic inside a single component. If you manage to get a high degree of reuse out of your BEM like classes, then this could definitely be an area of concern for you. But even when I was using BEM, I got very little reuse out of my semantic class names and found myself adding additional class names instead while refactoring for fear of breaking something, somewhere. Nope, unless I’m misunderstanding you. How would Atomic be any different than using any other type of class based convention in these areas? Ailwyn, I totally agree with you. As an example of an area this method may trip up: using CSS animations to transition from a neutral state to a focused state. For the sake of example, how would you handle things like background colour changes, hover state colours, border/outline changes? Those simple tactile feedback states seem rather convoluted to add under atomic CSS. If your application has visual modifiers to further promote the state of a part of the page (as a simple example: a delayed train may appear in orange), how can you easily add/subtract the large number of individual styles without majorly reworking the classes? If design changes are pushed through class changes, and not CSS changes, what is to stop redundant CSS piling up over time? Each transition/animation is it’s own atomic class, as are the individual properties. The convoluted piece isn’t solving the above issues in Atomic, it’s just settling on your naming convention. For example, let’s say we wanted to transition between two background colors and two text colors on focus. Here’s an example of how you could do it in plain ole Atomic CSS (no tooling). With the made up convention below, I use shorthand property identifier, value, and then a pseudo class letter identifier as my naming convention. CSS .BgcDarkGray { background-color: #111; } .BgcWhiteF:focus { background-color: #fff; } .CWhite { color: #fff; } .CBlackF:focus { color: #000; } .TrsAll { transition: all .115ms ease-in-out; } HTML <button class="BgcDarkGray BgcWhiteF CWhite CBlackF TrsAll">Click Me!</button> The neat part about all of the libraries and tools around Atomic is that you don’t need to come up with your own naming convention if you don’t want too (you probably don’t). Authoring is honestly the most difficult part about Atomic, so I definitely recommend checking out some of the tools/libraries. All pseudo classes, elements, @rules, etc. would be handled in the same manner as the example above. I could have an H suffix for “Hover” or I could use an @MqMinW60emsuffix for apply this rule only when this rule is in a window that’s at least 60em’s wide. The resulting CSS for dark gray at min-width 60em would look like this: CSS @media (min-width: 60em) { .BgcDarkGray@MqMinW60em { background-color: #111; } } Again, not difficult to handle, just requires you to think through how you want to name everything. The classes for every property you’ll use in your app will exist. It’s up to you to apply whichever ones are necessary for the state of your app at this time. Let’s say I need to show an error message on an API request failure. The neutral state HTML may look something like this (I’ll use Atomizer classes in this example): HTML <output class="D(n) Ta(C) Fz(1.25em) C(#111)"></output> Then an error occurs, the message needs to display and show the text in red… so the HTML would become HTML <output class="Ta(C) Fz(1.25em) C(#f00)">There was a problem!!</output> I’m only ever applying the classes I need to achieve the look I’m going for. I just remove/add classes as needed. The fact that Atomic CSS classes are unique and immutable. They never change and they’re never redefined. Only the CSS properties you need should have Atomic classes. Atomic is the CSS convention antithesis to redundancy. So how is this better than just using inline styles? A lot of these examples feel to me like they’d have a lot of the same brittleness that comes with re-defining all of your styles on every element, with the added overhead of having your styles in both your classnames and your CSS file. Inline Styles don’t support @ rules, pseudo selectors, or pseudo elements. Further, they have extremely high specificity (which may or many not be what you want). Think of the many benefits of Immutability and Functional Programming in your JavaScript. Now apply that thinking to your CSS. That’s what Atomic gives you in a nutshell. If you’re dealing with a small project by yourself, there may not be much of a benefit. But as you scale (both in scope and team size), Atomic really starts to shine, especially with the tooling available for it. The resulting CSS will be smaller and you’ll save yourself completely from refactoring. I have no horse in this race, other than just fascination in watching developer tooling and trying to understand it the best I can.. Does that mean I’m going to start using it on every project and expect you to as well? Nah. disclosure: one of the shed.css authors here. You nailed exactly what prompted us to approach this method, the “append-only” CSS trope. Even in a “proper” BEM codebase, once an app or site gets to a certain size, things become challenging. After much discussion we opted to try a functional approach on TED.com. After 10 months, 9 product launches, and on-boarding 3 front-end devs, we’ve found that a functional approach to CSS fulfills its promises. I think if you use it for a short time, you’ll fall in love so hard that you’ll be using it on every new project because it solves real problems at any scale. Rephrasing, the issue with Atomic CSS is that it may just want to ignore maintainability, but it comes off as not understanding it. I think it worth to add that as every tool, it should be used wisely and not excessive. For instance, if you’re noticing pattern in chaining of small utility classes — encapsulate it into understandable pattern class, like Object (example). Your specific component getting too much styling and should express difficult relations between inner items? Times to encapsulate it into Component class, otherwise your devs will get hard times understanding all relations and why exactly you used some specific utilities. The last point is, in fact, quite important. Expressing relations between items is weak point of atomic CSS, and the one who uses it should always remember it. Great run John! I’ve been captivated by Atomic CSS since first playing around with Atomizer and currently use it in several projects at work. Initially we used Atomizer but we’ve since switched over to a tool I wrote called Pre-Style (which is a CSS-in-JS variant that lets you author inline and spits out atomic classes at build time). The immutability has drastically cut down our refactor time and by using tools like Atomizer/Pre-Style it means that our stylesheets are only ever as big as we need them and never bigger. Needless to say, Atomic CSS comes highly recommended by this dev! Some of those class names make me sad. “.text-3rem” is collapsing functional and visual specs. What if that element needs to be 3.375rem? 2.975rem? USE. SEMANTIC. NAMES. If that’s a subhead, for example, call it .subhead or .text-subhead if that’s appropriate for the project. Same for things like .bgrBlue. If the background for that element needs to change to a shade of green, you now have to not only update the color definition, you need to update your markup or live with the ridiculous situation where .bgrBlue is actually green. This is what I worry about. I probably align more closely with this way of thinking and working for most of my projects than I do to Atomic ideas, but I’m curious about and open to other approaches. Closemindedness and attacking other ideas with emotion and yelling is worse for the web than any class name. I don’t think I attacked anyone here nor do I think I’m being close-minded so I’m not sure where that came from. I don’t see why Atomic and semantic class names are necessarily at odds but forced into choosing one or the other I’ll opt for semantic all the time. Maybe it’s that I work solo or with, sometimes, one other dev so I don’t run into the issue of huge projects with lots of developers but I’d rather segment things by namespace and end up with ‘duplicates’ (i.e. .component1 .subhead and .component2 .subhead vs .subhead3rem). It came from calling a class name “sad” and STATING. THINGS. WITH. ALL CAPS. Yes! Scoping opinions to your experience is much more valuable. That’s where I’m at. I work alone and on small-ish teams. The web is a big place and we all face unique challenges. What are the benefits of using semantic class names vs. functional ones? They don’t help our apps run faster or benefit end-users in any way. They don’t improve accessibility or SEO. As far as I know, semantic class names are really just meta-data for developers so they know what to change in the corresponding CSS. If that’s the case… then what’s really wrong with choosing a more functional, immutable approach to CSS, especially one that proves to be more efficient than it’s semantic counterparts? You wouldn’t run into this scenario following the Atomic convention. Atomic classes are immutable. .bgrBlue would be blue and would always be blue; .bgrGreen would be green and would always be green. If you wanted to change the background color, you’d swap class names on the element itself in the markup. This immutability principle gives Atomic based tooling the ability to strip out any CSS that’s no longer used at build time, resulting in CSS that only has the atomic classes needed for your site. So it’s the exact same as inline styling? What if you have 12 buttons on a page which are supposed to be accented? Instead of fixing a button-accentclass you replace 12 occurrences of background-bluewith background-green? I guess I am missing something because this doesn’t seem very convenient. If you’re curious about why some are choosing this methodology, I’d recommend these 2 articles: Full re-write in 10 days with tachyons and functional CSS: A case study Building and Shipping Functional CSS View story at Medium.com Or do .bgrBlue .bgrAddYellowto get green. :P Just kidding. Honestly, I agree with you totally. The idea of components and using atomic parts to avoid too much dependencies makes sense. The idea of using classes for single properties (unless they are something like .hidden { display: none; }) doesn’t really make much sense at all. Nor is it that much better than inline styling. I understand (and actually use) a little bit of “color related” classes when working on mobile hybrid apps (PhoneGap) if the framework gives them. But these rarely go beyond a single layout-redclass on the HTML element or something of that sort and changing that class to a different one of the same theme changes everything. That would be a situation where it could make sense. Hi Rick, You may want to read this article: It discusses the importance of “SEMANTIC NAMES”… yes, i too used this Atomic CSS for one of my client project. let me share my opinion about it, its a great tool but hard to manage at the same time especially in large projects.This Atomic CSS helped me in for the use of handy things such as media queries, contextual styling and pseudo-classes though. This is interesting as it’s exactly the opposite as I might have suspected. 1) Hard to manage on a large project. 2) Useful for things like Media Queries, which I think would be weirdly unintuitive to manage with just class names. Looking through that site’s CSS (unless it’s been updated since you’ve worked on it) I think you’ve misunderstood a big part of how to implement atomic CSS. I don’t have an opinion either way on which one is best but your opinion on how hard a tool it is to manage would be heavily coloured by you not implementing it correctly. Your CSS is mostly module based with a small sprinkling of atomic. I still wonder how you could implement this concept into WordPress. Breaking down the template into smaller components which could also include subcomponents sounds like pretty good, but I haven’t found a good example for that in WordPress yet. First and foremost, thanks for the article. I’ve got one question which goes unaddressed though—actually, it’s never addressed when talking CSS methodologies so this is no biggie. How do you deal with accessibility? e.g. -ms-high-contrast, inverted-colorsor light-level(MQ Level 4, should they be implemented at some point) I’ve never found anyone willing to answer this question for some reason but I’d really like to get some feedback about this. With Atomic all MQ’s are handled the same way. In Atomizer, you define media queries in the atomizer.configfile. So you could specify a invc(or whatever you want) media query and then use it like so: class="Bgc(blue)--invc"which says this element should have the background color of blue when the inverted media query is active. Atomizer handles the the writing of the actual CSS for you. With other tools you can author it inline like so (React example): All instances of that media query would be merged together and all properties inside said media query would have their own Atomic class. All Pre-Style blocks would be written to an external CSS file. TL;DR – The short of it is, Atomic is typically one selector per property, whether that’s a typical class selector, a pseudo selector/element, or inside of a media query. One possibility would be to handle them in a similar way to breakpoint prefixing (e.g. use a class like .dim-text-black to set the text color to black for dim light level). A bit of shameless self promotion, but I’d just like to add a new one that I recently built called hydrogencss. Mostly for use with CSS Modules but could be used with other things too. Good thing about it I feel is you can include as little or as much of it as you want. For some reason I find .black{color:navy}less offensive than not being able to change in one sweep every instance of said black. Problems like that can be solved by simple renaming things to make them more understandable. Instead of selector “black” it could be “color-default”. I just don’t see any profits from using it. CSS was created exactly so we could make broad changes with little writing. Using .color-default, .color-primary, .color-secondaryas selectors instead of .blackis a perfectly acceptable way to do Atomic CSS. I agree. I like using things like “color-primary” and “color-secondary” or “bg-color-primary” and “bg-color-secondary” to allow it to be flexible and still easy to modify with a simple changes. In reply to @Lazza (couldn’t reply to thread) It’s authored similarly, but the inner workings of doing class="BgcBlue"vs. style="background-color: blue;"are very different. I’ve outlined a few of those in other comments. Accented how exactly? If you want to change the background-colorof a button, just use a different class. The underlying CSS classes don’t change, they’re immutable. So <button class="AccentBlue">Click Me</button>becomes <button class="AccentGreen">Click Me</button>. If you’re using plain old vanilla HTML with no templating, partials, server-side includes, then yea.. you’ll have to manually replace all 12 occurrences. But let’s be honest… what’s more common: Replacing 12 button’s background colors at once (Holy indecisive designer Batman) or needing to make one of those buttons different from the rest? Atomic absolutely excels at the latter. So much so, that you’ll never have to worry about making breaking CSS changes again. If it’s frequently the former, then Atomic may not be a good solution for you or your team. If you want to author a CodePen to show what you mean I’d be happy to do a Atomic version to illustrate what I’m saying here. It’s my personal take that Atomic CSS prioritizes the end-user over developer convenience. However, tools like Atomizer, Pre-Style and libraries like Tachyons and Basscss make authoring in Atomic much better. Haha! :) Why does the concept of “atomic parts” or really just keeping things “DRY” make sense for components (or HTML and JS) but not your CSS? Reusability means less code repetition, which means smaller files, which means faster loading times. Should you switch to Atomic solely for the minor perf benefits? Probably not. You’d be better off just removing an image from your application. But those perf benefits are gravy on top of a very, very maintainable Sundae. The immutability factor means I can come back to a project a year later and make sweeping styling changes to a group of components without needing to worry about breaking anything, anywhere. You don’t get that assurance with semantic class conventions unless you abandon any sense of reusability altogether. Further, I get all the specificity handling benefits of BEM. Thanks for your answer. Generally, if I want to change how buttons look on my website I don’t want to change one button, I want to change all of them, unless one is special. CSS was invented to avoid repetition and separating style from content. I don’t want to tie a “colorful” class to elements because changing every occurence of it is going to be a nightmare. What if a company changes it’s primary color from blue to red? Am I going to replace all the classes on every .color-blueelement or am I just going to redefine a single, semantic, .color-accentclass? TBH I’d prefer the latter. :) I don’t see how these things relate to what CSS approach you use. You can write a WordPress template with all kind of server side stuff and use proper semantic CSS. If you are talking about using PHP to <?php print_correct_accented_color_class_name_here(); ?>instead of writing class="accented"it seems to me this is like trying to defeat the purpose of CSS in order to recreate it on the server. Or with CSS preprocessors, that are just nice (but superfluous) abstraction tools that produce normal CSS in the end. In reply to @Lazza CSS was invented 20 years ago. Its original goal relates to concerns that have since evolved/morphed. As I discussed in this article, the Separation Of Concern is now a moot point for many devs. In my opinion, one cannot understand the benefits of Atomic CSS without first accepting that it is “okay” to change styles outside of styles sheets. And the comment from Michal seems to prove my point: :-( Thierry, I understand that since you coined the term Atomic CSS you think it’s the best idea ever and one should not try to criticize it, but I’d say let’s keep a quite tone. Maybe, depends on what “outside” means. For sure you are not going to be “more right” if you write something in bold. :) If by “outside” you mean adding a weird class='text-centered'maybe we should go back to the whole presentational HTML tags idea and resurrect <center>… or even add more. Yay to <h1 color='red'>I guess? I’ll keep the CSS but you can keep the unsemantic markup if you like to. Evolution is a thing, regression to what we were using before (as the “visual” tags mentioned before) is another thing. Isn’t it weird that most people using Atomic, BEM, or whatever have to end up using preprocessors, compilers or other shenanigans to rebuild the semantic aspect of CSS that was lost when using one of those approaches? This doesn’t mean using Atomic CSS is illegal or that someone will get mad at you. It’s just using CSS in a very weird way, completely different from what it was designed for. Less convenient. More similar to inline CSS which is also not very good in several cases. It also doesn’t mean it’s always a bad idea. I can think of a couple situation where it could be a good idea. I can also think about a couple situation where I would use (or have used) inline CSS (which is almost the same) but yeah… one should be careful. Use sparingly. ;) Your article is smartly titled “Opinions of Leaders Considered Harmful” and it then goes on in a very long text where you act as a leader giving a harmful opinion. There is also a bit of ad hominem here and there used to attack the arguments of basically all the other people, which is not a very good approach IMHO. We could also discuss how you define best practices (which derive from how CSS was built and how it works and simplifies style maintenance) as simple “opinions”, but… rain check. Also the concept of Atomic CSS adding classes related to presentation in the markup seems to suggest you expect a specific markup to be styled in only one way at the same time (clearly not the case as one can have a print stylesheet or a mobile stylesheet, but I digress). What you wrote about Atomic CSS works very well for “old CSS”, too: In reply to Lazza Nope! And if you take time to read my articles about it you’ll find out this is not the case. Or you could simply check my reply to @unleashit in a comment below, in which I say: “Not saying here that Atomic CSS is the best thing to use, just giving you feedback about your assumptions”. It shows as bold to denote emphasis. What happened to your “let’s keep a quite tone.”? A very short read that explains the differences:- In the case of ACSS, one would not do what’s suggested in this article (“changing Bgc(colorOne)to Bgc(colorTwo)) simply because ACSS allows devs to use “variables” via a config file. In such case, one would use a class like Bgc(color-primary)across one’s entire project and then change the color in one place—the config file. This sounds a lot like using: .background-primary { background-color: colorOne; } But reinventing the wheel via config files, preprocessors and stuff. In reply to @Lazza I think you’re missing the point. A config, or a pre-processor, allows to replace color values across the board inside style sheets instead of changing classes in the markup—as often suggested. .background-primary { background-color: colorOne; } .color-primary { color: colorOne; } .border-primary { border-color: colorOne; } Does this fit in with the topic of client-side “application logic” being developed by front-end/design folks because it’s client-side? It makes me feel like it’s an attempt at making CSS “easy” for people who don’t understand CSS (like maybe programmers/server-side devs who are now working on the front-end because of frameworks like Angular). I’m sure there’s lots of front-end devs who have bent over backwards recently to get better at JavaScript etc, can we not ask for the same for our CSS? I wish we could go back a few steps and keep programming as programming and UI development as UI development. I sometimes wonder where the web is going with all this. CSS and (SCSS/LESS) is simple and easy to follow. This is just adding another layer which doesn’t benefit the person who uses it – the designer! What do you mean @Colin? Our design team uses functional css. I’d argue that it’s easier for a designer to change a classname from “red” to “dark-red” than it is for them to look at the markup, see that it’s a .Button.Button--primary, find the corresponding file, look for color: redin the .Buttonelement, if it isn’t there, look in .Button--primary, change it there, check the whole app to make sure they didn’t change something they didn’t intend to (a Button--primaryelsewhere). Thanks John for writing this. Just a footnote. I think techniques like these stir passion because the see sort of a battle ground between the old way of KISS, and the new wave of engineers who’ve recently become interested in the front end who are bringing along their (sometimes) over engineered ideas. Dramatic as the word “battle ground” may sound, these new voices are the ones that the industry pays attention to and for the better or the worse, are likely to become the expected practices of the present/future. I’m all over composition and functional programming, in “programming”. But I do think its a bit dangerous to try and subject CSS and the theme layer to all of these constructs. I’m sorry, but Atomic CSS unnecessary and an over engineered idea. It’s not that I don’t have an open mind, it’s just that I think its wrong and basically came about as a result of teams who were unhappy with CSS because either a) they don’t understand it well or b) they didn’t have the right collaborative systems in place, or didn’t enforce them or c) they feel personally satisfied by taking bold steps to solve problems even if the new solution creates a new set of problems greater than were originally present. IMO, CSS is far from perfect. Why should we need Sass/Postcss/Bem? I just think people should spend their time working for improvement to CSS itself (and browser uptake) rather than stopgap solutions like this. Sorry, I really don’t want to have to change the markup in 500 React component files because I want a different color button. To me that’s ridiculous. If you’re that scared of mutating your CSS, I suggest therapy :p (and better training in CSS). No, the idea does not come from “a new wave of engineers who’ve recently become interested in the front-end“; I’m not part of the new wave and have no engineering background. On the other hand, I believe I have a good grasp of CSS. Regarding b) I’d say it’s the opposite, Atomic CSS facilitates workflows as it does not require to follow strict rules (i.e. namespacing). Same for c) Atomic CSS addresses a different set of problems (i.e. bloat/performance) which—for some—may be more important… Not saying here that Atomic CSS is the best thing to use, just giving you feedback about your assumptions. Hi Thierry, first of all my intent is not to be confrontational. I can see you’re passionate about this, and I just had a chance to read your Smashing article and get some more context. Even if you didn’t have an engineering background, you are/were working with a company (like other major tech companies) who is constantly biting at the bit to try to do something, ANYTHING they can think of to increase efficiency and better compete. Do you tell your shareholders we’re going to do “more of the same” in order to meet their revenue goals? This reality is more of the macro picture of why the backend engineers now do CSS, and why the front end has changed so much in recent years. That’s not to say I think change is bad, or a lot of good hasn’t happened. There’s been a ton of neat stuff. On the other hand, some of the ideas not so much… in my opinion especially around CSS. Of course I care about performance. I actually think the problem you’re trying to solve has resulted in part by popularity of component based development which has meant a lot of CSS gets repeated. Personally, I like to utilize a combination of BEM or CSS modules, along with a healthy amount of the dreaded global CSS. I have worked on pretty large codebases with multiple engineers editing css (none as large as Yahoo I admit, but there aren’t many that are). It is a challenge, but with a good disciplined system and everyone involved having a good understanding of the box model, specificity, etc. I don’t think it’s much more bloated than Atomic CSS. Don’t forget the amount of code you’re adding to the markup. Maybe there is some savings if you get everyone doing the super minimalist shorthand version, but what’s the trade off? The markup is terribly hard to read, it’s awkward to type, no css linting, no emmet (ahh some stop the press right here!), no use of the vast armada of css frameworks, libraries, online pattern libraries, css from old projects, etc. Unless/until you can change the whole industry to use this, it will make my life and many other’s life more difficult when they have to encounter it. Sorry if that sounds negative, but I think there are other and better ways to save 20 or so k besides this. I’m not against you, but I have a right to my opinion just as you do. I despair. What on Earth is happening in the world of Web? It’s as if everybody has gone insane! Do these guys ever do any serious work? Large projects are not those with lots of style. Large projects are those with lots of content, styled consistently, delivering a brand. What crazy authors are changing the way they use HTML every new project? Not me. For example, my beloved, trusty, reusable form module that spews out the HTML for my forms so I don’t have to write HTML forms manually. It’s doing the hard work for me, reducing errors, ensuring accessibility, etc. I’m sure I’m not the only web professional that relies on components for generating their HTML, many people edit mark down and not HTML, for example. Anyway, do I edit this HTML if I want a form with a different design? No! Why would I do that? That would be totally insane! If I wanted to use atomic CSS, I would have to do exactly that. That’s a major waste of time, and an inappropriate use of HTML and CSS. If you’re considering atomic CSS, you’re doing something wrong, and about to make it worse. I think the reason for the big disconnect is that it depends if you are more of a designer or more of a frontend developer. When I came across this topic a year ago, I also didn’t understand the difference between this and inline styes. Especially since I was the only designer on the team. However, as my skillset changed, and I started to do more on the programming side, I began to understand how beneficial ACSS is. In addition, I started to work on larger teams and more complex projects.
https://css-tricks.com/lets-define-exactly-atomic-css/?utm_source=CSS-Weekly&utm_campaign=Issue-260&utm_medium=web
CC-MAIN-2017-34
refinedweb
5,859
62.98
NAME Create an event pair. SYNOPSIS #include <zircon/syscalls.h> zx_status_t zx_eventpair_create(uint32_t options, zx_handle_t* out0, zx_handle_t* out1); DESCRIPTION zx_eventpair_create() creates an event pair, which is a pair of objects that are mutually signalable. The signals ZX_EVENTPAIR_SIGNALED and ZX_USER_SIGNAL_n (where n is 0 through 7) may be set or cleared using zx_object_signal(), which modifies the signals on the object itself, or zx_object_signal_peer(), which modifies the signals on its counterpart. When all the handles to one of the objects have been closed, the ZX_EVENTPAIR_PEER_CLOSED signal will be asserted on the opposing object. The newly-created handles will have the ZX_RIGHT_TRANSFER, ZX_RIGHT_DUPLICATE, ZX_RIGHT_READ, ZX_RIGHT_WRITE, ZX_RIGHT_SIGNAL, and ZX_RIGHT_SIGNAL_PEER rights. Currently, no options are supported, so options must be set to 0. RIGHTS TODO(ZX-2399) RETURN VALUE zx_eventpair_create() returns ZX_OK on success. On failure, a (negative) error code is returned. ERRORS ZX_ERR_INVALID_ARGS out0 or out1 is an invalid pointer or NULL. ZX_ERR_NOT_SUPPORTED options has an unsupported flag set (i.e., is not 0). ZX_ERR_NO_MEMORY Failure due to lack of memory. There is no good way for userspace to handle this (unlikely) error. In a future build this error will no longer occur.
https://fuchsia.dev/fuchsia-src/reference/syscalls/eventpair_create
CC-MAIN-2020-29
refinedweb
189
59.19
28 September 2012 07:37 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The refineries have a combined capacity of 7.26m bbl/day, which accounts for 72% of the total capacity of Sinopec has ramped up production at its 160,000 bbl/day Yangzi refinery to above its capacity, with current run rate at 101%, up by seven percentage points from two weeks ago. PetroChina, on the other hand, has raised run rates at its 260,000 bbl/day Lanzhou refinery by six percentage points from two weeks ago to 67% currently, according to C1 Energy, an ICIS service in China. In October, the average operating rates of the 35 major refineries in China are expected to rise to 84-86% as Sinopec facilities are due to come back on stream, market sources said. Sinopec’s 260,000 bbl/day Higher refinery operating rates brings down the cost of feedstocks
http://www.icis.com/Articles/2012/09/28/9599377/run-rates-at-chinas-35-refineries-average-82.7-in-late-september.html
CC-MAIN-2013-48
refinedweb
150
56.79
strrchr - string scanning operation Synopsis Description Return Value Errors Examples Finding the Base Name of a File Application Usage Rationale Future Directions See Also #include <string.h> char *strrchr(const char *s, int c); The strrchr() function shall locate the last occurrence of c (converted to a char) in the string pointed to by s. The terminating null byte is considered to be part of the string. Upon successful completion, strrchr() shall return a pointer to the byte or a null pointer if c does not occur in the string. No errors are defined. The following sections are informative. The following example uses strrchr() to get a pointer to the base name of a file. The strrchr() function searches backwards through the name of the file to find the last / character in name. This pointer (plus one) will point to the base name of the file. #include <string.h> ... const char *name; char *basename; ... basename = strrchr(name, /) + 1; ... None. None. None. strchr() , .
http://www.squarebox.co.uk/cgi-squarebox/manServer/usr/share/man/man3p/strrchr.3p
crawl-003
refinedweb
162
65.32
DEBSOURCES Skip Quicknav sources / git / 1:2.20.1-2+deb10u3 / graph #ifndef GRAPH_H #define GRAPH_H #include "diff.h" /* A graph is a pointer to this opaque structure */ struct git_graph; /* * Called to setup global display of line_prefix diff option. * * Passed a diff_options structure which indicates the line_prefix and the * file to output the prefix to. This is sort of a hack used so that the * line_prefix will be honored by all flows which also honor "--graph" * regardless of whether a graph has actually been setup. The normal graph * flow will honor the exact diff_options passed, but a NULL graph will cause * display of a line_prefix to stdout. */ void graph_setup_line_prefix(struct diff_options *diffopt); /* * Set up a custom scheme for column colors. * * The default column color scheme inserts ANSI color escapes to colorize * the graph. The various color escapes are stored in an array of strings * where each entry corresponds to a color, except for the last entry, * which denotes the escape for resetting the color back to the default. * When generating the graph, strings from this array are inserted before * and after the various column characters. * * This function allows you to enable a custom array of color escapes. * The 'colors_max' argument is the index of the last "reset" entry. * * This functions must be called BEFORE graph_init() is called. * * NOTE: This function isn't used in Git outside graph.c but it is used * by CGit () to use HTML for colors. */ void graph_set_column_colors(const char **colors, unsigned short colors_max); /* * Create a new struct git_graph. */ struct git_graph *graph_init(struct rev_info *opt); /* * Update a git_graph with a new commit. * This will cause the graph to begin outputting lines for the new commit * the next time graph_next_line() is called. * * If graph_update() is called before graph_is_commit_finished() returns 1, * the next call to graph_next_line() will output an ellipsis ("...") * to indicate that a portion of the graph is missing. */ void graph_update(struct git_graph *graph, struct commit *commit); /* * Determine if a graph has finished outputting lines for the current * commit. * * Returns 1 if graph_next_line() needs to be called again before * graph_update() should be called. Returns 0 if no more lines are needed * for this commit. If 0 is returned, graph_next_line() may still be * called without calling graph_update(), and it will merely output * appropriate "vertical padding" in the graph. */ int graph_is_commit_finished(struct git_graph const *graph); /* * Output the next line for a graph. * This formats the next graph line into the specified strbuf. It is not * terminated with a newline. * * Returns 1 if the line includes the current commit, and 0 otherwise. * graph_next_line() will return 1 exactly once for each time * graph_update() is called. * * NOTE: This function isn't used in Git outside graph.c but it is used * by CGit () to wrap HTML around graph lines. */ int graph_next_line(struct git_graph *graph, struct strbuf *sb); /* * Return current width of the graph in on-screen characters. */ int graph_width(struct git_graph *graph); /* * graph_show_*: helper functions for printing to stdout */ /* * If the graph is non-NULL, print the history graph to stdout, * up to and including the line containing this commit. * Does not print a terminating newline on the last line. */ void graph_show_commit(struct git_graph *graph); /* * If the graph is non-NULL, print one line of the history graph to stdout. * Does not print a terminating newline on the last line. */ void graph_show_oneline(struct git_graph *graph); /* * If the graph is non-NULL, print one line of vertical graph padding to * stdout. Does not print a terminating newline on the last line. */ void graph_show_padding(struct git_graph *graph); /* * If the graph is non-NULL, print the rest of the history graph for this * commit to stdout. Does not print a terminating newline on the last line. */ int graph_show_remainder(struct git_graph *graph); /* * Print a commit message strbuf and the remainder of the graph to stdout. * * This is similar to graph_show_strbuf(), but it always prints the * remainder of the graph. * * If the strbuf ends with a newline, the output printed by * graph_show_commit_msg() will end with a newline. If the strbuf is * missing a terminating newline (including if it is empty), the output * printed by graph_show_commit_msg() will also be missing a terminating * newline. * * Note that unlike some other graph display functions, you must pass the file * handle directly. It is assumed that this is the same file handle as the * file specified by the graph diff options. This is necessary so that * graph_show_commit_msg can be called even with a NULL graph. */ void graph_show_commit_msg(struct git_graph *graph, FILE *file, struct strbuf const *sb); #endif /* GRAPH_H */
https://sources.debian.org/src/git/1:2.20.1-2+deb10u3/graph.h/
CC-MAIN-2020-50
refinedweb
745
64.71
In the prior lesson (6.6 -- Internal linkage), we discussed how internal linkage limits the use of an identifier to a single file. In this lesson, we’ll explore the concept of external linkage. internal linkage external linkage An identifier with external linkage can be seen and used both from the file in which it is defined, and from other code files (via a forward declaration). In this sense, identifiers with external linkage are truly “global” in that they can be used anywhere in your program! Functions have external linkage by default In lesson 2.7 -- Programs with multiple code files, you learned that you can call a function defined in one file from another file. This is because functions have external linkage by default. In order to call a function defined in another file, you must place a forward declaration for the function in any other files wishing to use the function. The forward declaration tells the compiler about the existence of the function, and the linker connects the function calls to the actual function definition. forward declaration Here’s an example: a.cpp: main.cpp: The above program prints: Hi! In the above example, the forward declaration of function sayHi() in main.cpp allows main.cpp to access the sayHi() function defined in a.cpp. The forward declaration satisfies the compiler, and the linker is able to link the function call to the function definition. sayHi() main.cpp a.cpp If function sayHi() had internal linkage instead, the linker would not be able to connect the function call to the function definition, and a linker error would result. Global variables with external linkage Global variables with external linkage are sometimes called external variables. To make a global variable external (and thus accessible by other files), we can use the extern keyword to do so: extern Non-const global variables are external by default (if used, the extern keyword will be ignored). Variable forward declarations via the extern keyword To actually use an external global variable that has been defined in another file, you also must place a forward declaration for the global variable in any other files wishing to use the variable. For variables, creating a forward declaration is also done via the extern keyword (with no initialization value). Here is an example of using a variable forward declaration: In the above example, a.cpp and main.cpp both reference the same global variable named g_x. So even though g_x is defined and initialized in a.cpp, we are able to use its value in main.cpp via the forward declaration of g_x. g_x Note that the extern keyword has different meanings in different contexts. In some contexts, extern means “give this variable external linkage”. In other contexts, extern means “this is a forward declaration for an external variable that is defined somewhere else”. Yes, this is confusing, so we summarize all of these usages in lesson 6.11 -- Scope, duration, and linkage summary. Warning If you want to define an uninitialized non-const global variable, do not use the extern keyword, otherwise C++ will think you’re trying to make a forward declaration for the variable. Although constexpr variables can be given external linkage via the extern keyword, they can not be forward declared, so there is no value in giving them external linkage. Note that function forward declarations don’t need the extern keyword -- the compiler is able to tell whether you’re defining a new function or making a forward declaration based on whether you supply a function body or not. Variables forward declarations do need the extern keyword to help differentiate variables definitions from variable forward declarations (they look otherwise identical): File scope vs. global scope The terms “file scope” and “global scope” tend to cause confusion, and this is partly due to the way they are informally used. Technically, in C++, all global variables have “file scope”, and the linkage property controls whether they can be used in other files or not. Consider the following program: global.cpp: Variable g_x has file scope within global.cpp -- it can be used from the point of definition to the end of the file, but it can not be directly seen outside of global.cpp. global.cpp Inside main.cpp, the forward declaration of g_x also has file scope -- it can be used from the point of declaration to the end of the file. However, informally, the term “file scope” is more often applied to global variables with internal linkage, and “global scope” to global variables with external linkage (since they can be used across the whole program, with the appropriate forward declarations). The initialization order problem of global variables Initialization of global variables happens as part of program startup, before execution of the main function. This proceeds in two phases. main The first phase is called static initialization. In the static initialization phase, global variables with constexpr initializers (including literals) are initialized to those values. Also, global variables without initializers are zero-initialized. static initialization The second phase is called dynamic initialization. This phase is more complex and nuanced, but the gist of it is that global variables with non-constexpr initializers are initialized. dynamic initialization Here’s an example of a non-constexpr initializer: Within a single file, global variables are generally initialized in order of definition (there are a few exceptions to this rule). Given this, you need to be careful not to have variables dependent on the initialization value of other variables that won’t be initialized until later. For example: This prints: 0 5 Much more of a problem, the order of initialization across different files is not defined. Given two files, a.cpp and b.cpp, either could have its global variables initialized first. This means that if the variables in a.cpp are dependent upon the values in b.cpp, there’s a 50% chance that those variables won’t be initialized yet. b.cpp Dynamic initialization of global variables causes a lot of problems in C++. Avoid it whenever possible. Quick summary We provide a comprehensive summary in lesson 6.11 -- Scope, duration, and linkage summary. Quiz time Question #1 Show Solution Global variables have global scope (aka. file scope), which means they can be accessed from the point of declaration to the end of the file in which they are declared. Global variables have static duration, which means they are created when the program is started, and destroyed when it ends. Global variables can have either internal or external linkage, via the static and extern keywords respectively. Hi :) See the following program: I'm dynamically allocating an array in generate() and accessing it from main(), but the array gets destroyed (I think) at the end of generate(), so I can't access it from main(). How can I make the array accessible from main(), while still dynamically allocating it from generate()? P.S. I've decided to take a break from learning C++ for a while, mainly because I don't have enough free time at the moment (school), but also because I need to pick up some experience with the language (I've read too many lessons without writing a single line of code). I've started working on a personal project (github.com/glibg10b/2DBlocks/). I'll continue learning C++ when the next vacation starts, but until then, I'll use the small amount of free time I have to work on this project (and maybe a few other projects). It's pretty fun :D void generate(World world) { world.grid = new Tile[world.xLength * world.yLength]{}; } In this function u need to pass object as an address!!! void generate(World &world) { world.grid = new Tile[world.xLength * world.yLength]{}; } When u pass direct object, u are going to create new object which is copy of previous object(learn about copy constructor for more details on object passing as a reference); what is difference between static initialization and dynamic initialization? When you initialized a variable's value in source code, it's static initialization. Like - But when you assign a value to the a variable at runtime(when the program is running, not compiling time), like ask user to enter a value, then it's dynamic initialization, since it's the variable's value was not defined before. Like - It is advisable not to use dynamic initialization is global variable, but using it in local variable is okay. as far as my knowlegde goes, in the second example x is initialized in the second line, so this is still a static initialization. The third line is just an assignment Uuh.. your statement makes sense. I can't find it now but I saw somewhere in learncpp saying this. That's why I wrote that. I maybe wrong. So a kind forgiving vision will be expected & fixing my explanation will be appreciated :) It is indeed not exactly right. In your example of dynamic initialization, you still initialize it statically (with 0) and then assign a value to it. We speak of static initialization if a variable is initialized with a value we know at compile time. If the initialization value is only known at runtime (because it is dependent on other factors) we call it dynamic initialization: Hmm, nice explanation! Appreciate your understanding :) Why can constexpr variables not be forward declared? Because the compiler needs to know the value of a constexpr variable. A forward declaration doesn't provide this. The linker could figure this out, but that doesn't run until after the compiler. Thank you for the answer @Chayim "Although constexpr variables can be given external linkage via the extern keyword, they can not be forward declared, so there is no value in giving them external linkage." so what if we have a constant variable in add.cpp that is a compile-time constant and so defined with constexpr but is needed in main.cpp ? Move it to a header file and #include it wherever you need it. Why can't constexpr variables be forward declared? Because the compiler needs to know the value of a constexpr variable. A forward declaration doesn't provide this. The linker could figure this out, but that doesn't run until after the compiler. Oooh, thanks for that insight! We can't use the global const variables with external linkage in another file if we can't declare them forward in files where we want to use them. Even though we can assign the external linkage to contsexpr global variables we can't use such constexpr variables in another files so it seems that giving them external linkage is pretty pointless or useless. And I expected compiler will complain when we give constexpr variables external linkage but the compiler didn't. Please illuminate me with some cases where giving external linkage to constexpr variables is useful. After further digging I think I found a way to use constexpr variables with external linkage in another file without taking the help from header file or preprocessing directive. But I am not sure if it is the good practise or my code is buggy. Here it is: link.cpp: and when I run this code the outputs are as the following: see? We can use the g_z variable which is constexpr along with external linkage in main.cpp. I forward declared the g_z with and keyword in main.cpp. Is this the good practise? or it is one of the undefined behaviors? iirc this is well-defined, but now main's `g_z` is not usable in constant expressions. If you want a variable to be `constexpr`, its definition has to be visible (ie. defined in a header or in the source file that uses it). Therefore my understandings of global variable with constexpr are: [Please correct me If I am wrong] 01. Global variables with constexpr have only internal linkage 02. And they are only avaiable within the file scope.(using Header file might give us option to use them somewhere.) 03. Using 'static' and 'extern' keyword with Global variables with constexpr are totally pointless. This unit of lesson shows the glimpse of complexity in C++, though I like the complexity which gives the programmers freedom.It also shows the beauty and flexibility of C++. I think most programmers don't like C++ because it has too many rules and it gives programmers absolute freedom, though we like freedom in personal our personal life but not in programming world. output:99 hi . i run this program on visual studio why output is 99 ? must be 09 The crucial idea in this code is function B(); because it is the one that has a literal value (9). BB variable is initialized with B() function which is 9. AA variable is initialized with A() function which uses BB variable which is 9. So AA variable is nothing but BB variable which is 9. hope it helps... I don't know the reason why @winterson is getting "99", but I wanna join in because I think you're wrong. `AA` and `BB` are zero-initialized during static initialization (Because they're not initialized with literals). During dynamic initialization, global variables are initialized in the order of their definition. That is, `AA` is initialized first with the value of `BB`, which is still 0 at this point. I suspect @winterson's compiler is initializing `AA` and `BB` at compile-time already, which breaks the initialization order (I don't think this is allowed to happen). Either way, global variables are evil and should be avoided, this is a good example. Sorry for the mess!! Thank you very much for correction. Since constexpr can't be forward declared does that mean we can never use it everywhere in our program? Is it only limited to the file it is initialized in? Correct. But `constexpr` variables have internal linkage, so you can define them in headers. a way from 'constexpr' case .. which is better for multi-files-variable-access, to define variables in a header, or to use 'extern' global variables? Is there any conditions of using either? If the variable can be `constexpr`, make it `constexpr`. It's likely faster and safer. Thank you for your time. You gave a choice of defining a constexpr variable in a header file. I was wondering, about not to use the 'external linkage 'and just stick to headers! The next lesson has cleared anything..Thanx. I am a little confused. As far as I understand: Static initialization include the following: Dynamic initialization include the following: Am I right? All of your examples are already initialized during static initialization, because you're initializing the variables with literals. The first snippet in section "The initialization order problem of global variables" shows when dynamic initialization is needed. The compiler doesn't know what `init` will return (In practice, compilers are smart enough to figure it out, but let's assume a dumb compiler), so `g_something` is zero-initialized during static initialization and gets the correct value (5) during dynamic initialization. extern const int g_y { 3 }; // const globals can BE defined as extern, making them external I think "be" was missing! thanks! "...and the linker connects the function calls to the actual function definition." Does this happen when program is running in the memory? or does this happen when a program is processed via the linker? Both answers are valid. If your compiling only your code, or are only using static libraries, the linker can connect everything right after compilation. If you use shared libraries, functions will be connected when you launch the program. Thank you for the lesson and all your hard work! In the last part you mentioned "Given two files, a.cpp and b.cpp, either could have its global variables initialized first". Is there any way to set the order of compilation, such as compiling a.cpp first and the b.cpp? No. Even if your compiler has a way of specifying the compilation order, it's not standardized and your code will break on another system. Hello,I've question look at the code below: in exp.cpp in main.cpp: I've stated my question in the comment. could you pls tell me why can't I assign it in global scope but can do it in main function ? thanks Why can't constexpr variables be forward declared? Is there a reason behind this restriction? Also, how does one remember which one (among const and constexpr) is allowed and which is not? Seems kind of arbitrary. > Why can't constexpr variables be forward declared? Is there a reason behind this restriction? I don't know the reason honestly. My guess is that, because it's not necessary to forward declare constexpr variables (ie. code can be rewritten without the forward declaration), it's not allowed, so that it's easier for the compiler to evaluate constant expressions. > Also, how does one remember which one (among const and constexpr) is allowed and which is not? You can use `constexpr` for constant expressions, ie. literals and entities marked as `constexpr`. `constexpr` functions and types aren't covered on learncpp, so we're limited to literals and other constexpr variables. In the initial explanation of constexpr is was said that "To help provide more specificity, C++11 introduced new keyword constexpr, which ensures that a constant must be a compile-time constant:" Forward declarations are somewhat incompatible with that notion, since they are dealt with _after_ compilation (at the linkage stage). P.S. That quote should say 'introduced the keyword constexpr'. It's section 4.13 P.S.S. From this page "Variables forward declarations do need the extern keyword to help differentiate variables definitions from variable forward declarations (they look otherwise identical):" -> "Variable forward declarations do need the extern keyword to help differentiate variable definitions from variable forward declarations (they look otherwise identical):" Thanks for pointing out the typo, I fixed it. My first thought was, yeah, that makes perfect sense. Then again, we do have forward declarations for constexpr functions (Not covered on learncpp). Found a typo. Line 4 of the quick summary has an open parentheses at the end of the comment. Possibly an unfinished thought or just a typo? Whatever it was, it's gone now. Thanks! Hi, I'm having some difficulties understanding the "constexpr" specifier in general. In a warning box of this lesson I can read: Doesn't this conflicts with the code that is written in the Quick summary section? No conflict there. is allowed, but not useful. I found a small typo: "Technically, in C++, all global variables in C++ have “file scope”, ..." The second "C++" is redundant. "This phase is is more complex and nuanced, ..." another one. Fixed. Thanks! I found another small typo you might want to correct for improved readability. In section "The initialization order problem of global variables", 3rd paragraph, You wrote "This phase is is more complex...". Should be "This phase is more complex..." Thanks! This issue has has been fixed. In the section "Variable forward declarations via the extern keyword" I think there is an error in an example Instead of: // non-constant int g_x; // variable definition (can have initializer if desired) extern int g_x; // forward declaration (no initializer) // constant extern const g_y { 1 }; // variable definition (const requires initializers) extern const g_y; // forward declaration (no initializer) There should be // constant extern const int g_y { 1 }; // variable definition (const requires initializers) extern const int g_y; // forward declaration (no initializer) Yep, thanks! Hello, I am confused by title "The static initialization order problem": While reading the following content, I thought more about a title like "The problem while initializing static variables". Indeed, the problem concerns the dynamic initialization of static variables rather than their static initialization? Good catch! static initialization isn't the problem, dynamic initialization is. Title updated to "The initialization order problem of global variables". Been learning cpp now for around 4 years, mostly thanks to this site I think I am reasonably competent now, but I still find it incredibly useful reference material for stuff that I do not do very often. I have started using a global stream for my logs as passing the object to every single class just seemed needlessly messy and the built in streams could not be used because I a writing a daemon, but I was getting linker errors as I had not forward declared my variable where I initialised it in main. I still have it declared extern in my header file though, it seems to work, but is that wrong? Declare it `extern` in the header, define it once in a single source fail. Thanks for the confirmation. I'm confused about "static variables" term in section "The static initialization order problem". g_x— is a static variable? In this context, "static variable" means a variable with static duration. Since all globals have static duration, g_x is indeed a static variable. At the beginning of this lesson, it says : "In the prior lesson (8.5b -- Non-static member initialization)". Just to let you know, if you want to put the correct one (6.6 — Internal linkage). Link updated, thanks! Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/external-linkage/
CC-MAIN-2021-17
refinedweb
3,560
56.45
boundaries.week() function boundaries.week() is experimental and subject to change at any time. boundaries.week() returns a record with start and stop boundary timestamps of the current week. By default, weeks start on Monday. Function type signature (?start_sunday: bool, ?week_offset: int) => {stop: time, start: time} Parameters start_sunday Indicate if the week starts on Sunday. Default is false. When set to false, the week starts on Monday. week_offset Number of weeks to offset from the current week. Default is 0. Use a negative offset to return boundaries from previous weeks. Use a positive offset to return boundaries for future weeks. Examples - Return start and stop timestamps of the current week starting on Monday - Return start and stop timestamps of the current week starting on Sunday - Query data from the current week - Query data from last week Return start and stop timestamps of the current week starting on Monday import "experimental/date/boundaries" option now = () => 2022-05-10T00:00:00.00001Z boundaries.week( )// Returns {start: 2022-05-09T00:00:00.000000000Z, stop: 2022-05-16T00:00:00.000000000Z} Return start and stop timestamps of the current week starting on Sunday import "experimental/date/boundaries" option now = () => 2022-05-10T10:10:00Z boundaries.week( start_sunday: true, )// Returns {start: 2022-05-08T00:00:00.000000000Z, stop: 2022-05-14T00:00:00.000000000Z} Query data from the current week import "experimental/date/boundaries" thisWeek = boundaries.week() from(bucket: "example-bucket") |> range(start: thisWeek.start, stop: thisWeek.stop) Query data from last week import "experimental/date/boundaries" lastWeek = boundaries.week(week_offset: -1) from(bucket: "example-bucket") |> range(start: lastWeek.start, stop: lastWeek.
https://docs.influxdata.com/flux/v0.x/stdlib/experimental/date/boundaries/week/
CC-MAIN-2022-40
refinedweb
267
53.98
Seam conversations have certain rules that you need to be aware of when using them. This article came about because for the last couple of years, the same questions have been asked on the Seam forums regarding conversations. It is also a couple of issues that cropped up while I was working on the Seam vs. Spring Web Flow articles. Some of the problems are uncannily similar with similar solutions, so parts of this series may be of interest to non-Seam users. Additionally, it seems like a lot of this stuff will also apply to the conversational pieces of JSR 299 – Contexts and Dependency Injection which will be a part of JEE 6. Conversational Fundamentals Let’s start with a fairly descriptive and steady paced description of what conversations are and what they are not. Some of these behaviors are probably more figurative that literal. This mainly applies to Seam, but is also similar to CDI. Conversations in Seam are like buckets that hold conversational data. A user session has a list of conversation contexts each identified by a conversation Id. A conversation is either long running or temporary and even when you are not in a long running conversation, you are using a temporary conversational context or bucket. The only difference between a long running conversation and a temporary conversation is the boolean longRunning flag on the conversation instance. When you start a conversation, all that happens is the longRunning flag on the conversation is set to true. When you end the conversation, the longRunning flag is cleared. There is no destruction of conversational objects and no clearing out of the conversation. Abandoned long running conversations sit in the conversation list until they time out. Note that in JCDI (JSR 299), the long running flag has been renamed to a isTransient flag on the conversation. Components that are scoped to the conversation are still held in the conversation context regardless of whether it is long running or temporary. The only difference with a long running conversation is that the id for the conversation is propagated from one page to the next. When the id is propagated, that same conversation ‘bucket’ is used by the next page and the objects that were in the previous page are accessible in the new page. In each request, Seam determines if the conversation is long running, and if so, it passes the conversation id to the next page as a parameter. Obviously, this propagation only takes place with faces requests, or GET requests that have special handling like manual conversation propagation or you are using the Seam JSF controls that provide GET requests with automatic conversation propagation. When rendering a new page, at some point Seam will need to access the conversational context. It does this by looking to see if the request contained a conversation id and if so, looking up the existing conversation context instance for that id. Otherwise, it obtains a new conversation instance with a new conversation Id. When there is no long running conversation, no id is propagated so each page obtains a new conversation instance and Id. When we start a long running conversation Seam will automatically propagate the conversation id from one page to the next for us which is how we write applications with multiple pages using the same conversation. When you end a conversation, the longRunning flag is set to false and Seam no longer propagates the id from one page to the next. However, when you end a conversation on one page, Seam will still propagate the conversation to the next page one last time. This allows us to carry things like faces messages and any other data over the conversation boundary. This next page gets to use the same conversation instance that just finished outside of the conversation boundary. It has a number of benefits as well as some important consequences that can cause many problems that are tricky to track down. If you end your conversation and set the before-redirect attribute to true the conversation is ended before the redirect so the conversation id is not propagated and the new page starts with a fresh conversation context. The problem with this is that since there is no propagation of the conversation, faces messages (and any other information you wanted to carry to the new page) is not propagated either. This is to be expected since you explicitly specified that you wanted to end the conversation before the new page. There are also times when Seam will propagate the conversation from one page to the next when it is not long running. If a redirect is taking place, then Seam promotes the conversation to long running temporarily so the conversation id parameter is passed to the redirect. The conversation is then demoted again to a temporary conversation. This allows items such as faces messages to propagate so you can show messages even after a redirect. One useful way of seeing which conversation you are using is to add Conversation = #{conversation.id} to your template so you can see what conversation id the page is using. This way you can see whether or not the conversation has propagated and whether you are using the same value from the previous page. If the conversation id on two pages is the same, they are using the same conversation instance and sharing data. Hopefully, this section has provided enough of an overview into Seam conversations, cleared some of the misconceptions up and will make understanding some of the conversational pitfalls easier. Dirty Data When you end a conversation, the conversation instance contains multiple pieces of data. Let’s take the scenario of editing a widget, and clicking save or cancel and being taken back to the widget view page. Our Seam page uses a factory method to generate the #{widget} instance from our WidgetHome bean. We may edit the instance, and post back the changes, and then decide to cancel our changes. At this point, our widget in the conversation is dirty, it has changes made to it that we have cancelled. If we do nothing and just go back to the view page, the conversation will be re-used since we propagate that ended conversation id over one last time. The #{widget} references in the view page will refer to our existing dirty instance in the re-used conversation. Since the variable exists in the conversation already, Seam won’t call the factory method to get a fresh instance. As a result our view page shows the dirty instance with all our modifications. This problem can be solved in a couple of different ways, each with its own problems. The simplest is to use before-redirect=true when ending the conversation. This way our view page won’t use the dirty data from the ended conversation and it starts with a fresh conversation. This may be a problem though if you are passing the widgetId parameter from the previous page. Pages.xml lets you easily add parameters to redirects, but pageflows don’t. It also means that you won’t be able to pass any other data over such as a message to say you have cancelled changes. Another similar, but more forceful, way of doing this is just to have a non-faces ‘cancel’ link on your edit page that takes you straight to the edit page with a GET request and passes in the widget Id. In this scenario, the conversation is abandoned since we used a link and it will not propagate the conversation or the associated dirty data over with it, nor can you pass any cancellation messages over. The other method is to let the view page re-use the conversation, but when the user cancels the changes, actually refresh the entity that has been changed. You create a cancel method on the entity home bean which is called when the user cancels their changes and it will refresh the entity so it is no longer dirty. This has the benefit of causing minimal disruption, but if you have a long chain of objects that ended up dirty, making sure you refresh them all can be tricky. Stale Data The stale data problem is similar to the dirty data problem except the problem occurs within the same conversation and without ending it. If we have some data in a conversation that depends on other values in the conversation, when those values change, we have to make sure we update our data, otherwise it will become stale. For example a paginated list of sales orders from on an EntityQuery means that we need to get a new set of results when we click next or previous. However, if the results of the query are outjected from the query bean and referenced as #{orderList} in the JSF page, then we will see the stale data problem. The first time we enter the page, the variable #{orderList} doesn’t exist, so Seam calls the factory for #{orderList} which returns the list of the first 10 results. Our datatable shows the list of results using the variable orderlist. <h:dataTable <!-- Columns Here --> </h:dataTable> The user clicks next in the paginator which does a postback, increases the firstResult value and causes a refresh on the result list referenced by the entity query to show the next 10 results. The page is rendered but the displayed results are exactly the same. We are still looking at the first 10 rows. Why? Because the orderList context variable is used by the view to obtain the list of orders. When the page is rendered the second time, JSF looks for the value of #{orderList} and finds it already exists in the conversational context even though it contains the first 10 results, and not the second 10. Seam has no reason to call the factory method to obtain the latest values. In essence, we have two sets of results, the original set which is referenced by the orderList seam variable, and the current set which is the correct list of results and is held by the query bean. We have two ways of fixing this problem. The first is to change the value our data table is referencing so it is always referencing the result set on the query bean directly. <h:dataTable <!-- Columns Here --> </h:dataTable> With this code, there is no El expression used that can become stale. When the page is re-rendered the table will get the results from the order query directly each time ensuring that the most up to date values are used. This is the easiest solution but it cannot be used if you are using the DataModel annotation since Seam requires you to use the outjected data model variable. In such cases refer to the second solution which is to invalidate the orderList variable when we refresh the search results. This is fairly easy, but requires us to override the refresh method in the entity query. When we refresh the list of orders, we simply remove the #{orderList} context variable. i.e. @Override public void refresh() { super.refresh(); Contexts.removeFromAllContexts("orderList"); } This means that when the user causes a refresh of the query data, the variables referencing that data will be ejected from all contexts and the next time that value is requested in a JSF page, the appropriate Seam factory will be called to get the most up to date result set. Starting a conversation Even starting a conversation can be a problem. In most cases, we utilize the join="true" attribute to gloss over the fact that we are going into a page that requires a conversation with or without a conversation already started. When we hit our target page, we know that we will be in a conversation, either a newly started one, or an existing conversation. We may not care which except that not considering our conversation start and end points has side effects. Using the join attribute is not a substitue for thinking about conversation demarcation. First is the issue of old data where a new page may re-use data from the last page because they share the conversation. For example, we are viewing a widget and the widget instance is loaded into the temporary conversation. 10 minutes later, we click edit which takes us to the widget edit page and starts a long running conversation. The edit page needs an instance of a widget which it already has from the view page, but this instance of a widget is 10 minutes old and has been edited by another user since you loaded the view page and therefore, you need to do a refresh. This problem arose without us even starting a long running conversation in the view page. The answer here is to ensure that you are always starting with a fresh conversation instance when you go in to the edit page. The easiest way to do that is to use propagation="none" on the link to edit the widget, or just use a plain old GET link. If a page is meant to start a conversation and also start a pageflow then you cannot enter that page with an existing conversation. If you do, the page will join the existing conversation and the pageflow will not start. Pageflows can only be started with a fresh conversation. Note that initially a page may be simple enough that you don’t need a pageflow and you could ignore conversation demarcation, but if you later start a pageflow on that page, you could end up with all sorts of headaches as invoking that page from different places may or may not start the pageflow depending on whether the page you were on previously had a long running conversation. Menus Always consider your menus and their links and what pages they will be used in. They could be called from pages where there may or may not be a long running conversation. Consider whether that conversation is propagated or not. Typically (and luckily) most links in menus are to top level items and thus conversation propagation is never really required which means you can just never propagate it. Propagation is mostly task centric and therefore is more likely to appear in the main page itself rather than a general application wide menu. One other problem I found was with rich menu items which only allow an action on the menu item. Typically to end or demarcate a conversation, you would need an s:link or s:button since only these Seam specific controls were are aware of the concept of conversation propagation. Since our menu is shared across all pages if we were in a pageflow, we could end up with Illegal Navigation issues since we don’t account for global menu navigation in our pageflows. Alternatively, we might be in a conversation and calling a page that starts a new conversation with a pageflow so we need to end the conversation before we get there so we can start the new conversation and also the new pageflow. In a nutshell, we need to end any current conversation then re-direct to a new page where we will start a new conversation. We also need to be able to do this from a JSF action since some menu components require actions instead of allowing you to add links. One solution to this is to use a navigator component that will perform these tasks for us and we just pass in the view-id that we want to go to. @Name("navigator") @Scope(ScopeType.STATELESS) public class Navigator { public void gotoView(String view) { if (Conversation.instance().isLongRunning()) { Conversation.instance().end(true); } Redirect.instance().setViewId(view); Redirect.instance().execute(); } } With this, we can define our action methods as #{navigator.gotoView("/startBookingProcess")} and when that menu item is selected, it will end the conversation and perform the redirect so on our new page we can start a new conversion and pageflow. Conversational Best Practices These are best practices that I’ve found working with Seam and conversations in general. Obviously, it’s a personal thing, and some people may disagree with me on them, but these rules have served me and my team well. Always determine where a page fits in terms of conversations and always treat that page the same way. For example, edit and view pages I tend to isolate from other conversations. I tend to only use the temporary conversation for the view page so if you click refresh, it reloads the data which is really what you want, a refreshed view of what you are looking it. Any links to a view (or edit) page do not propagate the conversation at all. I always start conversations in pages.xml since this provides a single common place to do it. I’ve never really used the annotations since it requires knowledge of the target page to know which method you need to call. To edit a widget, with pages.xml you can just go to /widgetEdit.seam?widgetId=234 as opposed to calling a specific method annotated with @Begin. Hope this has helped guide you through some of the complexities of conversations in Seam. Once you understand the basic principles, it makes it much easier to figure out why something isn’t working quite right, and some of these bugs relating to stale and dirty data can be subtle and sneaky. Thanks for the helpful guidelines Andy 🙂 We have use Seam at our company as well, and have found that even though conversations are quite nice conceptually, using it incorrectly can get you into a bit of trouble. In addition, we have found you have to be quite careful using SMPC with nested conversations, since even though the conversation is nested, the PC is not, so you may end up persisting things which you didn’t intend to persist. Yes, I think I’ve wrote about that issue before in one of my Seam documents, relating to the fact that multiple nested conversations use the same entity manager. However, I tend not to use nested conversations. Thanks Andy, great insight and a delightfully composed blog – I have to agree that you have to be careful using SMPC with nested conversations – its a real bugger and really gets under my skin! So from this day forward, I will use your line of thinking and no longer use nester conversations. Many thanks. Thanks alot for this wonderful sharing! I have been struggling with conversations for a while even after having implemented 2 SEAM applications and now in the midst of another. Finally, someone says it like it is. Oftentimes, the official SEAM documentation just glosses over all these ugly stuff and harps on the great functionalities that SEAM offers to the world until…poor developers like me keep banging their heads on the wall….haha. Reading your article is like the revelation. Good job, man! Many thanks. 😉
http://www.andygibson.net/blog/article/conversational-pitfalls/
CC-MAIN-2019-13
refinedweb
3,171
58.21
Guido van Rossum wrote: > > > hasattr(), getattr(), and doubtless other built-in functions > > don't accept Unicode strings at all: > > > > >>> import sys > > >>> hasattr(sys, u'abc') > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > TypeError: hasattr, argument 2: expected string, unicode found > > > > Is this a bug or a feature? I'd say bug; the Unicode should be > > coerced using the default ASCII encoding, and an exception raised if > > that isn't possible. > > Agreed. > > There are probably a bunch of things that need to be changed before > thois works though; getattr() c.s. require a string, then call > PyObject_GetAttr() which also checks for a string unless the object > supports tp_getattro -- but that's only true for classes and > instances. > > Also, should we convert the string to 8-bit, or should we allow > Unicode attribute names? Attribute names will have to be 8-bit strings (at least in 2.0). The reason here is that attributes are normally Python identifiers which are plain ASCII and stored as 8-bit strings in the namespace dictionaries, i.e. there's no way to add Unicode attribute names other than by assigning directly to __dict__. Note that keyword lookups already automatically convert Unicode lookup strings to 8-bit using the default encoding. The same should happen here, IMHO. > It seems there's no easy fix -- better address this after 2.0 is > released. Why wait for 2.1 ? -- Marc-Andre Lemburg ______________________________________________________________________ Business: Python Pages:
https://mail.python.org/pipermail/python-dev/2000-September/009252.html
CC-MAIN-2016-36
refinedweb
241
73.37
I’ve been trying to follow this tutorial about using BMFont-generated fonts to work in MonoGame which uses Extended library as a reference, but I couldn’t get the MonoGame Pipeline widget thing to automatically recognize them. This is how things should look like: And this is how things look in 3.5: There are no new files generated as a result of rebuilding. Is it something about the 3.5 and the latest Extended incompatibility? How can I make this work? Nevermind >.> I forgot to add using MonoGame.Extended.BitmapFonts; and change SpriteFont to BitmapFont. It works fine after that.
https://community.monogame.net/t/bmfont-not-recognized-by-monogame-pipeline-3-5/7359
CC-MAIN-2022-40
refinedweb
102
60.72
Python is an excellent choice for enterprises working in Big Data or machine learning-based companies. Large amounts of data and analytics have acquired great popularity in recent years. Python has quickly risen to become the programming language of choice among data scientists. Its advantages are scalability, ease of coding, and extensive library and framework collection. A Data Science course from Board infinity will help you prepare Python interview questions. Below mentioned are some common python interview questions for freshers. You can also go through these python interview questions for gaining experience and learn what to expect in the actual interview. What do you understand by PEP 8? PEP is an abbreviation for Python Enhancement Proposal. Also known as a Python Engineering Project (PEP), it is a formal design document that describes a new feature or the processes that run on it for Python. PEP 8 is essential since it offers guidance on following style guidelines while writing Python code. According to the Python website, one can contribute to the open-source community of Python by following these style requirements thoroughly. What is the definition of an Interpreted language? In contrast to written language, interpretive language executes the statements line by line rather than all at once. The term “interpreted language” refers to a computer language that may be executed without the need for a compiler. Python, Javascript, R, PHP, and Ruby are examples of such languages. In contrast to compiled programs, interpreted programs can execute directly from the source code without the requirement of an intermediary compilation procedure to be performed. What is the meaning of namespace in Python? A namespace is a naming system used to ensure that names are unique to prevent naming conflicts across applications. The global namespace holds all the names that have been specified at the level of the main application programme. Upon initialising the primary programme body in Python, it establishes a global namespace that stays in effect until the interpreter is closed down completely. What are decorators in the context of Python? The decoration is a technique for adding specific design patterns to a function without altering the function’s internal structure. Decorators are often defined before the function to enhance it. The decorator function must first be defined before one can apply it. Then you must create the function to which it is to be applied and simply place the decorator function above that function. This is accomplished by placing the @ sign before the decorator. Is it true that Python is case-sensitive? Yes. Python is a case-sensitive programming language. A typical example of case sensitivity in Python is the names of variables, which are capitalised by default. username, UserName, and UserName are all distinct variables, and using any of these names interchangeably results in an unexpected error. The same criterion applies to the names of functions. What does the term “scope” mean in Python? Every object in Python has a scope within which it may perform its functions. In Python, a scope is a section of code that contains an object that is still relevant. Namespaces are used to identify all items included inside a programme uniquely. On the other hand, these namespaces have a scope set for them, which allows you to utilize their objects without the need for a prefix. The following are a few instances of scope that may be formed during code execution in Python: 1.The term “local scope” refers to the items that are now accessible in the current function. 2.The term “global scope” refers to the items that have been accessible throughout the code execution since it began. 3.The scope of a module refers to the global objects of the current module that are available throughout the programme. 4.An outermost scope contains all of the built-in names that the programme may call. The items inside this scope are searched last to locate the name that has been referenced. How is memory handled in the Python programming language? 1.Python’s private heap area is in charge of managing the program’s memory. All Python objects and data structures are stored in a private heap accessible only to the Python interpreter. 2.The Python Interpreter is responsible for maintaining this private heap, and a programmer does not have access to it. 3.When it comes to allocating Python private heap space, Python memory management is in charge. 4.The Python garbage collector, which recycles and frees up all unnecessary memory, makes memory for the private heap area accessible to the language’s user interface. What is the meaning of PYTHONPATH? PYTHONPATH performs functions that are comparable to those of PATH. This variable instructs the Python Interpreter where to look for module files that have been imported into a program. Python source library folders and directories containing Python source code should be included in this directory structure. The Python Installer occasionally sets the PYTHONPATH variable. What is the purpose of the self keyword in Python? The term “self” refers to the instance of a class. In Python, you may use this keyword to access the properties and methods of a given class. It establishes a connection between the qualities and the arguments. The term “self” is used in various contexts and is often considered a keyword. How is Multithreading accomplished in the Python language? Multithreading is a term that refers to the execution of numerous threads at the same time. The Python Global Interpreter Lock prevents more than one thread from holding the Python interpreter simultaneously at any moment in the program. As a result, Python multithreading is accomplished via context switching. It differs from multiprocessing, which actually opens up numerous processes over multiple threads. Conclusion Python is extensively utilized in various fields, including web development and web scraping. Python is gaining popularity because of its simplicity and ability to deliver a wide range of skills with a few lines of code. These python interview questions will help to you.
https://techarge.in/top-10-popular-python-interview-questions-for-freshers/
CC-MAIN-2022-27
refinedweb
1,000
56.55
by Nacho Lafuente and Miquel Lopez-Miralpeix Published April 2009 [ Page 1] [ Page 2] [Page 3] Select the "Receive Data" tab to select where the event information will be temporarily stored. As this process is newly created, there are no variables and you will have to create a new one. Select "Create a new variable" option from the "Select variables to assign" combo box. The variable that needs to be created should be of type XML and named "inputEvent". WLI will assign the XML document that represents the received event to this variable. To finish the WLI process, you will insert a perform node to print out the value of the " inputEvent" variable. Select the Perform node from the Node Palette, drag it to the process definition in the main window and drop it just after the initial node and before the Finish node. The resulting process should look like this: Double-click the Perform node and click on the " View code" link to show the process source code for this node. Print out the value of the variable using the following code snippet. public void perform() throws Exception { System.out.println("DatabaseEG inputEvent: " + inputEvent); } Before receiving real database events, the newly created WLI process can be unit tested. The WLI Process application should be deployed to a running domain before testing. First, the WLI domain has to be started either manually or using Workshop for WebLogic. Follow the steps below to start the WLI domain using Workshop for WebLogic and add the application to the server: <26-mar-2009 19H47' CET> <Info> <WebLogicServer> <BEA-000377> <Starting WebLogic Server with Java HotSpot(TM) Client VM Version 1.5.0_11-b03 from Sun Microsystems Inc.> Enter any valid XML into x0 text box and click on " subscription" button. This sample uses the <foo/> XML document. The server log should show a line like the following. DatabaseEG inputEvent: <foo/> This trace demonstrates that the WLI process is working when an XML document is published to the message broker channel. You will now configure a real database event generator so that the WLI process will receive events coming from the database. Event Generators are configured using the WLI Administration Console which is accessible from - adjust host and port to your specific domain. Open the WLI console and select " Event Generators" from the left hand-side menu. Click on RDBMS > Create New to create a new Database event generator. Fill in " databaseEG" as the generator name and click on Submit. Click on " Define a New Channel Rule" to create the specific event generator that will publish database events to a message broker channel. Fill in the following information for the common event properties. A Trigger Event Type will be selected for the purpose of this sample. This database event generator will be configured to publish a new event every time that a new employee is added to the HR.EMPLOYEES table. If you are using a different schema, you should choose another table. Click on the " Table Name" link to select the required table. Navigate the schema, object type (TABLE) and finally select the required EMPLOYEES table. You can also introduce HR.EMPLOYEES in the " Table Name" text box. To complete the database event generator configuration, you should select what table columns should be selected when a new row is inserted. Click on " Select table columns to publish..." link to show the following dialog. Click on " Check All Columns" and Submit to publish all available columns. Now click on " Submit" at the main form to finish up the event generator configuration. The newly created database event generator should be created and the following table reflects that it is already running Now everything is fully configured to test the whole use case. You will insert a new employee into HR.EMPLOYEES table by typing the following at the command prompt. C:\WINDOWS>sqlplus HR/HR SQL*Plus: Release 10.2.0.1.0 - Production on Lun Oct 27 23:06:03 2008 Conectado a: Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production SQL> insert into EMPLOYEES(EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, HIRE_DATE, JOB_ID) VALUES (500, 'Nacho', 'Lafuente', 'nacho.lafuente@bea.com', SYSDATE, 'AD_VP'); 1 fila creada. SQL> commit; Confirmacion terminada. SQL> exit Desconectado de Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production The event generator poller has been configured using a frequency of 30 seconds. After that time has passed, the following trace should appear at the server log. DatabaseEG inputEvent: <TableRowSet xsi:schemaLocation=" WLI/RDBMS_EG/databaseeg TableRowSet.xsd" xmlns="" xmlns:xsi="" xmlns: <TableRow wld: <EMPLOYEE_ID>500</EMPLOYEE_ID> <FIRST_NAME>Nacho</FIRST_NAME> <LAST_NAME>Lafuente</LAST_NAME> <PHONE_NUMBER xsi: <HIRE_DATE>2008-10-27T23:12:34+01:00</HIRE_DATE> <JOB_ID>AD_VP</JOB_ID> <SALARY xsi: <COMMISSION_PCT xsi: <MANAGER_ID xsi: <DEPARTMENT_ID xsi: </TableRow> </TableRowSet> This trace demonstrates that the configured database event has been detected and published to WLI. The WLI process has received the event and printed the XML document that represents the event. This chapter will demonstrate how the same use case will be implemented in BPEL PM. The use case will retrieve new employees based on the HIRE_DATE column. The steps are the following: The process will then be ready for deployment. We need a helper table for knowing the last processed date in order to look for employees with HIRE_DATE newer than the date stored in this table. The SQL statement for creating the table will look like this: CREATE TABLE SEQUENCING_HELPER (TABLE_NAME VARCHAR2(32) NOT NULL,LAST_READ_DATE DATE); Step 0 - Installation of JDeveloper This is very simple: go to OTN , download JDeveloper 10g and just unzip it. Step 1 - Start JDeveloper Double-click on jdeveloper.exe Step 2 - Create an application Click on File -> New ... and choose Application. Fill in the details and choose No Template as Application Template. Step 3 - Create a BPEL Project Click on File -> New ... Enter the minimum details of the project (such as name and namespace) and the type of service: empty in this case. STEP 1 - Drag'n'Drop the DB Adapter from services and enter the service name. STEP 2 - Specify the database connection. If the database connection for querying schema information was not created under the JDeveloper connection's tab, it has to be created now. It's important to note that the JNDI Name of the connection has to match the one defined in the Application server (if no name matches, the details of JDev connection will be used during execution time). STEP 3 - Specify the type of service: Poll for New or Changed Records in a Table. STEP 4 - Import the Employees table by choosing it with " Import tables ..." button. STEP 5 - Remove any unneeded relationships (e.g. Remove all) STEP 6 - Select the necessary attributes (e.g. keep all) STEP 7 - Select the polling strategy: Update a Sequencing Table. STEP 8 - Provide helper table details STEP 9 - Set transaction and performance details (e.g. polling frequency). STEP 10 - Review the select statement used for polling rows. We need to create a receive activity for the BPEL Process to receive the messages generated by the Inbound DBAdapter partner link. STEP 1 - Drag'n'drop a Receive activity from the process activities palette. STEP 2 - Link it to the Partner link (drag left arrow to partner link). STEP 3 - Change the name and check the Create Instance check box. STEP 4 - Create a new variable by clicking OK (see previous screen shot). The process is now ready to be deployed on a BPEL PM Server and tested. Just create a row in the database (as was explained in the WLI functional test) and you will see a new instance in the BPEL Console as a result. Both WLI and BPEL PM are able to interact with databases in a similar way, and both tools are able to create process instances responding to database events, albeit using different polling strategies. BPEL PM creates "inbound" interactions based on events coming from the database, while WLI requires the configuration of a Database Event Generator to retrieve those events. BPEL PM creates "outbound" interactions from any on-demand operation that is executed by a BPEL process instance, whereas WLI has no equivalent concept of outbound operations for process instances. Note that, for inbound operations, WLI generates two different transactions: one to collect the message and the other to execute the associated process. Although BPEL PM can operate in the same fashion, it can also execute both operations in the same transaction, if desired. BPEL PM also offers a wide range of strategies for generating inbound interactions. WLI is limited to only two different polling strategies. In addition, the Oracle DB Adapter also supports the mapping of multiple related tables to nested xml. Only flat xml mappings are available in WLI and these are extremely limited, especially as they do not support outbound selects. The built-in O/R mapping tool TopLink is also an important differentiator. A key benefit of TopLink is database platform portability and third party database support. Finally, the SQL abstraction in the Oracle DB Adapter means that there is no need to code SQL. This improves maintainability and means that the same service can, for example, be deployed to DB2 in one scenario and Oracle DB in another. The table below summarizes the characteristics of each product:
http://www.oracle.com/technetwork/topics/soa/wli-event-generator-odb-adapt-03-094267.html
CC-MAIN-2015-32
refinedweb
1,557
55.64
autobox(3) User Contributed Perl Documentation autobox(3) NAME autobox - call methods on native types SYNOPSIS use autobox; # integers my $range = 10->to(1); # [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ] # floats my $error = 3.1415927->minus(22/7)->abs(); # strings my @list = 'SELECT * FROM foo'->list(); my $greeting = "Hello, world!"->upper(); # "HELLO, WORLD!" $greeting->for_each(\&character_handler); # arrays and array refs my $schwartzian = @_->map(...)->sort(...)->map(...); my $hash = [ 'SELECT * FROM foo WHERE id IN (?, ?)', 1, 2 ]->hash(); # hashes and hash refs { alpha => 'beta', gamma => 'vlissides' }->for_each(...); %hash->keys(); # code refs my $plus_five = (\&add)->curry()->(5); my $minus_three = sub { $_[0] - $_[1] }->reverse->curry->(3); # can, isa, VERSION, import and unimport can be accessed via autobox_class 42->autobox_class->isa('MyNumber') say []->autobox_class->VERSION DESCRIPTION though they are. The classes (packages) into which the native types are boxed are fully configurable. By default, a method invoked on a non-object is assumed to be defined in a class whose name corresponds to the "ref()" type of that value - or SCALAR if the value is a non-reference. This mapping can be overridden by passing key/value pairs to the "use autobox" statement, in which the keys represent native types, and the values their associated classes. As with regular objects, autoboxed values are passed as the first argument of the specified method. Consequently, given a vanilla "use autobox": "Hello, world!"->upper() is invoked as: SCALAR::upper("hello, world!") while: [ 1 .. 10 ]->for_each(sub { ... }) resolves to: ARRAY::for_each([ 1 .. 10 ], sub { ... }) Values beginning with the array "@" and hash "%" sigils are passed by reference, i.e. under the default bindings: @array->join(', ') @{ ... }->length() %hash->keys() %$hash->values() are equivalent to: ARRAY::join(\@array, ', ') ARRAY::length(\@{ ... }) HASH::keys(\%hash) HASH::values(\%$hash) Multiple "use autobox" statements can appear in the same scope. These are merged both "horizontally" (i.e. multiple classes can be associated with a particular type) and "vertically" (i.e. multiple classes can be associated with multiple types). Thus: use autobox SCALAR => 'Foo'; use autobox SCALAR => 'Bar'; - associates SCALAR types with a synthetic class whose @ISA includes both "Foo" and "Bar" (in that order). Likewise: use autobox SCALAR => 'Foo'; use autobox SCALAR => 'Bar'; use autobox ARRAY => 'Baz'; and use autobox SCALAR => [ 'Foo', 'Bar' ]; use autobox ARRAY => 'Baz'; - bind SCALAR types to the "Foo" and "Bar" classes and ARRAY types to "Baz". "autobox" is lexically scoped, and bindings for an outer scope can be extended or countermanded in a nested scope: { use autobox; # default bindings: autobox all native types ... { # appends 'MyScalar' to the @ISA associated with SCALAR types use autobox SCALAR => 'MyScalar'; ... } # back to the default (no MyScalar) ... } Autoboxing can be turned off entirely by using the "no" syntax: { use autobox; ... no autobox; ... } - or can be selectively disabled by passing arguments to the "no autobox" statement: use autobox; # default bindings no autobox qw(SCALAR); []->foo(); # OK: ARRAY::foo([]) "Hello, world!"->bar(); # runtime error Autoboxing is not performed for barewords i.e. my $foo = Foo->new(); and: my $foo = new Foo; behave as expected. Methods are called on native types by means of the arrow operator. As with regular objects, the right hand side of the operator can either be a bare method name or a variable containing a method name or subroutine reference. Thus the following are all valid: sub method1 { ... } my $method2 = 'some_method'; my $method3 = sub { ... }; my $method4 = \&some_method; " ... "->method1(); [ ... ]->$method2(); { ... }->$method3(); sub { ... }->$method4(); A native type is only asociated with a class if the type => class mapping is supplied in the "use autobox" statement. Thus the following will not work: use autobox SCALAR => 'MyScalar'; @array->some_array_method(); - as no class is specified for the ARRAY type. Note: the result of calling a method on a native type that is not associated with a class is the usual runtime error message: Can't call method "some_array_method" on unblessed reference at ... As a convenience, there is one exception to this rule. If "use autobox" is invoked with no arguments (ignoring the DEBUG option) the four main native types are associated with classes of the same name. Thus: use autobox; - is equivalent to: use autobox SCALAR => 'SCALAR', ARRAY => 'ARRAY', HASH => 'HASH', CODE => 'CODE'; This facilitates one-liners and prototypes: use autobox; sub SCALAR::split { [ split '', $_[0] ] } sub ARRAY::length { scalar @{$_[0]} } print "Hello, world!"->split->length(); However, using these default bindings is not recommended as there's no guarantee that another piece of code won't trample over the same namespace/methods. OPTIONS A mapping from native types to their user-defined classes can be specified by passing a list of key/value pairs to the "use autobox" statement. The following example shows the range of valid arguments: use autobox SCALAR => 'MyScalar' # class name ARRAY => 'MyNamespace::', # class prefix (ending in '::') HASH => [ 'MyHash', 'MyNamespace::' ], # one or more class names and/or prefixes CODE => ..., # any of the 3 value types above INTEGER => ..., # any of the 3 value types above FLOAT => ..., # any of the 3 value types above NUMBER => ..., # any of the 3 value types above STRING => ..., # any of the 3 value types above UNDEF => ..., # any of the 3 value types above UNIVERSAL => ..., # any of the 3 value types above DEFAULT => ..., # any of the 3 value types above DEBUG => ...; # boolean or coderef The INTEGER, FLOAT, NUMBER, STRING, SCALAR, ARRAY, HASH, CODE, UNDEF, DEFAULT and UNIVERSAL options can take three different types of value: · A class name e.g. use autobox INTEGER => 'MyInt'; This binds the specified native type to the specified class. All methods invoked on literals or values of type "key" will be dispatched as methods of the class specified in the corresponding "value". · A namespace: this is a class prefix (up to and including the final '::') to which the specified type name (INTEGER, FLOAT, STRING &c.) will be appended: Thus: use autobox ARRAY => 'Prelude::'; is equivalent to: use autobox ARRAY => 'Prelude::ARRAY'; · A reference to an array of class names and/or namespaces. This associates multiple classes with the specified type. DEFAULT The "DEFAULT" option specifies bindings for any of the four default types (SCALAR, ARRAY, HASH and CODE) not supplied in the "use autobox" statement. As with the other options, the "value" corresponding to the "DEFAULT" "key" can be a class name, a namespace, or a reference to an array containing one or more class names and/or namespaces. Thus: use autobox STRING => 'MyString', DEFAULT => 'MyDefault'; is equivalent to: use autobox STRING => 'MyString', SCALAR => 'MyDefault', ARRAY => 'MyDefault', HASH => 'MyDefault', CODE => 'MyDefault'; Which in turn is equivalent to: use autobox INTEGER => 'MyDefault', FLOAT => 'MyDefault', STRING => [ 'MyString', 'MyDefault' ], ARRAY => 'MyDefault', HASH => 'MyDefault', CODE => 'MyDefault'; Namespaces in DEFAULT values have the default type name appended, which, in the case of defaulted SCALAR types, is SCALAR rather than INTEGER, FLOAT &c. Thus: use autobox ARRAY => 'MyArray', HASH => 'MyHash', CODE => 'MyCode', DEFAULT => 'MyNamespace::'; is equivalent to: use autobox INTEGER => 'MyNamespace::SCALAR', FLOAT => 'MyNamespace::SCALAR', STRING => 'MyNamespace::SCALAR', ARRAY => 'MyArray', HASH => 'MyArray', CODE => 'MyCode'; Any of the four default types can be exempted from defaulting to the DEFAULT value by supplying a value of undef: use autobox HASH => undef, DEFAULT => 'MyDefault'; 42->foo # ok: MyDefault::foo []->bar # ok: MyDefault::bar %INC->baz # not ok: runtime error UNDEF The pseudotype, UNDEF, can be used to autobox undefined values. These are not autoboxed by default. This doesn't work: use autobox; undef->foo() # runtime error This works: use autobox UNDEF => 'MyUndef'; undef->foo(); # ok So does this: use autobox UNDEF => 'MyNamespace::'; undef->foo(); # ok NUMBER, SCALAR and UNIVERSAL The virtual types NUMBER, SCALAR and UNIVERSAL function as macros or shortcuts which create bindings for their subtypes. The type hierarchy is as follows: UNIVERSAL -+ | +- SCALAR -+ | | | +- NUMBER -+ | | | | | +- INTEGER | | | | | +- FLOAT | | | +- STRING | +- ARRAY | +- HASH | +- CODE Thus: use autobox NUMBER => 'MyNumber'; is equivalent to: use autobox INTEGER => 'MyNumber', FLOAT => 'MyNumber'; And: use autobox SCALAR => 'MyScalar'; is equivalent to: use autobox INTEGER => 'MyScalar', FLOAT => 'MyScalar', STRING => 'MyScalar'; Virtual types can also be passed to "unimport" via the "no autobox" syntax. This disables autoboxing for the corresponding subtypes e.g. no autobox qw(NUMBER); is equivalent to: no autobox qw(INTEGER FLOAT); Virtual type bindings can be mixed with ordinary bindings to provide fine-grained control over inheritance and delegation. For instance: use autobox INTEGER => 'MyInteger', NUMBER => 'MyNumber', SCALAR => 'MyScalar'; would result in the following bindings: 42->foo -> [ MyInteger, MyNumber, MyScalar ] 3.1415927->bar -> [ MyNumber, MyScalar ] "Hello, world!->baz -> [ MyScalar ] Note that DEFAULT bindings take precedence over virtual type bindings i.e. use autobox UNIVERSAL => 'MyUniversal', DEFAULT => 'MyDefault'; # default SCALAR, ARRAY, HASH and CODE before UNIVERSAL is equivalent to: use autobox INTEGER => [ 'MyDefault', 'MyUniversal' ], FLOAT => [ 'MyDefault', 'MyUniversal' ], # ... &c. DEBUG "DEBUG" exposes the current bindings for the scope in which "use autobox" is called by means of a callback, or a static debugging function. This allows the computed bindings to be seen in "longhand". The option is ignored if the value corresponding to the "DEBUG" key is false. If the value is a CODE ref, then this sub is called with a reference to the hash containing the computed bindings for the current scope. Finally, if "DEBUG" is true but not a CODE ref, the bindings are dumped to STDERR. Thus: use autobox DEBUG => 1, ... or use autobox DEBUG => sub { ... }, ... or sub my_callback ($) { my $hashref = shift; ... } use autobox DEBUG => \&my_callback, ... METHODS import On its own, "autobox" doesn't implement any methods that can be called on native types. However, its static method, "import", can be used to implement "autobox" extensions i.e. lexically scoped modules that provide "autobox" bindings for one or more native types without requiring calling code to "use autobox". This is done by subclassing "autobox" and overriding "import". This allows extensions to effectively translate "use MyModule" into a bespoke "use autobox" call. e.g.: package String::Trim; use base qw(autobox); sub import { my $class = shift; $class->SUPER::import(STRING => 'String::Trim::Scalar'); } package String::Trim::Scalar; sub trim { my $string = shift; $string =~ s/^\s+//; $string =~ s/\s+$//; $string; } 1; Note that "trim" is defined in an auxiliary class rather than in "String::Trim" itself to prevent "String::Trim"'s own methods (i.e. the methods it inherits from "autobox") being exposed to SCALAR types. This module can now be used without a "use autobox" statement to enable the "trim" method in the current lexical scope. e.g.: #!/usr/bin/env perl use String::Trim; print " Hello, world! "->trim(); EXPORTS autobox_class "autobox" makes a single method available to autoboxed types: "autobox_class". This can be used to call "isa", "can", "VERSION", "import" and "unimport". e.g. if (42->autobox_class->isa('SCALAR')) ... if (sub { ... }->autobox_class->can('curry')) ... type "autobox" includes an additional module, "autobox::universal", which exports a single subroutine, "type". This sub returns the type of its argument within "autobox" (which is essentially longhand for the type names used within perl). This value is used by "autobox" to associate a method invocant with its designated classes. e.g. use autobox::universal qw(type); type("Hello, world!") # STRING type(42) # INTEGER type([]) # ARRAY type(sub { }) # CODE "autobox::universal" is loaded automatically by "autobox", and, as its name suggests, can be used to install a universal method (i.e. a method for all "autobox" types) e.g. use autobox UNIVERSAL => 'autobox::universal'; 42->type # INTEGER 3.1415927->type # FLOAT %ENV->type # HASH CAVEATS Performance Autoboxing comes at a price. Calling "Hello, world!"->length() is slightly slower than the equivalent method call on a string-like object, and significantly slower than length("Hello, world!") Gotchas Precedence Due to Perl's precedence rules, some autoboxed literals may need to be parenthesized: For instance, while this works: my $curried = sub { ... }->curry(); this doesn't: my $curried = \&foo->curry(); The solution is to wrap the reference in parentheses: my $curried = (\&foo)->curry(); The same applies for signed integer and float literals: # this works my $range = 10->to(1); # this doesn't work my $range = -10->to(10); # this works my $range = (-10)->to(10); print BLOCK Perl's special-casing for the "print BLOCK ..." syntax (see perlsub) means that "print { expression() } ..." (where the curly brackets denote an anonymous HASH ref) may require some further disambiguation: # this works ( print { foo => 'bar' }->foo(); # and this print { 'foo', 'bar' }->foo(); # and even this print { 'foo', 'bar', @_ }->foo(); # but this doesn't print { @_ }->foo() ? 1 : 0 In the latter case, the solution is to supply something other than a HASH ref literal as the first argument to "print()": # e.g. print STDOUT { @_ }->foo() ? 1 : 0; # or my $hashref = { @_ }; print $hashref->foo() ? 1 : 0; # or print '', { @_ }->foo() ? 1 : 0; # or print '' . { @_ }->foo() ? 1 : 0; # or even { @_ }->print_if_foo(1, 0); eval EXPR Like most pragmas, autobox performs operations at compile time, and, as a result, runtime string "eval"s are not executed within its scope i.e. this doesn't work: use autobox; eval "42->foo"; The workaround is to use autobox within the "eval" e.g. eval <<'EOS'; use autobox; 42->foo(); EOS Note that the "eval BLOCK" form works as expected: use autobox; eval { 42->foo() }; # OK VERSION 2.75 SEE ALSO · autobox::Core · Moose::Autobox · perl5i · Scalar::Properties AUTHOR chocolateboy <chocolate@cpan.org> COPYRIGHT Copyright (c) 2003-2011, chocolateboy. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself. perl v5.12.5 2011-07-21 autobox(3)[top]
http://www.polarhome.com/service/man/?qf=autobox5.12&tf=2&of=MacOSX&sf=3pm
CC-MAIN-2018-26
refinedweb
2,213
53.92
On Wed, Jan 18, 2006 at 03:00:53PM -0800, Matt Zimmerman wrote: > On Wed, Jan 18, 2006 at 02:47:05PM -0800, Thomas Bushnell BSG wrote: > > Ok, then I must have misunderstood something. So it is clear then > > that Ubuntu does recompile every package. > > To clarify explicitly: > > - Ubuntu does not use any binary packages from Debian > - Most Ubuntu source packages are identical copies from Debian, while some are modified for Ubuntu > - All Ubuntu binary packages are built for Ubuntu in Ubuntu chroots > > > When you recompile packages, change their version number just as > > Debian does for binary-NMUs? That is, the first binary compile for > > an arch gets the same version number as the original source, but all > > future recompilations, which would include those done by Ubuntu or > > anyone else, should get a modified version number. > > I believe there are still packages which break when bin-NMU'd (e.g., > Depends: = ${Source-Version}), and there are parts of our infrastructure > which do not support them (Ubuntu doesn't do bin-NMUs). If it were > essential to version the packages differently, I would say that the source > package versions should be changed as well. Bin-NMUs are more trouble than > they are worth. The Source-Version problem will not affect Ubuntu because they rebuild both binary: all and binary: any packages. The issue with Debian style binNMU is that we only rebuild the binary: any packages that will have a different source version than the binary: all packages. You just need to bump the version before rebuilding the packages and that's it. It is not different from rebuilding the packages after a minor change. >. At least to avoid namespace conflict between Debian and Ubuntu .deb files. Cheers, Bill.
https://lists.debian.org/debian-devel/2006/01/msg01404.html
CC-MAIN-2015-40
refinedweb
288
58.52
Zones¶ Say you create a room named Meadow in your nice big forest MUD. That’s all nice and dandy, but what if you, in the other end of that forest want another Meadow? As a game creator, this can cause all sorts of confusion. For example, teleporting to Meadow will now give you a warning that there are two Meadow s and you have to select which one. It’s no problem to do that, you just choose for example to go to 2-meadow, but unless you examine them you couldn’t be sure which of the two sat in the magical part of the forest and which didn’t. Another issue is if you want to group rooms in geographic regions. Let’s say the “normal” part of the forest should have separate weather patterns from the magical part. Or maybe a magical disturbance echoes through all magical-forest rooms. It would then be convenient to be able to simply find all rooms that are “magical” so you could send messages to them. Zones in Evennia¶ Zones try to separate rooms by global location. In our example we would separate the forest into two parts - the magical and the non-magical part. Each have a Meadow and rooms belonging to each part should be easy to retrieve. Many MUD codebases hardcode zones as part of the engine and database. Evennia does no such distinction due to the fact that rooms themselves are meant to be customized to any level anyway. Below is a suggestion for how to implement zones in Evennia. All objects in Evennia can hold any number of Tags. Tags are short labels that you attach to objects. They make it very easy to retrieve groups of objects. An object can have any number of different tags. So let’s attach the relevant tag to our forest: forestobj.tags.add("magicalforest", category="zone") You could add this manually, or automatically during creation somehow (you’d need to modify your @dig command for this, most likely). You can also use the default @tag command during building: @tag forestobj = magicalforest : zone Henceforth you can then easily retrieve only objects with a given tag: import evennia rooms = evennia.search_tag("magicalforest", category="zone") Using typeclasses and inheritance for zoning¶ The tagging or aliasing systems above don’t instill any sort of functional difference between a magical forest room and a normal one - they are just arbitrary ways to mark objects for quick retrieval later. Any functional differences must be expressed using Typeclasses. Of course, an alternative way to implement zones themselves is to have all rooms/objects in a zone inherit from a given typeclass parent - and then limit your searches to objects inheriting from that given parent. The effect would be similar but you’d need to expand the search functionality to properly search the inheritance tree.
http://evennia.readthedocs.io/en/latest/Zones.html
CC-MAIN-2018-13
refinedweb
479
61.97
Created on 2007-12-15 03:55 by Wubbulous, last changed 2007-12-18 19:31 by gvanrossum. This issue is now closed. Python will not load the email module or any of its child modules. More detail is needed than this in order to try to fix this. What error message are you getting? What OS? What exact version of Python? Is this a binary distro or a source one? Since all releases are thoroughly tested and never had any import issues with the email code chances are there is a problem with your environment and not Python. I have attempted the following separately: import email import they each return the error: Traceback (most recent call last): File "C:\Panda3D-1.4.2\python\lib\smtplib.py", line 49, in ? from email.base64MIME import encode as encode_base64 ImportError: No module named base64MIME I just noticed that the directory you are executing from is Panda3D. Did you not download Python directly but are using the one from Panda3D? But the email package does not import smtplib (the dependency is the other way). Can you please try with the command: import email and paste the whole traceback? Let's not waste time in the bug tracker debugging some user's broken setup. Let him contact Panda3D's customer support.
https://bugs.python.org/issue1632
CC-MAIN-2018-09
refinedweb
218
75.71
This package complements Sense’s REST API by wrapping and simplifying some of the most common operations, such as launching and stopping worker dashboards. Its primary purpose is to support other packages that implement higher-level approaches to cluster computing. This package is preinstalled on Sense. You can import it with import sense To install it elsewhere use pip install sense This example launches several worker dashboards and communicates with them using ZeroMQ over the project’s private network. import time import sense n_workers = 3 # Use 'install' to install package 'pyzmq' from PyPI to the project. sense.install('pyzmq') import zmq # Create the ZeroMQ server. context = zmq.Context() socket = context.socket(zmq.REP) # Use 'get_network_info' to find out the private IP address of the current # dashboard in the project's virtual private network. address = "tcp://" + sense.network_info()['project_ip'] + ":5000" socket.bind(address) # Define code the worker dashboards should execute on startup. # Each worker will attempt to connect to the ZeroMQ server whose # address is stored in its 'SERVER' environment variable and then will send # a message to the server. worker_code = """ import os # Because pyzmq was previously installed to the project, workers don't # need to reinstall it. import zmq import sense # Connect to the master context = zmq.Context() print "Connecting to master..." socket = context.socket(zmq.REQ) socket.connect(os.environ['SERVER']) # Send a message socket.send("Sense is so easy!") # Wait for a reply message = socket.recv() print "Received reply: ", message """ # Use 'launch_workers' to start three small worker dashboards. The above # code is sent to each, and the current dashboard's project IP address is # stored in each worker's environment as 'SERVER', so each worker will contact # the current dashboard. workers = sense.launch_workers(n=n_workers, size=0, code=worker_code, env={"SERVER": address}) # Listen for worker messages. for i in range(0, n_workers): # Wait for next request from client message = socket.recv() print "Received request: ", message time.sleep (1) socket.send("I agree.") sense.stop_workers() Installs a Python package to the project with pip using the user scheme. import sense sense.install(package_name, flags=[], arguments={}) If you prefer, you can also install packages by running a shell command from IPython using the ! prefix: !pip install pyzmq --user Options: Once installed, any of the project’s dashboards can import the package. Returns the current dashboard’s contact information in a dict with keys public_dns, public_port_mapping, ssh_password and project_ip. import sense network_info = sense.network_info() Every project has its own virtual private network (VPN). The project IP address is bound to the project VPN and is only accessible to other dashboards in the same project. The project VPN makes it easy to use cluster computing frameworks that lack built-in security features, such as MPI. The public DNS hostname, public port mapping and SSH password describe how the current dashboard can be contacted from outside the project. The public port mapping is a dict whose keys and values are integers. Only ports that are keys of the public port mapping can be accessed via the public DNS hostname. If you run a service on port 3000, for example, it can be accessed from anywhere on the internet on the public DNS hostname and port public_port_mapping[3000]. If required, you can SSH to dashboards using the public DNS hostname and port public_port_mapping[22] with username “sense” and the SSH password. Launches worker dashboards into the cluster. import sense worker_info = sense.launch_workers(n, size=0, engine="sense-ipython-engine", script="", code="", env={}) In Sense, a cluster is a group of dashboards with the same master dashboard. Worker dashboards multiplex their outputs to the master and are cleaned up automatically when the master is stopped or fails. These features make it easy to manage, monitor and debug distributed applications on Sense. The parameters are: The return value is a list of dicts. Each dict describes one of the workers that was launched and contains keys such as "id", "engine", "status", etc. The full format is documented here. Returns information on the worker dashboards in the cluster in a list of dicts like those returned by launch_workers. import sense worker_info = sense.list_workers() Returns information on the cluster’s master dashboard in a dict like the ones returned by launch_workers. import sense master_info = sense.get_master() Stops worker dashboards. Dashboards’ numerical IDs are available at key id in the dicts returned by list_workers and launch_workers. The return value is a dict of the same type. import sense # To stop specific workers: worker_info = sense.stop_workers(id1, id2, ...) # To stop all workers in the cluster: worker_info = sense.stop_workers() Returns authentication information for the REST API as a dict with keys "user" and "password". Sense’s REST API gives you complete programmatic control over virtually every aspect of Sense. Most REST calls require Basic Authentication. To make authenticated REST calls, supply the information returned by get_auth your HTTP client of choice, such as the Python requests package. By default get_auth uses the environment variable SENSE_API_TOKEN for authentication. This token restricts access to the current project. For access across projects, you can pass in credentials manually or set SENSE_USERNAME and SENSE_PASSWORD in the environment. To better understand these options, read the Understanding Project Security documentation. This example retrieves information about the current project: import sense import requests auth = sense.get_auth() url = "" + os.environ["SENSE_OWNER_ID"] + \ "/projects/" + os.environ["SENSE_PROJECT_ID"] response = requests.get(url, auth=(auth["user"], auth["password"])).json() The environment variables used in this example are common to all dashboards, across all engines, and are documented here. IPython provides its own rich display system, so unlike its R and JavaScript counterparts this package does not provide any rich output functions. Use IPython’s rich display system to display HTML, images and more in a dashboard..
https://pypi.org/project/sense/
CC-MAIN-2017-09
refinedweb
953
50.43
How do you cache the content asset? If you use IObjectInstanceCache/ISynchronizedObjectInstanceCache (which is the recommended way), when you add an object to cache you can control how long before the cache will expire, using CacheEvictionPolicy if you want to remove the cache actively, just remove the cache key So, we're not caching anything ourselves. We just inherit from "ContentProvider" and then implement all the necessary operations. Unfortunately i'm not allowed to post hyperlinks, otherwise i would've posted a snippet. public class MyContentProvider : ContentProvider { protected override IContent LoadContent(ContentReference contentLink, ILanguageSelector languageSelector){} protected override IList<GetChildrenReferenceResult> LoadChildrenReferencesAndTypes(ContentReference contentLink, string languageID, out bool languageSpecific){} } This is what we do. Then ofcourse we hook it up to make this turn up in the Asset pane as a new tab. The problem is that the results of "LoadChildrenReferencesAndTypes" is cached after the first call. And we're trying to figure out where it is cached and how we can expire it. It could be at a higher level. We're not sure about that. Our content provider makes live API calls to an external data source. When we were debugging, we noticed that when we expand a node in the asset tree, live calls are going through, but the second time around, data turns up instantaneously, but its not making a live call. So we understand that its cached somewhere. We are trying to understand where exactly its cache (it must be SynchronizedObjectCache im guess) and how we can get the key if we need to expire it manually. Since our last update, we also found another function that we could override protected override void SetCacheSettings(IContent content, CacheSettings cacheSettings){} This allows us to set the cache interval, which is good, but we still have certain conditions where we would like to "manually" expire the cache. Just reach out to support@episerver.com. it should not cost money, at least at the beginning. We've created a custom content asset provider repository which pulls data from an external data source. We've then used identity mapper and mapped it so that it can be used by EPiServer CMS. Our problem is that once the content asset is cached, episerver doesn't request for the live call again since its cached. We need to know how to expire that cache as well as what the duration of the cache is.
https://world.optimizely.com/forum/developer-forum/CMS/Thread-Container/2021/2/expire-cache-on-custom-repository-items/
CC-MAIN-2022-33
refinedweb
400
52.9
Any idea why isn’t there System.XML? The assembly is probably not referenced, you can add import clr clr.AddReference("System.Xml.dll") import System.Xml as xml Thanks @jesterking, I know how to import an external dll, but why is it missing from ghpython? Is it a “bug”? I tested it with csharp and there it works fine. Update: Where are these dlls usually referenced from? Did I miss to install some dependency? Off Topic: You are Nathan, right? Are you incognito? Why the different account? I’m just curious. When people use (only) a signature you are not supposed to ask for their identity in public. PM is better if just curious. // Rolf When people don’t want their name revealed they wouldn’t put it in another very active (until recently) account. Anyways, I accept the remark. No worries guys, “the other account” is on vacation for the time being… Yes. No. Vacation, as @wim mentioned. The other account has all bells and whistles enabled, this one is nice and quiet. Thursday I’ll (he’ll?) be back on the job. Thanks for humoring me. Btw this was my first thought. There are many assemblies not being able to be included directly in Python. Could that be fixed, please? The ones commented in the image below: Is this LINQ thingy just generally forbidden to be used from IronPython? Nevermind I guess I found partially the answer: Still Some just can’t be added: Wrong reference: import clr clr.AddReference("System.Core.dll") import System.Linq as linq print(dir(linq)) More out of curiosity, what are you doing with LINQ that you can’t do with regular Python list comprehension (and/or itertools)? I am trying to translate this script I found on the old forum, in order to learn how to do that, but for me csharp is very confusing at times. GH.CreateCapsule.cs (4.4 KB) This is my process of translation from csharp to python: - In order to figure out what I am supposed to do I try to import whatever is imported to the csharp - then start with the code by copying the classes methods you name it and searching the API about examples. - If no examples exist I’m trying to figure out myself how to declare those things in python because most of the time csharp syntax is madly uncomprehensible to me. On top of all that I’m still a noob-programmer and there’s a lot of trial and error. When it comes to a point that I cannot even import something the panic button is pushed On the other hand System.Xml.Linq is something I need for reading XMLs but I haven’t yet started playing with that. Update: @AndersDeleuran, btw I have no idea what LINQ does, I assume linking something, but I haven’t got to that yet. I’ll read about it when I get to it. LOL how logical Thanks @jesterking For linq to xml check this LINQ to XML
https://discourse.mcneel.com/t/system-xml-missing/68680
CC-MAIN-2021-43
refinedweb
509
75.71
20 August 2009 06:04 [Source: ICIS news] By Prema Viswanathan SINGAPORE (ICIS news)--India’s polymer demand has surged 22-38% in the past four months – the sharpest increase in four years – but the outlook may not remain so bullish if prevailing drought conditions persist, market sources said on Thursday. “Ironically, the scant rainfall this year has caused the pipe-laying season to be extended, resulting in stronger-than-usual demand for polyvinyl chloride (PVC),” said an Indian producer. PVC consumption was estimated to have increased by 38% in April-July, the first four months of the fiscal year 2009-2010 that starts in April and ends in March, from the corresponding period last year to 620,000 tonnes, according to market sources. Normally, PVC demand begins to taper off in July, with the advent of the monsoon season, which was delayed this year. The demand surge in PVC had been mainly fuelled by a robust irrigation segment, suppliers and buyers said. “The construction sector has been sluggish this year due to the economic downturn, but the strong growth in irrigation has compensated for this,” a PVC converter said. Polypropylene (PP) demand also shot up by 22% to 720,000 tonnes in the past four months on the back of strong showing in the packaging segment, said a producer. “Although packaging for branded goods has not taken off very well this year, non-branded packaging has shown phenomenal growth,” the producer said. Demand from the pharmaceutical and cosmetics sectors had been strong, said an end user. Low density polyethylene (LDPE) consumption surged by 30% in April-July 2009 to 130,000 tonnes, said a producer. “Easier availability of LDPE this year compared to last year contributed to the growth in demand. Buying interest was particularly robust in the milk and oil pouch segments,” a converter said. High density PE (HDPE) and linear low density PE (LLDPE) also saw a 14% rise in consumption to 750,000 tonnes, sustained by packaging as well as blow-moulding applications, especially for chemicals. “Although demand for shopping bags, which use HDPE and LLDPE film, has been declining due to environmental concerns, we have seen a huge increase in buying interest for PE film in the food packaging and steel sectors,” said Ashok Rao, CEO of Daman Polymers, a PE converter. Rao said margins for plastics converters in ?xml:namespace> PP converters were equally bullish, with one converter saying that Indian consumers had defied the global recessionary trend and supported the market. “We could have seen even stronger demand growth in the past few months if it were not for supply constraints, which, thankfully, are easing now,” Rao added. However, the picture might not be so rosy in the coming months of the fiscal year, a trader said. “The current drought conditions, if they continue, will severely dent rural consumption and result in a slowing of polymer demand growth,” he said. Producers are also worried that the full year consumption figures may take a hit if the drought persists. “We may still see double digit growth for polymers, but the full year outlook is unlikely to be as bullish as in the first four months of the Indian fiscal year if rainfall doesn’t improve,” said a second PE producer. Another fallout from the drought would be the impact on the power sector. “Hydro-electric power will be even more scarce if the drought persists. Already, we are facing power-tripping four times a day in For more on polymers
http://www.icis.com/Articles/2009/08/20/9241302/india-polymer-demand-up-22-38-but-drought-worries.html
CC-MAIN-2014-10
refinedweb
586
55.98
got a formerly working script, which is not working anymore. basically it uses the RoboFab getPen() like so: from robofab.world import CurrentFont f = CurrentFont() newGlyph = f.newGlyph('demoDrawGlyph', clear=True) newGlyph.width = 1000 ## here is an issue ## pen = newGlyph.getPen() pen.moveTo((100, 100)) pen.lineTo((800, 100)) pen.lineTo((100, 100)) pen.closePath() newGlyph.update() f.update() It gets me: ImportError: No module named GSPen When I remove the parenthesis behind pen = newGlyph.getPen(), it runs further, but then I get: AttributeError: 'function' object has no attribute 'moveTo' RoboFab itself seems to be working. It nicely creates a new Glyph with the proper name and width, it is empty though and got trouble with the moveTo guys. Also i just updated the objectsGS.py from schriftgestalt. (G1, G2, both cutting edge, Yosemite)
https://forum.glyphsapp.com/t/robofab-getpen/2018/12
CC-MAIN-2019-26
refinedweb
134
62.95
sched — Timed Event Scheduler¶. By default monotonic() and sleep() from time are used, but the examples in this section use time.time(), which also meets the requirements, because it makes the output easier to understand. four arguments. - A number representing the delay - A priority value - The function to call - A tuple of arguments for the function This example schedules two different events to run after two and three seconds respectively. When the event’s time comes up, print_event() is called and prints the current time and the name argument passed to the event. import sched import time scheduler = sched.scheduler(time.time, time.sleep) def print_event(name, start): now = time.time() elapsed = int(now - start) print('EVENT: {} elapsed={} name={}'.format( time.ctime(now), elapsed, name)) start = time.time() print('START:', time.ctime(start)) scheduler.enter(2, 1, print_event, ('first', start)) scheduler.enter(3, 1, print_event, ('second', start)) scheduler.run() Running the program produces: $ python3 sched_basic.py START: Sun Sep 4 16:21:01 2016 EVENT: Sun Sep 4 16:21:03 2016 elapsed=2 name=first EVENT: Sun Sep 4 16:21:04 2016 elapsed=3 name=second The time printed for the first event is two seconds after start, and the time for the second event is three.ctime(time.time()), name) time.sleep(2) print('FINISH EVENT:', time.ctime(time.time()), name) print('START:', time.ctime3 sched_overlap.py START: Sun Sep 4 16:21:04 2016 BEGIN EVENT : Sun Sep 4 16:21:06 2016 first FINISH EVENT: Sun Sep 4 16:21:08 2016 first BEGIN EVENT : Sun Sep 4 16:21:08 2016 second FINISH EVENT: Sun Sep 4 16:21:10 2016 second Event Priorities¶ If more than one event is scheduled for the same time their priority values are used to determine the order they are run. import sched import time scheduler = sched.scheduler(time.time, time.sleep) def print_event(name): print('EVENT:', time.ctime(time.time()), name) now = time.time() print('START:', time.ctime3 sched_priority.py START: Sun Sep 4 16:21:10 2016 EVENT: Sun Sep 4 16:21:12 2016 second EVENT: Sun Sep 4 16:21:12 2016 first Canceling Events¶ Both enter() and enterabs() return a reference to the event that can be used to cancel it later. Because.ctime(time.time()), name) counter += 1 print('NOW:', counter) print('START:', time.ctime3 sched_cancel.py START: Sun Sep 4 16:21:13 2016 EVENT: Sun Sep 4 16:21:16 2016 E2 NOW: 1 FINAL: 1 See also - Standard library documentation for sched time– The timemodule.
https://pymotw.com/3/sched/
CC-MAIN-2018-47
refinedweb
426
66.13
WHO NAMES A NAMESPACE "SMITTY"?!?!? I hate: 1) "My" anything 2) Single letter variables (except loop counters) 3) "Cute" names (I have in fact seen variable names in Klingon) 4) Modules named after the developer. Sorry, just venting. Move along now, nothing to see here. Philo Philo Tuesday, June 10, 2003 I have seen developers map an single character array over a Fortran common block, so they could type less. U(50) was the tip speed in x-direction, U(30) was the blade length, U(172) was the air temperature, etc. Imagine tens of thousands of lines of code with only U() elements... And they wondered why 99.9% of their time was spent debugging. Jan Derk Tuesday, June 10, 2003 .. who names a namespace "SMITTY"? Obviously someone who can't spell: M and H aren't even _near_ each other on the keyboard.. (sorry, couldn't resist) Nice Tuesday, June 10, 2003 Oh. I use "mySomething" for references to things that objects own. Usually that live outside my namespace. It's so I know it belongs to this object. As opposed to a passing reference which is just "aSomething" And "the" as parameters, so members don't clash with parameters. I do this because typing the "theSomething" parameters seems to happen less than typing "m_something" members would. It sort of means the code reads in nice sentences which helps me think about it - "delete myParser;" Katie Lucas Tuesday, June 10, 2003 Jan, We had an anlayst who used Case tools, but did not know how to change the names from the default. Just as VB gives controls names like TextBox1, this Case tool would give processes names like CS0171. The anlayst then insited that all functions be given the name that matched her diagram. So all of the procedures had meaningless codes for names. Complete nightmare. Ged Byrne Tuesday, June 10, 2003 Thinking of variable names is one of the hardest parts of coding I reckon. That's why I like Perl, default variables mean less variable names to think of. Matthew Lock Tuesday, June 10, 2003 Klingon!?? ROFL! Look on the bright side, at least Klingon is written in Latin-1, would be hell on your source control otherwise .... Richard Tuesday, June 10, 2003 I saw a program that used vegetable names for variables and fruits names for the functions if banana(potato,carot,leak) apple(potato,carot) else raisin(potato,leak) Application Specialist Tuesday, June 10, 2003 <M and H aren't even _near_ each other on the keyboard..> How keyboardist!! (They are very close on wy keyboard.) Tom Tuesday, June 10, 2003 I worked for a company for awhile where a programmer frequently used variable names like Blue, Green, Yellow and Fuchia for no useful reason. The president of the company said he was "artistic". I said he was a "moron". Tim Sullivan Tuesday, June 10, 2003 "Klingon!?? ROFL! Look on the bright side, at least Klingon is written in Latin-1, would be hell on your source control otherwise ...." All .NET compilers accept UTF-8 source code files. While I'm not aware of a Klingon section in the Unicode standard you might quite well define your variables in polytonic Greek! (If the compiler accepts polytonic Greek variables, anyway.) Chris Nahr Tuesday, June 10, 2003 There goes a story from one university where one student was told to use longer and more mnemonic names to his variables. So, he started to name them "long_and_mnemonic_variable_number_one", "long_and_mnemonic_variable_number_two", etc ... Evgeny Goldin Tuesday, June 10, 2003 Now I think of it, I'm always changing my style of naming variables. How unprofessional. Leonardo Herrera Tuesday, June 10, 2003 I remember giving somebody a task to investigate the design of plugin modules to our control panel app (kind of similar to MMC snap-ins, actually) and he ended up writing it as a bee keeping system with variables like beeX and beeY. He didn't last long. Better Than Being Unemployed... Tuesday, June 10, 2003 [Modules named after the developer] I don't mind this so much if it's open source or their own personal toolbox. But I have to agree with the loathing for "my" variables. You own nothing on the machine. it owns you! Think not? Why are you looking at it right now? You can't look away can you! trollbooth Tuesday, June 10, 2003 I worked with a developer who used to use sexual innuendos in his code, using class names like "Shaft" and :balls" and funtion names like "probe()". Needless to say, after he left we junked all of his old code simply because noone liked to look at it (and we were afraid a customer might run into a Shaft.probe() exception too..) Colin Evans Tuesday, June 10, 2003 I'm largely with the original post. Here are a few of my tips 1. For scratch variables (like loop indexes, coordinates when drawing, width/height of some window when painting it or calculating it) use double letters. Instead of i, j, k, x,y,z, w, h use ii, jj, kk, xx, yy, zz, ww, hh The advantage is if later the scratch variable becoes meaningful, it is easy to change. 2. Don't leave letters out when naming variables. I hate it when people leave out letters like SalaryEarnedThisWeek becomes SalryErndThsWk As I can never remember (and can't tell by scanning the code unless I go back to the original definition and copy/paste) whether it's SalryErndThsWk, SlryErndThsWk, SlaryErndThsWk, etc. Either spell it out in full: SalaryEarnedThisWeek or spell it out in full with a shorter name if you don't like typing: SalaryThisWeek 3. Never use plurals for variable names. Some people like to name arrays (or other variables) with an 's. When you have a few variables like this, and some not, and you come back to the code after a while, it is real hard to remember which names are pluralized, which aren't. So... don't pluralize any. S. Tanna Tuesday, June 10, 2003 "3. Never use plurals for variable names." What would you name a collection of Employee objects, for example? John Topley () Tuesday, June 10, 2003 S Tanna: I'm not sure I understand your first point about scratch variables. Why is a double letter name any easier to change than a single letter name? Mike McNertney Tuesday, June 10, 2003 I spent about 20% of my coding time changing varable, class and method names.. It improves a lot the quality of my code. I am very fond of the VisualStudio's keystrokes: ctrl-h, [alt-c, alt-w] alt-a (Replace All, Match case, Match whole word) to replace names without side effects all the time. It's very safe and very convenient. It has become a essential part of my coding. Although I think it's kind of simple, there is even a refactoring about this: Sergio Tuesday, June 10, 2003 "Why is a double letter name any easier to change than a single letter name?" If you do a search/replace for "i" or "j", you'll get a bunch of false positive results. OTOH, if you're searching for "ii", you'll probably only find places where it's used as a variable. I don't user either method, however. I usually use "count" or "index" as my looping variable (depending on why I'm looping). RocketJeff Tuesday, June 10, 2003 Why are programmers allowed to be lazy when naming loop counters? "i" is a completely useless name. Is it that hard to qualify the "i" with what it actually is indexing, e.g. "iShape"? SomeBody Tuesday, June 10, 2003 > S Tanna: I'm not sure I understand your first point about scratch variables. Why is a double letter name any easier to change than a single letter name? Global replace Try global replacing (say) i in any source file with a nice name. It is next to impossible not to hit some other i's (say in other variable names, function names, etc) > What would you name a collection of Employee objects, for example? Employee[] Employee[1] Employee[2] etc I don't know how you read it aloud, but it also sounds better the way I do ("Employee Array", "Employee 1", "Employee 2") than if I had used Employees[] ("Employees Array" - not too bad, "Employees 1", "Employees 2" - yuck) Philo! Thanks man, myAnything is just so damn disgusting. Nat Ersoz Tuesday, June 10, 2003 <Why are programmers allowed to be lazy when naming loop counters?> Often the loop counter is just noise, required by whatever language you're using. If I'm iterating through N shapes, and treating each shape independently, what I really want is 'for shape in shapes', not something excessive and wordy like 'for(iShape=0;iShape<shapes.size();++iShape)'. So to cut down on the noise, I make the loop counter short. That's my rationale, anyway. It's not laziness. i and j are also traditional subscripts used in maths. I would contend than when something really is scratch variable, like some throw away loop index, a shorter name is MORE readable. 1. if you use a long name, when the variable is just throw-away garbage/noise/syntatical requirement of the language, is adding too much emphasis/importance to such an element. 2. if you have several nested loops, in each case the index being throw-away garbage/noise/syntatical requirement, long names for each makes it more not less confusing. 3. if you have several nested loops, in each case the index being throw-away garbage/noise/syntatical requirement, you are probably more concerned about which loop index you are dealing with (i.e. code dealing with a loop index wants to know it's dealing with the inner/outer most index, etc) than what you're counting throw. With ii, jj, kk (or i,j,k) this is obvious. With long names, it's not. 4. I can not recall any case, where any programmer I have worked with (or me personally) has been confused because the loop index was called ii, jj, kk (or i,j,k). It there is no problem with a short name for this case, why fix it. "Try global replacing (say) i in any source file with a nice name. It is next to impossible not to hit some other i's (say in other variable names, function names, etc)" ??? So your editor/IDE can't do "whole word only" search & replace? That has been standard since... uh, since about ever, or at least the last 15-20 years which amounts to the same thing. :-) Katie, I've written books with Smalltalk :) apw Tuesday, June 10, 2003 The problem with using a short, common name like 'i' is that the C/C++ scoping rules makes it almost inevitable that it'll get reused in an unintended manner. I've seen it happen where a programmer used 'i' in an outer loop, followed by another programmer coming along and adding an inner loop using 'i'. This worked fine until another programmer came along and decided that the second declaration of 'i' must be wrong and removed it. Granted, this is a good example of why you shouldn't hire bad programmers, but unfortunately bad programmers do get hired and even the best programmers occasionally screw up. Removing a variable declaration should cause the program to not compile. It shouldn't cause the program to behave in a completely different manner. This particular issue occurred due to the differences between Visual C++ 6.0 'for' loop scoping and Standard 'for' loop scoping. If you don't do a lot of porting between compiler's that have different 'for' loop scoping rules, it might be less of an issue. I don't see the use of i, j, etc. in math as a particularly good argument for using it in programming. If anything, it's a good argument for why you shouldn't use 'i' given the common confusion caused by its use in math as an index, a unit vector, and the square root of -1. >> What would you name a collection of Employee objects, for example? > >Employee[] >Employee[1] >Employee[2] >etc I was actually referring to collection objects, such as Java's ArrayList. Using i,j,k is a coding convention. Not using them breaks that convention. While one of my mantras is "a foolish consistency...", I don't see this one as foolish. Variable names are labels to help the next guy who reads the code. Since it's a convention, then anyone who has any business being in the code, should immediately recognize for(int i=0;i<value;i++) as a simple loop with a counter. More importantly, if they see dataGrid.Columns[i]=value; they should know they're in a loop. However dataGrid.Columns[iColumn]=value; does *not* automatically communicate the loopness of the variable. So by *not* using i,j,k you're losing community readability of code. There's nothing wrong with breaking conventions, so long as you have a strong reason to do so. IMHO "adding readability at the cost of readability" is debatable. My $.02 Philo Philo Tuesday, June 10, 2003 "iColumn" makes much more sense than the ambiguous "i", especially in complex code. No competent programmer would have a problem attributing "loopness" to "iCount" in a well written program. good: for(iRow = 0; iRow < MaxRows; iRow++) for(iColumn = 0; iColumn < MaxColumns; iColumn++) dataGrid.Columns[iColumn]=value; yucky: for(j = 0; j < MaxRows; j++) for(i = 0; i < MaxColumns; i++) dataGrid.Columns[i]=value; for(j = 0; j < MaxColumns; j++) dataGrid.Columns[j]=value; The first example is much easier to follow and will be much more reliable to maintain. njkayaker Tuesday, June 10, 2003 I fail to see how 'i' is more clearly a loop than 'iColumn'. I've seen 'i' used frequently outside of a loop (for example, in function parameter lists taking an index or as a variable taking the result of a search function). I hope you don't trust that every 'i' is in a loop. When I see 'i', I think 'index'. When I see 'iColumn', I think 'index of column'. I fail to see how 'index' is more useful information than 'index of column'. Pick which line has an error in it: (a) dataGrid.Columns[i]=value; (b) dataGrid.Columns[iRow]=value; While the argument about naming counters has the whiff of irreconcilable dogma about it, I would like to offer two points. The case for using single-letter variable names is stronger when the loop is only a few lines and can all be taken in with one glance. The case for using descriptive names is stronger when the loop comprises more lines of code, especially if the start and end of the loop cannot be seen simultaneously in the editor. Names like Counter, iRow, iColumn are no better than i,j,k because they are artificial (except possibly for a spreadsheet) in that they bear no relation to the data. If you have an array of the monthly expenses for each employee, then looping over Month and Employee (or something similar) provides insight to someone looking at code in the loop. However, using iRow and iColumn tells the reader nothing more than i and j would. In other words, it is obvious what "expenses[Employee][Month]" refers to, but "expenses[iRow][iColumn]" is no more informative than "expenses[i][j]". jcr Tuesday, June 10, 2003 You're correct that it matters more for large loops than small loops, but the problem is that small loops often become large loops. Using 'i' introduces a maintence burden when you expand the loop since you're either stuck with 'i' or you have to replace 'i' with a more appropriate name (thus increasing the possibility of introducing a bug in code that previously worked). I agree that in most circumstances, 'iColumn' would be a useless name. However, in this example, it was being used to iterate columns in a datagrid and thus makes perfect sense. Er, so does noone else use each loop counter in one place: the loop, and where you alias the current object? Like so: for(int i=0;i<employees.size();++i) { Employee *emp=employees[i]; //do stuff with emp } When I mentioned 'for shape in shapes' above, this is what I was getting at. You want to hide the looping construct so you can concentrate on what you are doing, and so the reader can see what you're doing in the body of the loop -- having to refer to the loop counter all the time, be it 'i' or 'integerCurrentEmployeeLoopIterationIndexCounter' is a distraction. Does anyone else use this? If you don't, why not -- is it a bad idea do you think? I use this kind of thing all the time, personally. (Which is probably why out of 219 for loops in my current project only about 15 have a loop counter that doesn't match [ijxy] :) "irreconcilable dogma" (jcr): not at all. "i" is highly ambiguous and is easily confused with j, k, etc. In short, simple code, it's OK but there is really no reason that a better name can't be used. Single letter loop iterators are used out of habit, precedence (i.e. "it's been done before), or lazyness. Using iRow to iterate months has no justification, clearly. No one is suggesting doing that. In the example shown, "iColumn" is a very reasonable name to iterate Columns[]. someone said: "Variable names are labels to help the next guy who reads the code" which is exactly what I think. then someone else said: "I've seen 'i' used frequently outside of a loop" my god Id shoot the swine who did that. 'i' is a terrible variable to use anywhere _except_ inside a loop, it carries no meaning and its job as a label to help the next guy is unfulfilled. The advantages of using it inside a loop are: short, lets programmer focus on the code that actually does so. and that works nicely except for more complicated code...I tend to agree that sometimes variables such as iColumn, or iEmployee etc can give make the code more readable, where thats true they should of course be used. bottom line: i should _never_ be used outside a loop and should only be used inside a loop if it improves readability. (its my belief that it often does) FullNameRequired Tuesday, June 10, 2003 I'd be happy to shoot the swine who did that (and other things like it) but unfortunately that's illegal :) For what its worth: I believe the origins of using i, j, k for loop variables came from Fortran. They were automatically defined as integers. OTOH, I may be wrong... ShowingMyAge Tuesday, June 10, 2003 Just when I thought I'd seen it all some guys come along to protest the use of i as a loop variable. Oh well... What's next, maybe a campaign against the hard-to-read "+" sign instead of writing a clear self-documenting Add function? Add(2,3) is so much better than 2+3! After all, "+" is only used out of habit, has no justification, and the fact that it's the standard mathematical operator doesn't mean anything since, you know, SOMETIMES it can mean something else in mathematics! Who's with me on this righteous crusade to rid the world of the evil of the "+" operator? Chris Nahr Wednesday, June 11, 2003 "Who's with me on this righteous crusade to rid the world of the evil of the "+" operator? " <g> I believe I can make a half-decent case on the evils of overriding the standard operator symbols in c++ if that would help? FullNameRequired Wednesday, June 11, 2003 Tom, I do stuff like this: for(int i=0;i<employees.size();++i) { Employee *emp=employees[i]; //do stuff with emp } all the time. It maps well to std:: containers too. Dereference the iterator at the top and then act on the object in the body. I like it because the code following the loop initialisation reads more clearly and, in the case of std:: containers, it makes it easy to look into the object in the debugger. Then again my code tends towards short functions in a explicit (some say verbose) style. Len Holgate Wednesday, June 11, 2003 Tom, I'll second Len. I use that all the time. On Employee[1] vs Employees[1], I can see what you mean by reading it "Employee 1", but the second still makes more sense to me. I think it's because I read it as "Employees of 1" or "Employees index 1". So to me, Employee[1] would probably suggest that you were indexing the property with index 1 of an employee (this actually works in Javascript). I always suffix my collections with an 's' or with 'List'. One-Armed Bandit Wednesday, June 11, 2003 Chris, your sarcasm doesn't accomplish much other than making it painfully apparent that you have no counter argument. SomeBody Wednesday, June 11, 2003 Chris, if we took your advice, we'd all be programming in Add(Add(C)). Mr. Snrub Wednesday, June 11, 2003 "Chris, your sarcasm doesn't accomplish much other than making it painfully apparent that you have no counter argument." Since your "argument", if one can call it that, basically consists of "I find loops with i hard to understand" I thought it would be easy enough to figure out my "counter-argument": I find loops with i easy to understand. How about that? Yeah, there are those really long and complex loops where I prefer to use "speaking" variables like row or iRow, depending on the type. But generalizing these rare cases to a rule "never use i", especially when propped up with bogus claims like "editors can't search for i" or "sometimes mathematicians use i as the imaginary unit", is really just ludicrous. Redeclaration of a variable isn't a problem either because the compiler will complain. Proficient programmers read and undertand a loop of a few lines as a single unit. The name of the loop variable doesn't matter -- in fact, the shorter the better, because it makes it easier to read the whole loop at once. Using long loop variable names implies you're reading word-by-word, as it were, and that's not appropriate except for complex/long/deeply nested loops. That's odd. In all of my posts, I can't seem to find myself ever saying "I find loops with i hard to understand" or anything like it. Nor did I ever say "never use i". I have no trouble understanding loops with "i". Assuming we're talking about C/C++ (as I clearly was), if your compiler complains about a redeclaration of a variable in nested scopes, you should report it as a bug. I would think that a "proficient programmer" would know this. I'm not sure why you have such a hard time reading "iColumn" versus "i". I can read them both in one glance with no difficulty. I don't know where you got the impression that I was talking exclusively to you -- I wasn't. There were others posting in this thread besides you. I'm currently using C# which in fact does complain about redeclaration in a nested scope, as per the language definition. For C++ you might use PC-lint if your compiler doesn't have a warning for this condition. Allowing variable hiding with no notice is a language design problem, not a variable naming problem. Anyway, using iColumn instead of i won't help you here, nor with the obsolete VC6 for loop scoping, if a column index is required on multiple levels -- and that's not exactly unlikely if your code requires column indexing in the first place. What it boils down is that you like to read iColumn because it makes you happy. That's good for you but hardly a reason why anyone else should adopt this convention. Chris Nahr Thursday, June 12, 2003 I guess the only thing that is important is consistancy. The for-each is cool. VB has it, IIRC. In c++, you have iterators or loop counters. C++ and Java both lack a 'with' operator, which makes pascal so much more readable! In Symbian style, iSomething is an instance variable. So iColumn would confuse a symbian programmer if used as a loop counter. i, j, k is just fine for loops. Sometimes I give my loop counters more explicit names, like 'row' or 'col' or 'idx'. I often see m_something as an instance variable name, and I just described the iSomething convention in Symbian. Personally, I use _something. Much lighter on the eyes imo. I use _somethings for the count of a _something array. So some typical code might be: for(int i=0; i<_somethings; i++) { cout << i << '\t' << _something[i].name << endl; } Well, enough about me, nice to contribute to this long thread. i like i Thursday, June 12, 2003 Recent Topics Fog Creek Home
http://discuss.fogcreek.com/joelonsoftware2/default.asp?cmd=show&ixPost=49522&ixReplies=50
CC-MAIN-2017-17
refinedweb
4,219
71.85
Validation with XSD using XML::LibXML::Schema, and XML::Validator::Schema - From: huntingseasonson@xxxxxxxxx - Date: 27 Nov 2006 18:12:01 -0800 Both XML::LibXML::Schema and XML::Validator::Schema error when I attempt to validate, yet the XML and XSD files appear to be perfectly fine. XML::LibXML::Schema errors with: Element '{}element', attribute 'ref': References from this schema to components in the namespace '' are not allowed, since not indicated by an import statement. Code: my $parser = XML::LibXML->new(); my $doc = $parser->parse_file("TV.xml"); my $v = XML::LibXML::Schema->new(location=>"TV.xsd"); eval { $v->validate($doc); }; die $@ if $@; +++++++++++++++++++++++++++ XML::Validator::Schema errors with: Found <simpleType> illegally combined with <complexType>. at /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi/XML/LibXML/SAX.pm line 64 at ./transform.pl line 234 <simpleType> is allowed to be nested withen a <complexType> correct? As the examples I have seen on the w3c's schema tutorial nest them. LibXML's error, well I thought a "ref" to a element withen the same namespace (none) is perfectly ok. Code: my $v = XML::Validator::Schema->new(file=>"TV.xsd"); my $p = XML::SAX::ParserFactory->parser(handler=>$v); eval { $p->parse_uri("TV.xml") }; die $@ if $@; Both fXML and XSD files are quite long, but I will post if necessary. Im not sure these errors are do to a problem with Perl's implementation, in javax.xml.validation.Validator they validated ok; maybe Java's implementation is more relaxed....? Thanks in advance . - Follow-Ups: - Re: Validation with XSD using XML::LibXML::Schema, and XML::Validator::Schema - From: Brian McCauley - Prev by Date: FAQ 1.13 Is it a Perl program or a Perl script? - Next by Date: Re: modPerl, Apache, and REMOTE_USER - Previous by thread: FAQ 1.13 Is it a Perl program or a Perl script? - Next by thread: Re: Validation with XSD using XML::LibXML::Schema, and XML::Validator::Schema - Index(es):
http://coding.derkeiler.com/Archive/Perl/comp.lang.perl.misc/2006-11/msg01907.html
CC-MAIN-2014-15
refinedweb
322
50.53
.'" Broken. Simple solution. (Score:5, Interesting) Re:Simple solution. (Score:3, Interesting) The Double Click (and other stupid patents) (Score:2, Interesting) That's it. I'm not going to sign up with Netflix (Score:1, Interesting). Intelliflix (Score:5, Interesting) Re:Anyone wanting to discuss this intelligently .. (Score:5, Interesting) Re:Simple solution. (Score:3, Interesting) less objectionable. But when we're talking about business process innovation -- finding new ways to store inventory, or manage relationships with vendors and customers, or hire and retain employees, or deliver goods and services -- then I think the argument is less clear. Presumably you do these things simply to derive a competitive advantage, and the additional profits you expect to earn are incentive enough. It used to be that the PTO wouldn't grant patents for business methods, because they saw them as abstract ideas -- this all changed with the State Street [findlaw.com] case.? Why patents? (Score:1, Interesting) Now, in this case, could it EVER be kept a trade secret? No. So why should everyone else agree not to use the idea without permission when there is nothing given in return (i.e. the idea CANNOT be kep secret, so no secret given up)? the majority. In that case, whatever the majority (or "society") finds desirable is correct. If society decrees that slavery is beneficial, under your model of rights, then slavery is allowed. Under the individual rights model, as the US is founded on, each individual citizen is granted all the rights of every other citizen. You have the right to be free from being enslaved, I have the right to be free from being enslaved, Bob has ... get the picture?. Pretend for a moment that you've been slaving (hehe) away in your basement to create a new method for conducting business that is vastly superior to the well-established companies already in the market. You create a new company to compete with these multi-billion dollar per year corporations, and with your business method you have the potential to blow them away. However, without a patent on your new method, all the established companies copy you immediately. Not only did you not benefit from your hard work, you basically did all your competitors a favor by giving it away for free. You worked for nothing. What's the point in doing it again next time you have a good idea? You tell your story to a few friends, who tell it to a few more friends, and all of a sudden no one wants to innovate. Allowing a patent on your business method gives your startup company a fighting chance to establish itself in the marketplace. The limited term of patents (currently 20 years) means that eventually, yes, all your competitors will be able to use the same business method that made you so fantastically successful. Know what that means? Time to innovate again. Also, for the other companies that cannot use your business method, they must innovate new and even more improved business methods to compete with *you* now - they can't just use your idea and stop there. I wish you damn socialists would just stop complaining that other people have better opportunities and luck than you because they came up with something people want and you didn't. Show me something you've invented or created and shared with the whole world gratis - what's that? You can't? Oh. Don't stand for this. (Score:2, Interesting) Netflix, I cannot express with enough emphasis my disappointment with your decision to sue Blockbuster because they had the audacity to compete with you. I have been a Netflix member for several years and while I find your service superior to Blockbusters (which I canceled after 2 weeks) I do have something it appears you do not believe to be common among your subscribers. That thing is a conscience. If you continue to pursue this shameful attempt to intimidate future startups from trying to compete I guarantee you that I will cancel my account. We Internet users, which constitute a large part of your subscriber base, actually follow these events with keen interest and typically find this practice of yours reprehensible. Patenting a business model, while successful on your part, is seen by many as an abuse of the system. I ask you, on behalf of many of your subscribers, to end this, UN-American attempt to eliminate competition through dodgy manipulations of our legal and patent system. MOZART DID NOT DIE IN POVERTY (Score:1, Interesting) FOR centuries he has been portrayed as an impoverished genius, who wrote begging letters to friends and ended up in a pauper's grave. But a new exhibition claims that Wolfgang Amadeus Mozart lived a solidly upper-crust life and was among the top earners in 18th-century Vienna. Documents on display at Vienna's musical society, the Musikverein, reveal that he earned 10,000 florins a year, a huge sum. "His income put him in the top 5 per cent of the population," Otto Biba, the exhibition's curator, said. gained, the exhibition shows. The documents on display include an invoice for 800 florins from his royal patron, Joseph II. The composer lived in Vienna between 1781 and 1791, the year of his death, aged 35. He was interred in a regular communal grave in accordance with contemporary practice, Mr Biba said. The exhibition, Mozart: A Composer in Vienna, runs until June 30. It displays bills and receipts from the last decade of Mozart's life, and is part of a year of events in Austria celebrating the 250th anniversary of the composer's birth in Salzburg on 27 January 1756. The Guardian -Sj53 HOW CAN YOU PATENT *NOT* DOING SOMETHING? (Score:3, Interesting) Brilliant. Although, since I'm not charging late fees right now I suppose I'm violating netflix patent.
https://slashdot.org/story/06/04/05/0210213/netflix-suing-blockbuster-for-patent-infringement/interesting-comments
CC-MAIN-2016-50
refinedweb
983
61.56
[Update: 2015/08/15] - I now consider this project complete and highly successful. I've been using it IRL for 2 months and its great! I'll likely print out a case for it (and add a project log of course) otherwise it's done. Note This project is not for beginners. It assumes some familiarity with Arduino and the Arduino IDE. Intermediate soldering skills are also required. Also we're pushing the limits of the Atmega328P RAM. So the we use a separate sketch to provision keys. (Note- I originally wrote it as one app and had the key provisioning data in EEPROM. But it was WAY too big to compile once the MPU and GPS parsing code was added. ) While this project is ongoing, its also quite stable. My biggest remaining challenges are to see- - how small can I make the finished hardware? - how many features can I fit into 32k RAM? - How low can I get the power consumption? The current version uses the Arduino Pro Mini at 3.3V which eliminates the need for the boosting regulator that was in the original version. (The first prototype was built from parts I had lying around.) The alarm sits on the FONA like a shield and is about as small as I can make without busting out Kicad . If you wish to follow along and build one yourself, check out the 'Directions' section below. Prerequisites In addition to the Arduino IDE, this sketches use the following Arduino Libraries and will not compile without them- - I2CDevLib: - AdaFruit FONA Library: - RunningAverage Library(included in libraries dir): Software This project consists of 2 sketches- Bike-Alarm and newKey. - Bike-Alarm is (as you might imagine) the alarm sketch. - newKey provisions a new PICC card. In order for everything to work, the RFID encryption keys, sector number and token data MUST match in both sketches. It can also be used to unprovision or test PICCs. (BTW - Please don't use the default key or token! It'll work. But it's like making your password 'password'.) Usage Once the system is installed and configured, to use you simply place the provisioned PICC (card) in it's 'pocket' within range of the RFID reader. Once the reader authenticates the PICC, the alarm emit beep three short beeps, indicating it's disarmed. Remove the PICC and the alarm arms, emitting one long beep. When armed, the Arduino turns on the GPS, then scans the output from the MPU6050. If motion is sensed an SMS with the GPS coordinated, heading and speed of the bicycle are sent to the alert phone. SMS are sent by default every 4 minutes while motion continues or every 10 minutes until the alarm is disarmed. (This behavior can be altered in the config.) The alarm is silent and does not beep when triggered. However, you could also change that in the sketch, should you so desire... (or perhaps even take some other action, like have it voice dial your mobile and yell at the thief via speaker phone? ;-) Troubleshooting If you run into problems there is quite a bit of disabled debugging code in the sketch that can be used with the serial monitor to figure things out. But even enabling the DEBUG #ifdefs is unlikely to work because the sketch uses almost all of the Atmega328P's memory without any debugging enabled. So you'll probably need to enable the debug messages you need 'a la carte' by commenting out the #ifdef and #endif on either side of them. Most errors can be deduced by the beep. If you run into issues you can post your question here on the project page and I'll try to assist. To prevent issues always power up with the PICC next to the reader. If the unit beeps continuously on power up there was an error initializing the hardware. If the unit beeps continuously when arming then there is no GSM network available to the FONA - Check your antenna and SIM. License (GPL v2) is available on the Github project page. Bugs can be reported to info@boffinry.org. This is a work in progress! This does NOT come with any warranty...Read more » Awesome idea/project. Not sure if you are still monitoring this project but I'm just wondering if I swap out the close range RFID for something with about 1m range (so that it acts like a fob like in most cars), would that interfere with the programming/function of it? Regards, Mick
https://hackaday.io/project/6382-nano-bike-alarm/
CC-MAIN-2020-40
refinedweb
756
73.58
! Hello Players, Long time no see? well all i have today is some code. /** * * @author Botifier */ public class MonsterTutorial extends Monster { public MonsterTutorial() { //super("MonsterName", int hp, int atk, int def); super("tutorial", 0, 0, 0); } } this is the code to making a monster... I hope i can release a test soon! ~botifier Today I am going to show you the new update of ani-monsters This is the indev source code fore animon I am posting this for people to create pokemon style games in construct classic this is for making new games... Changelog This is the changelog read please jobs for FlounderGames free gates at the moment please jre 1.6 to run. battle scene with monsters Brand New Ani-Monsters better Monster Textures Different Srarters soon just some minor changes to Ani Monsters like a changed map V2.0.1 Update this is the update full update well a very minor update Ani-Monsters V2 fixed up and other stuff like savegame no password Its the V2 cause the old file broke the game code. fixed it :D my computer Kinda Broke so i cant use construct D: so i need help finding a free to use gamemaker mac or a easy programming language moving into java if possible still need to upload latest version i need to upload latest version totally forgot to say this if you beat five animon you unlock dance and bite i think rank 193 is quite good BotA Coming soon oh I didnt say this game was made by one person me and it was hard my question is can i allow user content to be added to the game through user votes? because my api idea it will require 1.a team 2.Python Knowledge or javascript
http://www.moddb.com/games/animon
CC-MAIN-2017-39
refinedweb
297
65.96
When we check in changes to our product, it's traditional to send check-in email to the people that are impacted (and, if the emails I get are any indication, a dozen people pulled randomly from the Microsoft address book as well). These emails usually say something like: Fixed bug #11881 - added support for negative anti-pressure to the gravitational support code. or sometimes just: #11911 Where the numbers are bug numbers in our bug tracking system (named Product Studio but often referred to as Raid, after it's predecessor). A seemingly irrelevant piece of info that should become slightly more relevant in the near future. Back in April, I'd just listened my way through the Hitchiker's Guide radio shows, and decided to write my checkin email in the form of a radio drama. Which I would have shared with you, except for the fact that I'm not allowed to talk about what I've been doing (yet...). In the weeks that followed, I did a scene from a bad sci-fi movie, a Led Zeppelin takeoff ("Fixed a whole lotta bugs"), a bit of Dickens, and ... Well, you get the idea. Some of them pretty funny, some of them not really that funny, but none of them fit to share. This morning, however, I wrote one that I think I can share with you (or, at least that part without the bug details), so here it is: Checkin mail: Bug Fixes "There are those who think I watch too much TV…" I think they might be right. My group does the same thing. I get an email that an issue has been assigned to me. Recently an automated system was put in to notify me of the same thing. So now I get at least two emails for each issue, and sometimes more as someone adds comments. I’ve had a few recipients put "Unsubcribe" as a joke on the high volume ones. Have you tried a Dr. Suess rhyme, or Harry Potter, or Star Trek beam me up? The possiblities are endless. You could run for the Bulwer-Lytton Fiction Contest .It’s gone to a microsftie this year.Maybe microsoft will have a leading share here as well 😉 Take a look at this – Carburettor breast fantasy wins bad writing prize @ Hello Mr. Eric, C# 2.0 supports many new and interesting features amongst them is that u can set a modifier on the setter or getter of a property. I want to know can I do something like this in an interface as below: interface IMicrosoft { List<Employee> Employees {get; internal set;} List<Product> Products {get; protected set;} } and then do something like below: public class MicrosoftOrganisation : IMicrosoft { private List<Employee> employees public List<Employee> Employee { get{ return employees; } internal set { employees = value; } } //…….. and then the others are implemented } because i wanted to do something like the above and I got like thousands of errors. Can u tell me using a blog post why this doesnt work and whats the workaround of this or give a link to the solution. Umer. PingBack from PingBack from
https://blogs.msdn.microsoft.com/ericgu/2005/08/01/bugfixing-mode-and-checkin-email/
CC-MAIN-2017-47
refinedweb
522
69.41
Edit: as requested I've included the code in 'ledic'. However, it never ran - any of it, not even a hello world printf as first line, so I am relatively sure the problem would never be withinit. Edit2: ironically enough, it was within the 'ledic' function. Looks like I understand even less about this than I previously thought. I am writing for my current project at Uni and no one around me can figure out this segmentation fault. It should be pretty straightforward so I appreciate your help. Code as follows: #include <stdlib.h> #include <string.h> #include <stdio.h> void ledic(FILE *fp){ printf("Hello world\n"); int len; int j, i, k; char palavra[30]; char dictionary[30][10000][30]; int VecOcorrencias[30]; for (j=0; j<30; j++) VecOcorrencias[j]=0; printf("Hello world\n"); while ( fscanf(fp, "%s", palavra) == 1 ) { len = strlen(palavra); k = VecOcorrencias[len]; strcpy (dictionary[len][k], palavra); VecOcorrencias[len]++; } for (i=0; i<1000; i++) printf("%s %d\n", dictionary[5][i], VecOcorrencias[5]); } } FILE *OpenFile( char *nome, char *mode){ FILE *fp; fp = fopen (nome, mode); if( fp == NULL){ printf(" Cant open file\n"); exit(1); } return (fp); } int main( int argc, char *argv[]){ FILE * fp; fp = OpenFile( argv[1], "r"); ledic(fp); return(0); } void ledic(FILE *fp) The declaration char dictionary[30][10000][30]; creates a 9Mb variable 30*30*1000 = 9'000'000. As it is a local variable it is created on the stack and the default stack size on a typical Linux machine is only 8Mb (on Windows it's even only 1Mb). If you declare it as static, the variable is not on the stack and therefore it can take more memory than the stacksize. See this SO article for more details on the static keyword.
https://codedump.io/share/ozwjZILSdfQw/1/segmentation-fault-when-calling-void-function
CC-MAIN-2017-04
refinedweb
300
60.04
Member Since 3 Years Ago 4,265. tronix left a reply on Multiple Connection Use Orm And SetConnection Way,it Can Not Work! Hi, I had this problem too. I solved putting this code in the constructor of your Model <?php namespace App\Models; class SecondModel extends \Illuminate\Database\Eloquent\Model public function __construct(Array $attributes = []) { parent::__construct($attributes); $this->setConnection('yourOtherConnectionName'); // see config/database.php where you have specified this second connection to a different DB } Then your "Test" class must extend this "SecondModel", so that it inherits this connection. Now you can use: Test::find($id); // it uses the non-default connection tronix started a new conversation Laravel Uses The Default Queue Even If I Specified A Different Queue/tube I'm using Laravel 5.0.2. I need to use two different queues in my code. They must use the beanstalkd driver. So I specified those queues in config/queue.php: 'default' => env('QUEUE_DRIVER', 'sync'), 'connections' => [ 'sync' => [ 'driver' => 'sync', ], 'bean-high' => [ 'driver' => 'beanstalkd', 'host' => '127.0.0.1', 'queue' => 'bean-high', 'ttr' => 60, ], 'bean-low' => [ 'driver' => 'beanstalkd', 'host' => '127.0.0.1', 'queue' => 'bean-low', 'ttr' => 60, ], [...] In my code, I used: Queue::pushOn('bean-low', new SendEmail($message )); My listener is: php artisan queue:work --daemon --queue="bean-high","bean-low" --tries=3 --env="production" My actual environment is "production". It seems ok, but Laravel uses always the default queue (the "sync" driver) even if I specified a different queue. I tried to change the default driver to a fake one and I've seen that it uses this driver (throwing an exception). If I specify the "bean-high" or "bean-low" connection as the default driver in the queue.php file, my queues works correctly, but the queue/tube parameter in "Queue::pushOn" is always skipped. What am I doing wrong? tronix left a reply on Google Map Problem I had the same problem. The map is hidden because you didn't specify the height of the . I solved adding a "height: 400px" to the map-canvas-0 id. You can add this css style to your file: into thetag. Every "map-canvas-xy" IDs are targeted by that css rule. Hope this helps
https://laracasts.com/@tronix
CC-MAIN-2019-13
refinedweb
369
58.69
IRC log of egov on 2010-11-02 Timestamps are in UTC. 08:00:56 [RRSAgent] RRSAgent has joined #egov 08:00:56 [RRSAgent] logging to 08:01:13 [sandro] RRSAgent, make logs public' 08:01:14 [sandro] RRSAgent, make logs public 08:01:20 [sandro] People in room, in order: 08:01:20 [sandro] Karen Myers 08:01:20 [sandro] Sandro Hawke 08:01:20 [sandro] Jeni Tennison 08:01:20 [sandro] Daniel Dardailler 08:01:21 [sandro] Roger Cutler 08:01:23 [sandro] Phil Archer, W3T + Talis 08:01:24 [karen] karen has joined #egov 08:01:27 [sandro] Martín Álvarez, Fundación CTIC 08:01:29 [sandro] Thomas Bandholtz Germany -- LD Environrment Data 08:01:31 [sandro] Antonio Sergio Cangiano, SERPRO 08:01:33 [sandro] Jose Leocadio, SERPRO 08:01:35 [sandro] Yosuke Funahashi, Tomo-Digi Corporation 08:01:37 [bandholtz] bandholtz has joined #egov 08:01:37 [sandro] Vagner Diniz 08:01:39 [sandro] Karen Burns 08:03:16 [PhilA] PhilA has joined #egov 08:03:30 [PhilA] scribe: PhilA 08:03:35 [PhilA] scribeNick:PhilA 08:03:39 [karen] Daniel: Are we going to talk about the creation of a task force to look at education and outreach? 08:03:51 [martin] martin has joined #egov 08:03:55 [PhilA] DD: Raises issue of non-tech education & outreach 08:04:04 [PhilA] .. (as possible agenda item later) 08:04:33 [PhilA] Karen: 1.5 yrs ago we had an active task force 08:04:40 [PhilA] .. comm team etc. planning lots of stuff 08:04:59 [PhilA] .. then there was a shift in priorities, and Josema left. It was very effective when we were doing it 08:05:27 [PhilA] .. I have a personal interest. We have some support from our PR firm that has a knowledge base in this area. 08:05:37 [PhilA] .. but it's US-based. Need a more global view 08:06:03 [PhilA] DD: There is funding from the EU to help PSI 08:06:11 [PhilA] Karen: I like the idea of a TF. 08:06:31 [PhilA] .. if there's a need for an IG just looking at that, all well and good 08:06:40 [PhilA] DD: we could spin off other groups from the IG 08:07:08 [PhilA] Karen: We need high level messages - what is open data, what is Linked data etc. 08:07:17 [PhilA] PhilA: Talis is interested in this ;-) 08:07:29 [PhilA] Sandro: Others? 08:07:46 [PhilA] Interest in the room from New Zealand, Brazil and more 08:08:02 [sandro] Karen B, Vagner 08:08:05 [karen] Vagner Diniz, Karen Burns 08:09:16 [PhilA] action: Daniel D to set up task Force on EO 08:09:17 [trackbot] Created ACTION-118 - D to set up task Force on EO [on Daniel Bennett - due 2010-11-09]. 08:10:14 [PhilA] Topic: Linked data at data.gov.uk 08:10:25 [PhilA] Jeni: Takes the floor... 08:10:40 [PhilA] .. shows data.gov.uk website 08:10:50 [PhilA] s/website/Web site/g 08:10:59 [sandro] ACTION-118 is really on Daniel Dardailler not Daniel Bennett. 08:11:03 [PhilA] ( ) 08:11:31 [PhilA] Jeni: Most data is in CSV or XML. Some, but not much, LD 08:11:54 [PhilA] .. explains the term 'organogram' to mean org chart, organisational info etc. 08:12:26 [PhilA] .. an edict from gov said that all departments should publish their organograms on data.gov.uk, and it specified what info had to be included 08:12:38 [PhilA] .. about 62 on d.g.u now 08:13:04 [PhilA] .. majority published a PDF of their organisational structure 08:13:28 [PhilA] .. pretty pictures with tables that don't help a lot as there's no data to pull out 08:13:45 [PhilA] rrsagent, make logs public 08:14:10 [PhilA] Jeni: some of the org charts use headings defined centrally 08:14:16 [PhilA] .. some published as Power Point 08:14:27 [PhilA] .. senior post data includes reporting structures 08:14:32 [PhilA] rrsagent, draft minutes 08:14:32 [RRSAgent] I have made the request to generate PhilA 08:15:02 [PhilA] Jeni: shows a CSV file 08:15:24 [PhilA] .. talks about 'Gridworks', now renamed 'Google Refine' 08:15:45 [PhilA] .. see 08:15:51 [PhilA] Roger C: That's cool! 08:15:56 [PhilA] Jeni: yes it is! 08:16:13 [PhilA] .. important tool for cleaning up data 08:16:23 [PhilA] .. sometehing that non-specialists can use 08:16:37 [PhilA] .. Demos Google Refine 08:16:55 [PhilA] .. You can see the facets for a column, edit values that have gone wrong, edit column names 08:17:46 [PhilA] .. the key point is that civil servants can use this tool 08:18:05 [PhilA] .. we have gone round training a bunch of civil servants. Lots of good feedback. People have begun using it 08:18:32 [PhilA] .. extremely nice features around reconciling data around already published data 08:18:57 [PhilA] .. you can ask the tool to reconcile a column 08:19:11 [FabGandon] FabGandon has joined #egov 08:19:15 [sandro] gridworks "reconcile" to link to web data. nice! 08:19:17 [PhilA] .. turns strings into links (if it finds relevant data) 08:19:41 [PhilA] Jeni: You can do a bit of manual work to produce clean RDF without actually handling RDF (knowlingly) 08:19:45 [PhilA] .. you can apply scripts 08:19:56 [PhilA] .. shows adding a column for, in this case, provenance 08:20:08 [PhilA] data.gov.uk tries to keep track of where we get data from 08:20:24 [PhilA] s/data.gov.uk tries to keep track of where we get data from/..data.gov.uk tries to keep track of where we get data from/ 08:21:14 [PhilA] .. and if I open up a script (in this case, a bit of JSON). Paste that in and apply those instructions - it will perform various tasks, creating extra columns etc. 08:21:25 [PhilA] .. my script adds in lots of URIs in this case 08:21:34 [PhilA] .. (URIs central to linked data) 08:22:15 [PhilA] .. DERI has created a plug in that describes the data 08:22:40 [PhilA] .. now can export the data as turtle or RDF/XML 08:22:58 [PhilA] (Shows RDF generated from the CSV) 08:23:23 [PhilA] Jeni: You can see the different posts within 'BIS' (Department of Business Innovation and Skills) 08:23:37 [PhilA] .. we run several stores, mostly hosted by Talis 08:23:39 [sandro] (I wonder if there's a way to simplify that script application process....) 08:23:53 [PhilA] .. they bring together data sets for, say, transport 08:23:58 [PhilA] .. then one on education and so on 08:24:06 [PhilA] .. organogram data is "reference data" 08:24:17 [PhilA] i.e. 08:24:49 [PhilA] (Shows SPARQL queries against BIS organogram data). Live. No safety net 08:25:09 [PhilA] Voila! Some results 08:25:38 [PhilA] Jeni: Most people, including developers, don't react well to being asked to write SPARQL queries 08:25:56 [PhilA] .. so we have added a layer on top of the SPARQL to provide a simpler API 08:26:06 [PhilA] .. I'll show you the basic Linked data API first of all 08:27:31 [PhilA] 08:27:42 [PhilA] Shows how this gives a 303 to 08:27:56 [PhilA] demos exploring the data 08:28:21 [karen] q+ 08:28:49 [PhilA] ack ka 08:28:56 [PhilA] Karen: This is fabulous 08:29:05 [PhilA] .. practical question - who is updating the data? 08:29:33 [PhilA] Jeni: the generic answer is "how long is a piece of string". Some data changes daily, some changes much less frequently 08:29:58 [PhilA] .. for organogram work, the stipulation was that data should be valid on 30/6/10 and should be updated every 6 months 08:30:08 [PhilA] Karen: How did the departments react? 08:30:22 [PhilA] Jeni: It was hard. it took a big stick from the Cabinet office to get it done 08:30:37 [PhilA] Jeni: Most departmetns have generated just a PDF or a POwer Point 08:30:48 [PhilA] .. some generated a CSV (prob by HR with help from IT dept) 08:31:06 [PhilA] .. generation of RDF was done by me (x 6). One dept has done it themselves 08:31:16 [PhilA] Karen: And they can navigate this UI? 08:31:41 [PhilA] Jeni: This UI is designed to show them the benefit of doing it as LD. Shwoing that people can navigate around the data 08:31:49 [PhilA] .. you can see the different sources of the data 08:32:02 [PhilA] Sandro: Is everyone's salary info public by law? 08:32:15 [PhilA] Jeni: Top civil servants - although it's not by law, it's the culture 08:32:40 [PhilA] Roger: Who wants to do this and why? 08:33:01 [PhilA] Jeni: WE have a strong developer community in the UK. They want to get hold of gov data, package it and so on 08:33:22 [PhilA] .. they usually want to pursue this for lobbying or political ends 08:33:45 [PhilA] Jeni: person X is claiming ABC on their expenses, is this right? 08:34:14 [PhilA] .. personally I don't find that the most interesting data that governments can put out but it is where the current political drive is in the UK 08:34:22 [PhilA] Karen: it is tangible though 08:34:34 [PhilA] Jeni: School performance is something that people can relate to as well 08:35:15 [PhilA] Jeni: completes demo 08:35:37 [PhilA] .. this helps people explore the data and find out where the data came from 08:36:34 [sandro] exploring 08:36:40 [PhilA] .. shows XML data, or JSON data - the interface allows you to access the data in various formats. Just add .xml or .json to the URI. That's what the Linked data API is about 08:37:16 [PhilA] Jeni: So much for the data, available as an explorer and as data for developers. But it's not especially pretty 08:37:25 [PhilA] Jeni: so let's see if we can find a pretty output 08:37:39 [PhilA] Demos BIS organogram visualisation 08:38:12 [PhilA] 08:38:51 [PhilA] Sandro: Does it go all the way ip to the prime minister? 08:39:17 [sandro] sandro: if you want to get on this giant org chart, give us your RDF 08:39:24 [PhilA] Jeni: Not yet, but that would be cool, especially if it came out of all the different data sets created by different departments. The overall org chart comes out of its component parts - if you use linked data 08:39:45 [PhilA] Jeni: Getting to an end to end story like this has taken several months 08:40:04 [PhilA] .. we had to work out what URIs should look like for different departments. This is a department within a department, a unit etc. 08:40:28 [PhilA] .. we had to create some vocabularies for organisational structures generally and then specifically for UK 08:40:35 [PhilA] .. provenance data is very important 08:40:58 [PhilA] .. statistics around salary costs - needed a vocabulary for talking about statistical dta 08:41:17 [PhilA] .. and those fundamnetla design choices etc. had to be done to support the kind of end to end story we've been looking at here 08:41:36 [karen] q+ 08:41:40 [PhilA] Sandro: Those vocabularies sound like candidates for standardisation 08:42:32 [Vagner-br] s/fundamnetla/fundamental/ 08:42:38 [PhilA] Roger: AIUI you started by defining standardised things. In the tool you had a reconciliation step that knew what to do with the data. So it must have been pretty close for automated reconciliation 08:42:44 [PhilA] .. what does that depend on? 08:43:21 [PhilA] Jeni: Gridworks takes the values that it finds in the column. Takes a sample, sends it to a reconciliation service - an API for this kind of thing 08:43:47 [PhilA] .. the Rec service looks at the values, looks at the data it has, and works out what it looks like and what vocab is appropriate 08:43:50 [sandro] sandro: I've put those vocabularies, as best I understood, into the GLD WG Work Items list, 08:45:38 [PhilA] .. recognising "John Smith" as a name cf. "Smith, John" is something the reconciliation service does. Leigh Dodds (Talis) created a good example of this 08:46:08 [PhilA] See 08:46:48 [PhilA] Further discussion on how this works between Roger, Jeni and Sandro 08:47:11 [PhilA] Roger: How does a salaray get recognised as a salary 08:47:17 [PhilA] Jeni: That's in the RDF schema 08:47:24 [sandro] sandro: so reconciliation takes strings which are intended to be identifiers and turns them into proper URI identifiers 08:47:32 [PhilA] .. and we can use the CSV column name as the hook 08:47:49 [PhilA] Roger: so "salary" might match and "sal" won't 08:47:51 [PhilA] Jeni: yes 08:48:07 [PhilA] Roger: So there's a certain amount of fixing up of "user data" 08:48:08 [sandro] q? 08:48:09 [PhilA] ack kar 08:48:24 [PhilA] karen: What is the UK gov policy towards the APIs? 08:49:26 [PhilA] jeni: The Linked data API is on Google Code and anyone can use it 08:50:09 [PhilA] Talis implementation in PHP 08:50:39 [PhilA] Karen: Are you shouting about this? 08:50:42 [PhilA] Jeni: yes 08:51:06 [PhilA] Sandro: The Linked data API work was presented at various meetings 08:51:20 [PhilA] karen: so it needs more outreach 08:51:33 [PhilA] Roger: I'd like to hear more about how politicians talk about this? 08:51:41 [PhilA] Jeni: Gordon brown got it and understood it 08:52:02 [sandro] It's a possible item for GLD WG: 08:52:43 [PhilA] .. current government see it as part of the transparency agenda. Making data available in a machine readable format 08:59:45 [PhilA] Roger: Made the point that organisational capability, software support etc. is really important for commercial companies etc. 08:59:54 [PhilA] Vagner; Jeni talks about visualisation 09:00:09 [PhilA] .. has W3C done any work on visualisation? 09:00:20 [PhilA] Sandro; beyond CSS and SVG, I'm not aware of any 09:00:37 [PhilA] Vagner: You added this item on the WG. I wonder if it's something we need to discuss? 09:00:57 [PhilA] Sandro: That's coming out of the data.gov.uk work but I don't know any more detail 09:02:53 [PhilA] PhilA: I think an RDF-SVG link would be cool 09:03:21 [PhilA] Fabien: Talks about an existing effort to link CSS, SPARQL and more 09:03:45 [PhilA] Topic: Martin Alvarez, CTIC 09:04:08 [PhilA] Martin: Shows map drawn in SVG, lots of tables in RDF so we're already linking RDf and SVG 09:04:16 [PhilA] Sandro: What's the linkage? 09:04:25 [PhilA] Martin: I think it's Java 09:04:32 [PhilA] Martin: begins talk 09:04:42 [FabGandon] Cytoscape combines SPARQL CONSTRUCT with a graph interface to allow the user to select and render RDF data 09:05:09 [PhilA] s/Topic: Martin Alvarez, CTIC/Topic: Open data initiatives in Spain/ 09:05:21 [PhilA] Martin: Open Data act 2007 09:05:30 [JeniT] JeniT has joined #egov 09:05:53 [PhilA] .. aim to create catalogue of open gov data 09:06:05 [FabGandon] more precisely the S*QL plugin for cytoscape 09:06:26 [PhilA] .. 3 regional governments (Asturias) Basque and Catalonia 09:06:50 [PhilA] Shows Asturias catalogue 09:06:58 [PhilA] Martin: only 4 data sets but all linked 09:07:12 [John] John has joined #egov 09:07:36 [PhilA] .. uses things like the organisation vocab, iCal etc. 09:07:49 [PhilA] .. project is 100% linked data, hosted on our won Oracle triple store 09:08:15 [JeniT] s/won/own 09:08:16 [PhilA] .. we've added some Jena modules (and our own) to create SPARQL endpoints etc. 09:08:27 [PhilA] .. metadata modelled using VoID 09:08:41 [PhilA] .. HTML view generated dynamically 09:09:19 [PhilA] .. Basque country is similar but is focussed on raw data. They have some RDF links but they're static files to describe the data sets 09:09:30 [PhilA] .. more than 1,000 data sets in raw formats 09:09:37 [PhilA] .. useful info for citizens anda industry 09:10:05 [PhilA] .. translation memories (Euskara -> Espanol etc.) 09:10:18 [PhilA] .. Catalonia is a new one 09:10:33 [PhilA] .. this will be similar to Basque country initiative 09:10:42 [PhilA] .. most data will be in raw formats (CSV, XML etc.) 09:10:47 [PhilA] .. they will provide some info in RDf 09:11:01 [PhilA] .. as well as RDF static files 09:11:15 [PhilA] .. we're also creating a catalogue using DCAT 09:11:33 [PhilA] .. See 09:11:41 [PhilA] rrsagent, draft minutes 09:11:41 [RRSAgent] I have made the request to generate PhilA 09:11:44 [FabGandon] S*QL plugin for Cytoscape presentation here 09:12:12 [PhilA] Martin: they will present > 26K vCards in RDF, describing public centres, using linked data approach 09:12:59 [PhilA] .. as well as the regional governmetns we also have Zaragossa, Gijon and Barcelona as cities in the project 09:13:04 [PhilA] .. hope to have more info next month 09:13:18 [PhilA] s/Zaragossa/Saragossa/ 09:13:38 [PhilA] .. Saragoss will be using linked data. Should be first city to adopt this 09:13:44 [PhilA] .. they're also using DCAT 09:14:06 [PhilA] .. Gijon is a simple project 09:14:26 [PhilA] .. adapting a CMS to provide RDF content representations in parallel byt adding RDFa to pages 09:14:45 [PhilA] .. we conclude that most governmetns are interested in publishing many data sets quickly 09:14:54 [PhilA] .. they want to release the data 'now' 09:15:00 [PhilA] .. they want good headlines 09:15:18 [PhilA] .. they are neutral on idea of linked data 09:15:38 [PhilA] .. they 'know' that semantic modelling is hard and they don't want to spend more time and money on it 09:15:48 [PhilA] .. for us it's easy to create examples. It's not so easy for the developers 09:15:58 [PhilA] .. maybe we need more examples like the Linked data API to help 09:16:15 [PhilA] .. this would help to help to foster the use of the linked data info 09:17:05 [PhilA] Jeni: It is the case that making data useable and reusable is hard. Linked data is no harder. It's making the data clean that's hard. 09:17:19 [sandro] jeni: Making data reusable is hard (not semantics, per se) 09:17:33 [karen] q+ 09:17:33 [PhilA] Martin: we are trying to convince them using these examples. we gather their spreadsheets and show the linked data examples 09:17:47 [Ibrahima__] Ibrahima__ has joined #egov 09:18:13 [PhilA] ack kar 09:18:28 [martin] Example of linked data representation 09:18:31 [PhilA] Karen: Can you say a little more about the time and money. What levels of government are you working with? 09:19:12 [PhilA] Martin: The best example is Catalonia. They called us 15 days ago and said they wanted to have an open data site within a month. Can you help? 09:19:20 [PhilA] .. speed was major concern 09:19:33 [PhilA] .. get the data we have out there 09:20:09 [PhilA] .. they are convinced that linked data is a good solution, they want to follow it, but they prefer spending their resources in developing open data site, specifying the licence 09:20:17 [PhilA] .. LD comes later? 09:20:22 [PhilA] Karen: So who called you? 09:20:53 [PhilA] Martin: Not an IT person. More close to the citizenry 09:21:04 [PhilA] .. not sure of actual department 09:21:17 [PhilA] .. some are closer to the IT departments 09:21:23 [PhilA] Sandro: What was their motivation 09:21:32 [PhilA] Martin: They know about linked data because we told them about it 09:21:46 [PhilA] .. most of them haven't heard about LD before 09:22:05 [PhilA] .. they know open data initiatives, not linked data 09:22:14 [PhilA] ..we managed to convince them ;-) 09:22:39 [PhilA] Sandro: Any other questions? 09:22:46 [PhilA] .. then we'll take our break now 09:23:01 [PhilA] rrsagent, draft minutes 09:23:01 [RRSAgent] I have made the request to generate PhilA 09:23:36 [sandro] 09:25:11 [John] John has joined #egov 09:30:24 [John] John has joined #egov 09:42:46 [John] John has joined #egov 09:55:54 [bandholtz] bandholtz has joined #egov 09:58:43 [FabGandon] Datalift: 09:58:49 [FabGandon] FabGandon has left #egov 10:06:03 [sandro] topic: Fabien Gandon on France's DataLift Project 10:06:08 [karen] karen has joined #egov 10:06:53 [sandro] fabien: I'm not speaking for all of France! This is just one accepted project. Accpted in june, kickoff was at end of September. 10:07:11 [sandro] ... Not a lot to show yet, but now is a good time to give us feedback. 10:07:46 [leocadio] leocadio has joined #egov 10:07:49 [sandro] ... Last year at ISWC we had a meetup, and discussed the lack of data.gov project in France 10:08:23 [sandro] ... We considered a prototype in Talis; first question --- where will the data physically be stored? In the UK or France? 10:08:32 [sandro] ... considered cloud in Europe 10:08:48 [sandro] ... datalift == lifting from raw data to rdf in France 10:09:31 [sandro] ...Atos Origin will be integrator, building an open source integrated platform. As side effect they'll be ready to offer services 10:09:50 [sandro] ... Mondeca is a KR firm in Paris, doing industrial knowledge modeling 10:10:41 [sandro] ... Academics: INRIA at Grenoble (aligning schemas), Eurocom, Lirmm (the guy from INRIA got promoted there). 10:10:59 [sandro] ... I'll be using DataLift as a scenario for pushing Named Graphs 10:11:21 [sandro] ... INSEE has all the national statistics for France, IGN has all the maps 10:11:47 [sandro] ... Fing is new generation of tools - use cases and business models 10:12:03 [sandro] ... Phase 1: an easy open end of data, open platform 10:12:28 [sandro] ... not re-inventing wheel. We'll re-use existing solutions if they pass our benchmarks; all dev will be open source. 10:12:49 [sandro] ... - Assist the selection of data 10:13:17 [sandro] ... (every thing must be proven on INSEE and IGN data) 10:13:26 [sandro] ... - identify appropriate schemas 10:13:39 [PhilA] q+ to ask about licensing/openness of IGN data 10:14:33 [sandro] ack PhilA 10:14:33 [Zakim] PhilA, you wanted to ask about licensing/openness of IGN data 10:15:11 [sandro] phil: glad to see IGN in there (we have Ordnance Survey, in UK, which does the mapping); OS wants money for some of the data. 10:15:59 [sandro] fabien: IGN has to get half their budget from sales, so that is a concern 10:16:03 [David] David has joined #egov 10:16:20 [sandro] roger: RDF only, or OWL too? 10:16:34 [sandro] fabien: We'll use OWL when the scenario calls for it 10:17:01 [sandro] fabien: We are concerned about speed of reasoning, so we'll have to strike the balance 10:17:07 [MoZ] MoZ has joined #egov 10:17:34 [sandro] sandro: you don't have to do the reasoning 10:17:49 [sandro] fabien: it depends on the scenario 10:18:16 [sandro] roger: Is this typical in eGov, to do this tradeoff? 10:18:57 [sandro] fabien: Everyone needs to make this kind of tradeoff 10:19:06 [sandro] jeni: we're mostly staying away from OWL 10:19:17 [sandro] fabien: if we need some bit of OWL, then we can use it. 10:19:36 [sandro] fabien: With Atos, we'll benchmark every solution and see what scales well enough. 10:20:10 [sandro] roger: in HCLS, I saw a very elaborate authentication scheme, that was depending on just being in RDF [[S?]]. 10:20:21 [sandro] fabien: I heard of this in Freebase 10:20:52 [emma] emma has joined #egov 10:21:29 [sandro] ... not even using RDFS because it was deemed too expensive. 10:21:42 [sandro] ... - format conversion & connectors 10:21:47 [Roger] I believe it was RDFS 10:22:00 [sandro] ... (eg csv to rdf) 10:22:10 [Roger] The system was called S3. It's pretty interesting. 10:22:46 [sandro] ... - data publication itself (led by Atos) 10:22:59 [sandro] ... - interconnecting data 10:23:28 [sandro] .. eg URI for Paris connected to other URIs for Paris 10:23:33 [sandro] ... (or re-used) 10:24:01 [sandro] phil: What about talking to developers about using the data? 10:24:12 [sandro] fabien: Yes, we should have raised that topic more. 10:24:27 [sandro] ... it's one thing to show how to publish data; it's another thing maintain it 10:24:31 [Roger] Sorry -- S3DB 10:24:59 [sandro] ... our developers mostly don't speak SPARQL and many don't speak English. 10:25:15 [sandro] ... so a cookbook in English wont be enough 10:25:32 [sandro] TB: (missed question) 10:25:37 [sandro] fabien: As soon as possible 10:26:15 [sandro] fabien: Other topics: visualize, API for mobile, clouds, legal advice, cookbook 10:27:16 [sandro] fabien: can you legally protect a URI? 10:27:32 [sandro] phil: *boom* TimBL exploding on hearing that [imagined] 10:27:57 [sandro] fabien: R&D challenges: 10:28:05 [sandro] ... methods and metrics for schema selection 10:28:27 [sandro] ... balance of specific needs & reusability (I think there is a tradeoff between usability and reusability) 10:28:43 [sandro] ... data conversion & identifiers generation 10:29:03 [sandro] ... automation of dataset interconnection (via Jerome Euzenat) 10:29:32 [sandro] ... named graphs [hopefully aligned with RDF 1.1), provenance, licenses and rights 10:29:34 [Roger] S3DB Permissioning: 10:30:33 [sandro] ... First 18 months get platform running by www2012 in this building in Lyon!, then 18 more months. 10:30:47 [sandro] ... user's club -- folks who want to use it 10:31:19 [sandro] ... includes City of Bordeaux 10:31:28 [sandro] ... Various Liaisons 10:31:56 [sandro] sandro: how much money is the funding? 10:32:22 [sandro] fabien: 3 years, about 2-3k per year, some more for leader. 10:32:45 [sandro] fabien: may create related sub-projects. 10:33:05 [sandro] fabien: we're trying to disturb the environment to create bubbles. :-) 10:33:32 [sandro] Topic: Linked Environment Data in Germany (Thomas Bandholtz) 10:38:42 [sandro] tb: Open Environment Data in the 90s 10:38:52 [sandro] ... Aarhus Convention 1998 10:39:06 [sandro] ... European Env. Agency (EEA) until 2002 10:39:25 [sandro] s/until 2002/ 10:39:38 [FabGandon] FabGandon has joined #egov 10:39:57 [sandro] ... Environmental Agencies in Germany 10:41:12 [sandro] ... (slide 4) 10:42:09 [sandro] ... INSPIRE based on open geospacial consortium, nor RDF yet 10:42:21 [sandro] ... access to raw data in OGC feature service 10:43:26 [sandro] ... many public sector portals about water, soil, etc --- web pages, pdf, csv, xml of web services --- exhausting harmonization process 10:44:31 [sandro] ... sub-clouds like Linked Open Drug Data, linked to dbpedia; we probably wont use dbpedia as the central ref point, but it looks like they will map to us. 10:45:03 [sandro] ... (slide 13) 10:45:57 [sandro] ... (slide 14) 10:46:51 [sandro] ... GEMET and EUNIS published as Linked Data by EEA 10:47:26 [tlr] tlr has joined #egov 10:47:41 [sandro] ... (slide 15) 10:51:05 [sandro] ... (slide 17 has involve rdf vocabs) 10:51:20 [sandro] ... SKOS, SKOS(XL) -- only stable/w3c 10:51:24 [sandro] ... Dublin Core 10:51:27 [sandro] ... geonames 10:51:36 [sandro] ... linked events ontology, for the chronicle 10:51:44 [sandro] ... Darwin Core (for species) 10:51:53 [sandro] ... SCOVO 10:52:16 [timbl] timbl has joined #egov 10:52:20 [sandro] fabien: I think there's a commercial version of geonames for more/better/current data 10:52:30 [timbl] With a different ontology? 10:53:06 [sandro] tb: German govt has their own data, and the agency that owns the data wants to sell it. There's a free version, but it doesn't include the polygons. 10:53:14 [timbl] q+ to OSM 10:53:30 [sandro] tb: We us geograph names; we don't use maps; this river flows through these cities, one by one. 10:53:59 [sandro] tb: sensor web, many developments to come 10:54:01 [David] David has joined #egov 10:54:19 [sandro] tb: Darwin Core seemed to like the version I did of their work using SKOS. 10:54:56 [sandro] timbl: Have you looked at Open Street Map as a source of geospacial? 10:55:09 [sandro] timbl: linkedgeodata.org is a LD mirror of it. 10:55:15 [sandro] tb: I'll take a look at that. 10:55:36 [sandro] timbl: I'm told open streetmap is a better source of data than geonames 10:56:17 [sandro] tb: We use SCOVO or env. specimen bank, and some extensions. SDMX data came along. 10:56:54 [sandro] Jeni: We've looked at using SDMX -- just using the datacube part looks good, as a midpoint between SCOVO and SDMX. 10:57:05 [sandro] tb: We used the specialized subproperties of dimensin 10:57:09 [sandro] jeni: Yes 10:58:00 [sandro] tb: In skox-xl, class literals, so you can link labels. 10:58:24 [sandro] tb: inflectional forms of one word, extended properties of label class. 10:58:29 [timbl] For an RDF mapping see LinkedGeoData.org 10:58:38 [sandro] tb: you could talk about this for years, we never came to an end. 10:58:38 [PhilA] s/skox-xl/skos-xl/ 10:58:55 [sandro] tb: (slide 18) 10:59:26 [sandro] tb: SPARQL end points -- can easily give accidental Denial of Service attack. :-) 10:59:57 [sandro] tb: but providing SPARQL would be nice. 11:00:14 [sandro] tb: authentication and access control would be good. 11:00:17 [timbl] (or a default limit =1000 for non-authenticated users) 11:01:07 [sandro] sandro: 4store includes a built-in resource limit, but default 11:01:32 [sandro] fabien: we built in a default limit, although that can confuse users who dont know about it. 11:01:46 [sandro] tb: This is good advice 11:02:53 [sandro] RRSAgent, pointer? 11:02:53 [RRSAgent] See 11:03:26 [sandro] RRSAgent, draft minutes 11:03:26 [RRSAgent] I have made the request to generate sandro 11:03:55 [PhilA] PhilA has left #egov 11:07:09 [martin] martin has left #egov 11:18:06 [johnlsheridan] johnlsheridan has joined #egov 11:19:00 [bandholtz] bandholtz has joined #egov 11:39:00 [johnlsheridan] johnlsheridan has joined #egov 11:56:44 [johnlsheridan] johnlsheridan has joined #egov 12:01:22 [john_] john_ has joined #egov 12:16:21 [johnlsheridan] johnlsheridan has joined #egov 12:25:07 [David] David has joined #egov 12:37:17 [Vagner-br] Vagner-br has joined #egov 12:38:16 [karen] karen has joined #egov 12:39:02 [timbl] timbl has joined #egov 12:40:21 [bandholtz] bandholtz has joined #egov 12:50:08 [darobin] darobin has joined #egov 12:53:55 [tlr] tlr has joined #egov 12:58:44 [leocadio] leocadio has joined #egov 13:00:28 [JeniT] JeniT has joined #egov 13:00:29 [tlr] tlr has joined #egov 13:06:44 [FabGandon] FabGandon has joined #egov 13:06:45 [jaeyeollim] jaeyeollim has joined #egov 13:09:03 [PhilA] PhilA has joined #egov 13:09:22 [sandro] topic: 13:09:54 [tban] tban has joined #egov 13:10:05 [JeniT] sandro: using same model as RDF Core Work Items list 13:10:28 [PhilA] Sandro: inspiration for methodology here is the RDF Core 13:10:36 [gautier] gautier has joined #egov 13:10:46 [JeniT] sandro: four categories for the work items 13:10:57 [JeniT] sandro: 1. helping deployment happen 13:11:11 [JeniT] sandro: 2. liaison items such as provenance & named graphs 13:11:30 [JeniT] sandro: 3. vocabulary items 13:11:54 [JeniT] sandro: 4. other technical development work items such as design patterns for URIs 13:12:22 [JeniT] sandro: promised charter by end of January 13:12:31 [JeniT] sandro: would mean start in April, running for two years 13:12:55 [JeniT] sandro: expect F2F meetings to be useful but hard for people to travel, so may try split F2F meetings 13:13:30 [JeniT] ... video conferencing between two places 13:13:57 [JeniT] ... to specific work items: 13:14:07 [JeniT] ... 2.1 Procurement Definitions 13:14:17 [JeniT] ... @johnlsheridan mentioned that this is an issue 13:14:58 [JeniT] ... having standardised definitions of terms/products to include this in ITTs etc 13:15:35 [timbl_] timbl_ has joined #egov 13:15:47 [JeniT] PhilA: something that is very important for government procurement 13:16:15 [JeniT] ... similar to WCAG guidelines, governments can point to them and say 'you must produce according to these standards' 13:16:57 [JeniT] FabGandon: would this include success stories? 13:17:02 [JeniT] ... real scenarios? 13:17:13 [JeniT] Sandro: not in this piece 13:17:22 [JeniT] Sandro: beautiful license out of UK 13:17:35 [JeniT] ... could be understood as a human 13:17:44 [JeniT] ... is there something we can do internationally? 13:17:53 [JeniT] ... having a list of licenses used in different countries? 13:18:03 [JeniT] FabGandon: I've been using double licensing 13:18:38 [JeniT] ... RDFa/GRDDL profile was licensed LGPL and a french license 13:19:10 [JeniT] Sandro: yesterday Daniel talking about getting bicycle accident data 13:19:18 [JeniT] ... had to sign a paper license 13:19:31 [JeniT] ... included things to say that he had to keep his application up to date 13:19:54 [sandro] vocab for describing licenses 13:20:24 [sandro] sandro: let me query for datasources I;m allowed to use for my app 13:20:45 [JeniT] FabGandon: something to indicate where licenses are roughly equivalent 13:21:44 [sandro] jeni: maybe some recommendations about what makes a good license for gov data --- allowing reuse 13:22:08 [sandro] jeni: guidance for licenses which enable the right kind of use 13:22:27 [JeniT] Sandro: 5-10 page note maybe? 13:22:47 [JeniT] Sandro: is this W3C says this or just the working group says this? 13:23:01 [JeniT] PhilA: be hard to have a recommendation for licenses 13:23:14 [JeniT] ... but a recommendation carries more weight 13:23:48 [JeniT] ... how would you include two independent implementations? 13:23:58 [JeniT] Sandro: two governments that follow the practices 13:24:40 [JeniT] ... might make sense to have it as one of several points within a recommendation 13:24:57 [JeniT] ... need the WG to work out what granularity of documents they want 13:25:03 [JeniT] Sandro: 2.3 Community Survey 13:25:14 [JeniT] ... self-sustaining database of vendors 13:25:25 [JeniT] PhilA: would this include apps that use the data? 13:25:38 [JeniT] Sandro: wasn't thinking so but data consuming systems would be good 13:25:47 [JeniT] ... the hardest part is to make it self-sustaining 13:26:11 [JeniT] FabGandon: only example that comes to mind is Semantic Web Tool Wiki page 13:26:19 [JeniT] ... but you're talking about a real database 13:26:31 [JeniT] Sandro: it could be a wiki page, but there are some people who aren't happy with that 13:26:39 [JeniT] ... would give WG freedom to decide how to do it 13:27:38 [JeniT] PhilA: why do you care that this gets done? 13:27:39 [sandro] sandro: it's more important that this is done than that ie be a demo. 13:28:00 [JeniT] PhilA: about the whole government linked data thing 13:28:12 [JeniT] Sandro: got a very enthusiastic yes from the AC 13:28:38 [JeniT] PhilA: building community is very important 13:28:42 [JeniT] ... how far does it go? 13:28:51 [JeniT] ... it's hard to keep it coherent and up to date 13:29:01 [JeniT] ... high hurdle for WGs 13:29:06 [JeniT] Sandro: these lists tend to atrophy 13:29:23 [JeniT] FabGandon: only successful example is this wiki page, because it survived the group that started it 13:29:43 [JeniT] Sandro: even if it doesn't survive the group, the list working for a year or two would be very useful 13:29:49 [JeniT] PhilA: certainly as the group is going 13:30:10 [sandro] jeni: make it be a resource for the WG as it's runnig. 13:30:26 [JeniT] Sandro: would hope that it could aim to be potentially self-sustaining 13:31:05 [sandro] jeni: It should be a success just to have it run during the live of the wg. 13:31:15 [JeniT] PhilA: would hope that at the end someone would want to pick it up and continue with it, but it would not be a failure of the WG if that didn't happen 13:31:28 [JeniT] Sandro: maybe the mediawiki solution is good enough in that case 13:31:42 [JeniT] ... fairly dogfoody, even if RDF is not very linked data 13:32:19 [JeniT] ... helps us make sure that we know who to ping to try to get public review of our specs 13:32:28 [JeniT] ... and is useful to the communities 13:32:36 [JeniT] Sandro: 2.4 Cookbook or Storybook 13:32:48 [JeniT] FabGandon: yes, scenarios and success stories 13:33:09 [JeniT] ... when I talk to people in public sector, as a researcher they think everything I say is science fiction 13:33:22 [JeniT] ... I want a place to point them 13:33:34 [JeniT] PhilA: would that be the equivalent of a use cases document? 13:33:50 [JeniT] FabGandon: use cases aren't always implemented, scenarios are things that are already deployed 13:33:59 [JeniT] ... using UK a lot for this 13:34:13 [JeniT] PhilA: but this would be early input to the group 13:34:33 [tlr] tlr has joined #egov 13:34:35 [JeniT] FabGandon: making them visible in a document gives me something to point to 13:34:45 [JeniT] ... there are best practices 13:34:50 [PhilA] rrsagent, draft minutes 13:34:50 [RRSAgent] I have made the request to generate PhilA 13:35:03 [JeniT] Sandro: use cases tend to abstract from scenarios 13:35:20 [JeniT] FabGandon: GRDDL use cases were a fiction 13:35:33 [JeniT] PhilA: I'm expecting WG to come up with best practices and recommendations 13:35:43 [JeniT] ... need to have scenarios as input for that 13:35:50 [JeniT] ... same function as use cases 13:36:04 [JeniT] Sandro: a product of WG is to have gathered a collection 13:36:17 [JeniT] ... could be written by people associated with scenarios, if we can get them to do it 13:36:33 [JeniT] ... not sure about stories about failures 13:36:57 [JeniT] PhilA: having stories about failure are really useful 13:37:12 [JeniT] ... being able to talk about failures in a constructive way 13:37:20 [JeniT] Sandro: may be hard to do that in published writing 13:37:24 [JeniT] ... but worth a try 13:37:32 [JeniT] Sandro: 3.1 Provenance 13:37:43 [JeniT] ... been incubator running for a year 13:37:48 [JeniT] ... final year is going to recommend WG 13:37:54 [JeniT] ... suspect that there will be one in the next 6 months 13:38:04 [JeniT] ... this group interacting with that group would be useful 13:38:12 [JeniT] Sandro: 3.2 Named Graphs 13:38:18 [JeniT] ... similarly, this interacts with provenance 13:38:28 [JeniT] Sandro: 3.3 POI WG 13:38:39 [JeniT] ... not sure how much government geography is addressed by this 13:38:48 [JeniT] ... think it's just going to be lat/long + polygons 13:38:57 [JeniT] PhilA: I ran workshop that led to POI WG 13:39:10 [JeniT] ... going to be struggle to get them to acknowledge linked data exists 13:39:27 [JeniT] ... one guy from DERI trying to get them to think about it 13:39:38 [JeniT] ... augmented reality main group 13:39:51 [JeniT] ... will need active steering to ensure liaison 13:39:58 [JeniT] Sandro: need a person in both groups 13:40:08 [JeniT] ... I was being optimistic about RDF vocabulary 13:40:14 [JeniT] PhilA: yes, very 13:40:31 [JeniT] ... as interested in moving objects as static 13:40:43 [JeniT] ... and motion in relative direction 13:41:09 [JeniT] Sandro: in worst case, someone could take formal model and map to RDF 13:41:34 [JeniT] Sandro: probably other liaisons I've forgotten 13:41:38 [JeniT] ... SPARQL? 13:41:51 [JeniT] ... don't know exactly what dependency looks like 13:42:07 [JeniT] ... are there any outside of W3C? 13:42:09 [Andre] Andre has joined #egov 13:42:16 [JeniT] ... organisations doing some close to GLD? 13:42:47 [JeniT] PhilA: need people from data.gov from different countries 13:42:54 [JeniT] Sandro: hoping that they get involved in the working group 13:43:01 [JeniT] ... thinking about peer organisations 13:43:16 [JeniT] ... normally have standards, vendors & other standards bodies 13:43:43 [JeniT] FabGandon: wonder if relying on local offices to synchronise locally 13:43:48 [MacTed] MacTed has joined #egov 13:43:54 [JeniT] ... W3C office in Paris will be good point of synchronisation 13:44:11 [JeniT] ... of communicating, diffusing, making sure right people are aware 13:44:17 [JeniT] PhilA: not just national governments 13:44:30 [JeniT] ... colleague talking to Helsinki, Berlin, city authorities 13:44:37 [JeniT] ... not just national governments, but local ones as well 13:45:34 [JeniT] Sandro: check with OASIS and OMG and usual suspects 13:45:51 [JeniT] Thomas: INSPIRE and OGC? 13:46:07 [JeniT] ... they are doing something not so different, but with URNs and XML 13:46:30 [JeniT] ... someone would have to write a technical spec for RDF 13:46:39 [JeniT] Sandro: is there funding available if someone has the skills to do it? 13:46:55 [JeniT] Thomas: it's a EU directive, and each government has people who are working on it 13:47:07 [JeniT] Sandro: seems like the kind of thing that a university might do 13:48:02 [JeniT] Sandro: is it a good model that anyone else might be interested in? 13:48:09 [PhilA] Jeni: Stuart Williams is working with the UK end of INSPIRE to do some mapping of the object modles into RDF 13:48:17 [JeniT] Thomas: harmonising on what each member should provide on each topic 13:48:22 [JeniT] ... they have a dozen themes 13:48:32 [JeniT] ... mandatory data items on each theme 13:48:39 [PhilA] Stuart Williams, formerly of HP, TAG member, now at Epimorphics, Bristol-based Sem Web consultancy 13:48:43 [JeniT] ... we shouldn't care about domain-specific things 13:49:01 [JeniT] ... we could get a huge mass of more data if we mapped into RDF 13:49:08 [JeniT] ... get a lot of benefits from organisational power of INSPIRE 13:49:17 [JeniT] PhilA: the one bit of data that sticks in my head 13:49:25 [JeniT] ... is target for implementation is 2018 13:49:31 [JeniT] ... so don't want to depend on INSPIRE 13:49:36 [JeniT] ... this group would inspire INSPIRE 13:49:49 [JeniT] ... W3C is known to be slow, but we're faster than that! 13:50:01 [sandro] OGC 13:50:01 [JeniT] Thomas: there are many agencies publishing data using OGC services 13:50:21 [JeniT] ... maybe better to talk about SDI 13:50:30 [sandro] spacial data infrastructure 13:50:41 [JeniT] ... they have a G (Global) SDI conference every year 13:50:50 [JeniT] ... have questions about how to publish this in RDF 13:50:56 [JeniT] ... all fragmentary contributions 13:51:04 [JeniT] ... would be a different level 13:51:12 [JeniT] ... they have a catalogue service web, like DCAT 13:51:23 [JeniT] Sandro: is OGC a reasonable way to interact with them? 13:51:27 [JeniT] ... they are W3C members 13:51:38 [JeniT] ... we might be able to get them to participate in a liaison capacity 13:52:00 [JeniT] Thomas: geoSPARQL is one of these topics 13:52:09 [JeniT] ... encoding of sensor observation services in RDF 13:52:15 [JeniT] ... these are ongoing activities 13:52:22 [JeniT] ... not specific for government, but INSPIRE is 13:52:39 [JeniT] Sandro: every nation has a lot of legal issues around geographical information 13:52:52 [JeniT] Thomas: this is one of the things, that you describe the data that you will sell 13:53:04 [JeniT] ... I used to talk about linked data 13:53:26 [JeniT] ... not talking about LOD any more, because we shouldn't exclude non-open data 13:53:47 [JeniT] FabGandon: And accessing the data from my company I have access to things on the intranet 13:54:07 [JeniT] Sandro: these are good pointers, but I'm not sure what it makes sure to do in this charter 13:54:17 [JeniT] ... my thought was that POI would take care of it, but I guess not 13:55:31 [JeniT] JeniT: feels like a rat hole 13:55:40 ) 13:55:46 [JeniT] Sandro: we can make it in scope, out of scope, or get the WG to decide 13:56:11 [JeniT] FabGandon: think it's difficult to rule out geographic data in a government data charter 13:56:19 [JeniT] ... so many scenarios where you need geographical data 13:56:27 [JeniT] PhilA: some liaison would be useful 13:56:57 [JeniT] ... 'we will liaise with POI WG, and be aware of other work going on in this area, but not core duty of GLD WG to codify' 13:57:13 [JeniT] FabGandon: going to be the same with temporal data representation 13:57:29 [JeniT] ... want to say that 'this data is only valid for this financial year' 13:57:32 [JeniT] ... another rat hole 13:57:40 [sandro] PhilA: "We think this is important, and we'll liaise, but we wont develop a vocab for geo" 13:57:51 [JeniT] ... good part is that you don't have proprietary aspects 13:58:06 [JeniT] ... again needs liaison with people in time data 13:58:23 [JeniT] PhilA: this is relevant for POI, because important in crisis management 13:58:45 [JeniT] FabGandon: we have someone who may be involved in this aspect 13:59:23 [JeniT] Sandro: The next two groups were vocabulary and non-vocabulary technical items 13:59:34 [JeniT] ... I had some idea of doing vocabularies later, but let's proceed in order 14:00:02 [JeniT] ... TimBL at dinner last night said something... 14:00:21 [JeniT] ... I had always envisioned that W3C would write the vocabulary, document it and so on 14:00:43 [JeniT] ... but TimBL said that if foaf:name is what people should use, we can say in the W3C Recommendation that that's what people should use 14:00:56 [JeniT] ... but we could set a bar for what we mean for a 3rd party vocabulary 14:01:02 [JeniT] ... and if FOAF can get over that bar 14:01:04 [JeniT] ... then that's fine 14:01:11 [JeniT] PhilA: we wanted to use FOAF 14:01:26 [JeniT] ... and if DanBrickley goes under a bus, the server goes with him 14:01:32 [JeniT] ... (this is in POWDER) 14:01:43 [JeniT] ... got around it by using Dublin Core 14:01:57 [JeniT] ... we had conversations for ages about this, about how FOAF could become more stable 14:02:02 [JeniT] ... doesn't have an organisation behind it 14:02:07 [JeniT] ... could W3C manage it? no 14:02:29 [sandro] jeni: I think there are some important things here, around check boxes for what vocabs we will trust. 14:03:06 [sandro] ... lots of stuff around the org behind it, documented policy on change control, ... it would be useful to document these up front. THESE ARE THE THINGS WE EXPECT A GOOD VOCAB TO DO. 14:03:23 [JeniT] Sandro: going meta, aside from the terms that we recommend... 14:03:30 [JeniT] ... this is going to be useful for Governments as well 14:03:41 [JeniT] ... to help Governments to identify which vocabularies they can use 14:03:56 [JeniT] ... could be GLD or could come from somewhere else 14:04:43 [sandro] jeni; Wider LD cloud might not care so much about stability. Academic projects don't mind so much. 14:04:56 [sandro] fabien: France wont use schemas of the UK. 14:05:07 [JeniT] PhilA: going to be a problem all over 14:05:13 [JeniT] ... W3C isn't designed to manage vocabularies 14:05:19 [JeniT] FabGandon: scalability problems as well 14:05:25 [JeniT] ... only standardise what's domain independent 14:05:29 [JeniT] ... can standardise provenance 14:05:37 [JeniT] ... cannot standardise biology ontology 14:05:43 [JeniT] ... this changes things a little bit 14:05:58 [JeniT] ... here we're crossing that line a bit 14:06:17 [JeniT] Thomas: we don't have to standardise geographical vocabulary, just specifying serialisation 14:06:34 [JeniT] FabGandon: there could be a well-known XML vocabulary, just provide RDFS version 14:06:41 [JeniT] PhilA: I think purls provide the way out of this 14:06:49 [JeniT] ... if it can't be on w3.org 14:06:58 [JeniT] Sandro: I wouldn't say it can't be on w3.org 14:07:05 [JeniT] ... there's the organisation vocabulary 14:07:51 [JeniT] ... @der42 approached TimBL to host it 14:08:01 [John] John has joined #egov 14:08:04 [JeniT] ... there's a maintenance headache that comes with that 14:08:14 [JeniT] ... this is something TimBLs been pushing a long time 14:08:25 [JeniT] ... I've been pushing this for a long time too 14:09:12 [JeniT] PhilA: the person to convince is Ted Gild 14:10:36 [PhilA] s/Gild/Guild/ 14:10:39 [JeniT] Sandro: vocabulary hosting in general is a huge issue for governments 14:10:48 [JeniT] FabGandon: more important than in any other domain 14:11:12 [JeniT] Sandro: I've been advocating that someone like IBM should get into the vocabulary hosting business 14:11:27 [JeniT] PhilA: same issue with Talis hosting it: we're a commercial company! 14:11:33 [JeniT] Sandro: so you get what you pay for 14:12:19 [JeniT] ... could pay a company to host it for a period of time 14:12:30 [JeniT] PhilA: we would host the stuff with a purl pointing to it 14:12:47 [JeniT] ... the purl points somewhere else if Talis goes under a bus 14:12:53 [JeniT] Sandro: I would say domain name per vocabulary 14:13:01 [JeniT] ... foaf.org rather than xmlns whatever it is 14:13:17 [JeniT] ... that gives the most flexibility 14:13:28 [JeniT] PhilA: govvocabulary.org/2010 or whatever 14:13:39 [JeniT] Sandro: but then you bind together several vocabularies in one organisation 14:13:52 [JeniT] ... if they are controlled by different people then you don't want them on the same domain name 14:14:01 [JeniT] PhilA: it's an issue because of neutrality 14:14:05 [JeniT] ... FOAF is a good example 14:14:19 [JeniT] Sandro: were you serious, Fabien, when you said that France wouldn't use any UK vocabularies? 14:14:29 [JeniT] FabGandon: I haven't checked, I know the reaction about hosting the data 14:14:33 [leocadio] leocadio has joined #egov 14:14:50 [JeniT] ... wouldn't be surprised if French objected 14:15:02 [JeniT] ... issue with internationalisation as well 14:15:16 [JeniT] Sandro: would hope that any vocabulary provider would accept translations 14:15:26 [JeniT] PhilA: but who guarantees translation is accurate 14:15:42 [JeniT] FabGandon: in EU, have whole process of maintaining translation of different documents 14:16:09 [JeniT] PhilA: if you had a vocabulary that had anything but a .com, .org ending... 14:16:16 [JeniT] ... no way Americans would accept that 14:16:49 [JeniT] Sandro: end up using .com, .org or .net for the vocabularies 14:17:06 [JeniT] Sandro: 4.1 Metadata for Data Catalogs 14:17:14 [JeniT] ... no brainer that we want to move along DCAT in this group 14:17:29 [JeniT] ... had an interest group telecon with @cygri 14:17:40 [JeniT] ... wanted to spin off taskforce to do it 14:18:00 [JeniT] ... had large group that quickly dwindled 14:18:11 [JeniT] ... stopped entirely when Semtech came around, and didn't start up again 14:18:18 [JeniT] ... lots of interest there 14:18:38 [JeniT] ... bit question is does it end up as WG Note, as a Recommendation, as a pointer to something else? 14:18:42 [JeniT] s/bit/big 14:18:49 [JeniT] FabGandon: how specific is it to eGov? 14:18:59 [JeniT] Sandro: right now taskforce in eGov IG 14:19:23 [JeniT] ... in doing taskforce charter 14:19:34 [JeniT] ... said clearly applicable beyond government 14:19:42 [JeniT] ... but let's take narrower scope for now 14:20:01 [JeniT] ... can see that it could be broader 14:20:07 [JeniT] FabGandon: it could even be a task of the new RDF WG 14:20:14 [JeniT] Sandro: I think it's too late to go there now 14:20:20 [JeniT] ... or in the provenance WG 14:20:35 [JeniT] ... someone asked what's the difference between provenance and DCAT 14:20:49 [PhilA] xLooking at 14:21:01 [JeniT] PhilA: one thing that is missing is refresh rate 14:21:21 [JeniT] JeniT: think that's part of VoiD 14:21:29 [JeniT] PhilA: ah right 14:21:37 [sandro] 14:21:43 [JeniT] ... Alex Tucker has done RDF dump of CKAN data 14:22:02 [JeniT] Sandro: Wiki page includes use cases, deliverables, minutes and participants: 28 participants 14:22:12 [JeniT] ... huge amount of interest 14:22:29 [JeniT] ... reminded that Thomas was listening 14:22:38 [JeniT] Thomas: got a little bit bored... 14:22:49 [JeniT] ... did so much work on data catalogs in Germany... 14:23:01 [JeniT] ... ended up disappointing because no one used it 14:23:15 [JeniT] ... idea of having one data catalog as an access point is not a priority 14:23:24 [JeniT] ... in linked data domain discovery is following links 14:23:30 [JeniT] ... not looking at catalogs 14:23:40 [JeniT] ... it's OK, we need it, but... 14:23:52 [JeniT] Sandro: you don't need 28 people to design a vocabulary 14:23:59 [JeniT] ... you want 3 people to do the work, and wide review 14:24:09 [JeniT] ... you don't want big telecons with everyone who cares 14:24:16 [John] John has joined #egov 14:24:18 [JeniT] ... in general that's going to be true 14:24:35 [JeniT] ... sometimes there will be issues that you want discussion for, but a lot is design by a small group 14:24:48 [JeniT] PhilA: I still think in terms of best practice document 14:24:59 [JeniT] ... say 'use DCAT and VoiD to describe your catalog' 14:25:08 [JeniT] Thomas: how is VoiD involved? 14:25:20 [JeniT] Sandro: DCAT can be for non-RDF data, VoiD for RDF data 14:26:11 [sandro] jeni: Some vocab (dcat) is about EVERY data set, and then some other vocabs are for certain kinds of data (eg geo about geo data, void about RDF data) 14:26:45 [sandro] PhilA: Neither void nor dcat covers refresh rate. 14:27:07 [JeniT] Sandro: I've never heard anyone assess quality or suitability of VoiD 14:27:11 [JeniT] ... only game in town 14:27:58 [JeniT] ... if we're going to recommend a vocabulary, in a recommendation 14:28:05 [JeniT] ... then we need implementation experience 14:28:10 [JeniT] ... which includes going through to consumers 14:28:19 [JeniT] Thomas: VoiD has been designed without DCAT in mind 14:28:27 [JeniT] ... so didn't care about separation of concerns 14:28:36 [JeniT] ... I think someone has to make a new version of VoiD, to fit in 14:29:16 [JeniT] Sandro: we could ask @cygri whether he thinks a new version of VoiD is needed 14:29:27 [JeniT] ... another thing on DCAT is I don't know how it relates to CKAN 14:29:40 [JeniT] ... I don't know how happy CKAN were with it 14:30:04 [JeniT] ... another force in play is the Sunlight Foundation in the US 14:30:18 [JeniT] ... they have done national data catalog that combines Federal, State and Local levels 14:30:48 [JeniT] JeniT: do you need input about what to put in the charter? 14:31:01 [JeniT] Sandro: I feel we should say a W3C Recommended vocabulary along the lines of DCAT 14:31:13 [John] John has joined #egov 14:31:27 [JeniT] PhilA: so the group would create and maintain the vocabulary 14:31:48 [JeniT] Sandro: I think DCAT should enable multiple catalogs, for a decentralised system 14:32:15 [JeniT] ... each catalog should describe itself using DCAT 14:32:24 [sandro] s/catalog/data source/ 14:33:49 [JeniT] JeniT: there's the set of terms (Dublin Core + DCAT + VoiD etc) and the namespace for DCAT 14:34:19 [JeniT] FabGandon: when you look at FOAF, FOAFomatic really helped encourage its use 14:34:36 [JeniT] Sandro: OKFN has a form where they're asking people to fill out questionnaire about their government data 14:34:43 [JeniT] ... be nice if it gave back RDF 14:35:14 [JeniT] PhilA: keen to do outreach as well 14:35:20 [JeniT] ... ideally as part of this working group 14:35:26 [JeniT] ... important part of the implementation 14:35:58 [JeniT] Sandro: OK, add under Procurement Assistance 14:36:10 [JeniT] BREAK TIME UNTIL 16:00 14:36:59 [John] John has joined #egov 14:47:32 [martin] martin has joined #egov 14:47:38 [timbl] timbl has joined #egov 14:52:19 [karen] karen has joined #egov 14:53:36 [tlr] tlr has joined #egov 14:54:23 [David] David has joined #egov 15:01:06 [leocadio] leocadio has joined #egov 15:02:46 [bandholtz] bandholtz has joined #egov 15:02:50 [tban] tban has joined #egov 15:05:09 [FabGandon] scribe: FabGandon 15:05:50 [FabGandon] resuming on vocabularies. 15:06:06 [FabGandon] ... JeniT: what are the next stages? 15:06:54 [FabGandon] Sandro: next stage is identify what can be done within the WG charter/timespan/force 15:07:44 [FabGandon] ... avoid shoot for too little or too much. 15:08:05 [FabGandon] ... identify what can be done in other TF / WG. 15:08:37 [FabGandon] ... for vocs we could work on the basis of having an identified editor for each voc. 15:08:50 [sandro] sandro: maybe the vocabs will each be time-permitting / nice-to-have 15:09:04 [JeniT] 15:09:06 [FabGandon] JeniT: Organization Ontology 15:10:00 [sandro] JeniT: foaf and vcard exist 15:10:10 [FabGandon] ... Dave Reynolds put that together because nothing was putting togerther what we needed about Org. 15:10:30 [FabGandon] ... so we took that and extended that for UK gov. 15:11:03 [FabGandon] Sandro: this is reusable in other organizations. 15:11:32 [FabGandon] PhilA: very UK centric. 15:11:57 [FabGandon] Sandro: this should be blessed by W3C for others to use 15:12:13 [FabGandon] PhilA: an Org.org schema :-) 15:13:20 [martin] In Spain, we use it, and it was OK for our purpose (city council and departments) 15:13:21 [FabGandon] JeniT: change event is used to capture a change in an Organization, it is hook 15:13:31 [sandro] JeniT: changeEvent hook for saying org1+org2 => org3 15:14:22 [FabGandon] Vagner-br: very useful to follow changes in structures and names, acronyms, etc. 15:14:37 [sandro] s/Vagner-br/TB/ 15:14:49 [FabGandon] PhilA: does your national library archives web sites? 15:15:46 [JeniT] FabGandon: In France, we have law that says we must archive every French official media channel 15:15:51 [JeniT] ... and we don't know how to do that 15:16:45 [FabGandon] Sandro: question of ontology engineering process and the way to go for a new voc. 15:17:22 [FabGandon] tban: I wouldn't use UML, this is not object-oriented work 15:17:33 [FabGandon] ... I use TopBraid composer 15:17:57 [FabGandon] ... nice figures. 15:18:29 [darobin] darobin has joined #egov 15:18:38 [FabGandon] ... Richard came up with SDMX but not enough sem. web oriented. 15:19:38 [FabGandon] JeniT: we work with Richard on that because SDMX is important in the statitician community 15:19:57 [sandro] jeni: ONS used SDMX already, so it was opportunistic for us to use it. 15:20:27 [FabGandon] ... SDMX is hard but may be necessary. 15:21:02 [FabGandon] Sandro: we haven't solve the evolution story of how we move from a voc to the next. 15:21:49 [FabGandon] JeniT: also hard to know when a voc is stable enough to be really used. 15:22:13 [Vagner-br_] Vagner-br_ has joined #egov 15:22:17 [FabGandon] ... check list of what you expect from a voc. 15:22:26 [sandro] jeni: checklist item: have documentation which is good, have ref guide, examples, etc 15:22:48 [FabGandon] ... e.g. it must have ref guide, examples, managed by an org with a longevity, etc. 15:23:19 [FabGandon] PhilA: for FOAF for instance the longevity of the domain is a problem. 15:24:17 [JeniT] FabGandon: reading through the minutes yesterday, there's a good thing happening in eGov in that we have very stable bodies involved 15:24:24 [JeniT] ... INRIA is a government institute 15:24:35 [JeniT] ... so we have hosting that is very stable 15:24:42 [JeniT] ... people believe we will continue to exist 15:25:03 [JeniT] ... won't want to use a namespace hosted by the UK 15:25:20 [JeniT] ... but one hosted by a government would have longevity 15:25:46 [JeniT] ... We tried several things, including knowledge engineering approach 15:25:55 [JeniT] ... tried VoCamp approach, where people come with a need for a vocabulary 15:26:01 [JeniT] ... break up in small groups and hack 15:26:07 [JeniT] ... some of these were successful 15:26:20 [sandro] FabGandon: We tried Knowledge Engineering - limits, VoCamp fairly successful, ... 15:26:28 [JeniT] ... depends on scope of vocabulary 15:26:45 [FabGandon] Sandro: this a question for the chairs and the group. 15:26:54 [FabGandon] ... any other org ontology. 15:27:04 [FabGandon] JeniT: there is a blog post from Dave 15:27:11 [sandro] sandro: I'll just link to DER's blog post, with its references 15:27:25 [JeniT] 15:28:00 [sandro] tb: what about sameAs inflation? 15:28:09 [FabGandon] tban: the inflation of sameAs, and misuse of sameAs. 15:28:34 [FabGandon] ... I wouldn't sameAs, but what else. 15:28:59 [sandro] tb: mapping vocab like skos but without inferring it's a skos concept. 15:29:45 [JeniT] FabGandon: subClassOf subPropertyOf also used in alignment 15:29:53 [FabGandon] ... provide a mapping voc with only properties and no classes to avoid inferences 15:30:17 [sandro] sandro: bad sameAs is just bad data 15:30:54 [sandro] FabGandon: in datalift, we are thinking about how to do mapping, from sameAs onto procedural declaration. 15:31:31 [sandro] FabGandon: okaam huge eu project on this -- efficient sameAs resolution for semweb. give uri, it gives back ones which might be equivalent. 15:31:59 [sandro] FabGandon: (let's stay away from this...) 15:32:21 [FabGandon] 15:33:40 [FabGandon] tban: when we try to link e.g GEMET and German Thesaurus we need the same in SKOS without domain and range. 15:35:29 [sandro] jeni: a school is not a skos:Concept according to the SKOS spec 15:35:36 [sandro] sandro: skos is just broken. :-( 15:36:10 [FabGandon] JeniT: same name for a local authority vs. the area 15:36:41 [FabGandon] Sandro: you need to formalize properly. 15:37:31 [FabGandon] tabn: we should include the problems aboout alignment to be discussed in the charter 15:39:28 [FabGandon] JeniT: if RDF 1.1 don't want to do it we have to come up with a convincing scenario 15:40:22 [FabGandon] Sandro: the key thing for people is to see if we can stabilize FOAF. 15:40:26 [sandro] jeni: important to understand how foaf works with vcard 15:40:53 [FabGandon] tban: what about foaf+ssl? 15:41:20 [FabGandon] JeniT: I wondered if we should include something about identitity in the eGov WG. 15:42:04 [sandro] 4.4 Statistical/Data Cube Datasets 15:42:23 [FabGandon] sandro: statistical, so far there is a sub-set of SDMX 15:42:32 [sandro] sandro: I'm hearing there's a subset of SDMX, cube, that's pretty good. 15:42:38 [JeniT] 15:42:48 [sandro] PhilA: It's good for describing what you see in CSVs. 15:43:02 [FabGandon] PhilA: the cube ontology is good to describe the sort of data you find in CSV file. 15:43:55 [FabGandon] JeniT: Cube comes from the hypercube structure of the data. 15:44:09 [FabGandon] JeniT: an observation is a cell in the cube 15:44:27 [FabGandon] ... each dataset is described by a dataset def 15:45:38 [FabGandon] ... for statistical data, payment data, etc. any thing you put in a Spreadsheet 15:45:49 [FabGandon] ... we use it a lot 15:47:03 [FabGandon] sandro: how can be sure this meets most needs? 15:47:33 [sandro] sandro: if we make this a Rec, who might object? Among people who buy into SDMX & RDF already.... 15:48:03 [sandro] PhilA: Statisticians might find this reduces too much. 15:48:32 [FabGandon] Sandro: if we need more of SDMX can we extend it? 15:48:44 [sandro] Jeni: that was the goal, yes. 15:48:48 [FabGandon] JeniT: yes it was designed to be extended 15:49:07 [FabGandon] tban: we use it for measurment data 15:50:11 [FabGandon] JeniT: we wanted to publish statistic for a larger audience than the statistician community 15:50:37 [FabGandon] sandro: if we want to change these schema, how do we do that? what would be the process? 15:51:02 [FabGandon] JeniT: feel free to take it ! 15:51:43 [FabGandon] sandro: it rare that somebody does this kind of work and does follow it as an editor of the Rec. 15:52:12 [FabGandon] sandro: Data Cube seems important. 15:52:24 [John] John has joined #egov 15:52:58 [sandro] [edit] 4.5 Data Quality, Timeliness, Status 15:53:48 [FabGandon] JeniT: I am sure that voiD as something about temporal validity 15:53:50 [sandro] jeni: we use dc:temporal for expressing the temporal range for which the data is true 15:54:03 [FabGandon] ... we have our own small voc for that 15:54:09 [sandro] jeni: we use our own data.gov.uk for draft-ness 15:54:15 [FabGandon] ... nothing on data quality at the moment 15:54:28 [FabGandon] PhilA: can't find this in voiD 15:54:38 [FabGandon] JeniT: in must be in RSS then 15:54:49 [David] David has joined #egov 15:55:04 [sandro] PhilA: Who is responsible for cleaning it up? Who will update it, and when? 15:55:11 [FabGandon] PhilA: need to know if the data I am using now will be here tomorrow 15:55:19 [sandro] PhilA: Ooften the data comes from screen-scraping! 15:55:27 [FabGandon] ... need to know how often data updated 15:55:52 [sandro] FabGandon: This is in Provenance -- an expiration 15:56:23 [FabGandon] JeniT: this is new work probably 15:56:27 [sandro] JeniT: I think this is new work, much less baked than data cube 15:56:50 [FabGandon] sandro: the WG could provide such voc. 15:57:04 [FabGandon] JeniT: it fits under dcat 15:57:05 [sandro] jeni: This goes under dcat -- it applies to data sets. 15:57:42 [sandro] FabGandon: Granularity might be small -- some bit of the data changes often, some bit doesn't. 15:59:10 [sandro] FabGandon: this might not be about the dataset, it might be about one subgraph within the dataset. 15:59:49 [PhilA] rrsagent, draft minutes 15:59:49 [RRSAgent] I have made the request to generate PhilA 16:00:05 [sandro] tb: In the Gazettier, when we have changes in communities, merging, the official service just drops the old communities. We don't drop them, we mark them expired. 16:00:16 [sandro] tb: dcat should describe your policies about such things. 16:00:22 [FabGandon] tban: the policy should be also described on the dcat level. 16:01:18 [FabGandon] sandro: the granularity problem might be more general with dcat and dataset. 16:01:37 [FabGandon] ... granularity can be a political game. 16:02:36 [sandro] sandro: so if dcat can handle the gran. then this can be folded in. 16:02:52 [sandro] 4.6 Assumptions/Basis/Comparability of Data 16:03:17 [FabGandon] JeniT: we need to know if we can compare two values. 16:03:22 [sandro] jeni: In statistical data they really care if you can compare two values, because defn of some bit in your data changed. 16:03:26 [FabGandon] ... e.g. after a policy change. 16:04:09 [sandro] JeniT: annotate a qb:observation to say this is not comparable, etc. 16:04:28 [sandro] JeniT: Vocab for classiying these kinds of annotations 16:04:36 [FabGandon] PhilA: we have a 10 month data vs. an 11 month data 16:04:53 [FabGandon] tban: different methods in differents countries. 16:04:55 [sandro] tb: lining maps up between country, INSPIRE Harmonization effort. 16:05:33 [sandro] FabGandon: The notion of an unemployed person in France is totally different than in some other countries -- not comparable. 16:05:55 [FabGandon] JeniT: encourage people to use different terms when they use different notions 16:06:01 [sandro] JeniT: Sometime you just mean datafr:unemployment has a different URI than datauk:unemployment 16:06:27 [FabGandon] ... there may be some matches but when we use the same URI it IS the same thing 16:06:50 [sandro] JeniT: this is more about same vocab, same dimension, ... this is to annotate where it's different. 16:07:45 [FabGandon] JeniT: at least we should be able to say "this is a statement about comparability". 16:08:03 [sandro] JeniT: This is for categories of ways to annotate observations. 16:08:22 [FabGandon] tban: using different URIs is different from using different terms. 16:09:15 [FabGandon] sandro: no candidate voc on that right now? 16:09:16 [JeniT] 16:09:33 [FabGandon] JeniT: some of the SDMX voc may be relevant 16:09:55 [FabGandon] ... Dave has mapped those onto a voc which could be a candidate 16:10:15 [JeniT] 16:10:56 [sandro] [edit] 4.7 Describing Visualization and Presentation 16:11:10 [sandro] fresnel 16:11:40 [FabGandon] 16:12:36 [sandro] sandro: not hearing a lot of interest/experience on this one. 16:12:45 [sandro] FabGandon: Fresnel has a huge potential 16:13:46 [FabGandon] sandro: design pattern for URIs 16:13:53 [sandro] 5.1 Design Patterns for URIs 16:14:12 [FabGandon] JeniT: updated version: 16:14:22 [JeniT] 16:14:41 [FabGandon] ... it takes a different kind of angle. 16:16:02 [FabGandon] sandro: huge design space, how much we want to expand or focus the design space 16:16:33 [FabGandon] ... should we give all the options or pescribe some good practices? 16:16:45 [sandro] PhilA: use of id, 303 to doc, SHOULD be in LD 16:17:07 [PhilA] I mean - the pattern breaks down as 16:17:11 [sandro] JeniT: sayig do 4.2 from coolURIs 16:17:39 [PhilA] {sector}.data.gov.uk/id/{department}/unique_identifier 16:18:02 [FabGandon] JeniT: sometimes the pattern does work well 16:18:23 [PhilA] If you dereference that, the /id/ gets replaced by /doc/ as part of the HTTP 303 (see other) response, and that leads to a document that describes the original identified thing 16:18:27 . 16:18:32 [FabGandon] ... we used # URIs depending on the dataset. 16:18:44 [sandro] JeniT: just using pattern 4.2 doesn't always work well. 16:18:46 [FabGandon] ... not simple to just say use that pattern. 16:20:02 [sandro] FabGandon: need keys :- 16:20:06 [sandro] FabGandon: need keys :-) 16:20:19 [sandro] sandro: Just get everyone to mint URIs for themselves :-) 16:20:40 [FabGandon] tban: the original URL of TimBL also described what you should not do. 16:21:15 [sandro] tb: '98 cool uris, don't put classifications/datatypes into URI, or other things that would make them change. 16:21:23 [David] David has joined #egov 16:22:20 [sandro] FabGandon: Don't forget there are scenarios where you want to do the opposite -- to anonymous people. 16:23:56 [sandro] tb: I've come to prefer totally opaque URIs. 16:23:59 [FabGandon] tban: generally I prefer URI that don't tell anything by themselves 16:24:54 [FabGandon] sandro: what should we do? 16:25:11 [JeniT] FabGandon: it could be 'follow the guidelines of the LOD group' 16:25:27 [FabGandon] sandro: one output could be follow 4.2 16:25:59 [sandro] sandro: maybe a flowchart, even! 16:26:28 [sandro] JeniT: I found we needed design patterns not just for schools, but also for vocabs, concept schemes, datasets. 16:26:34 [FabGandon] JeniT: we also need design patterns for URIs for schemas 16:27:47 [FabGandon] sandro: versioning of dataset crosses with the temporal point before. 16:29:12 [sandro] sandro: shoud I fold this into designing-URI, or timeliness vocab ? 16:29:32 [FabGandon] tban: what does versioning mean here, e.g. statiscal data changes every year 16:29:33 [sandro] tb: Every year has year more --- discussion of versioning. 16:29:44 [sandro] tb: verionsing of vocab, too. 16:29:59 [sandro] Jeni: how you design URIs, how you design the data.... 16:30:37 [sandro] 5.3 Change Propagation and Notification 16:30:50 [sandro] dady -- dataset dynamic 16:31:16 [sandro] I think of this as protocol, 16:31:40 [sandro] FabGandon: RSS feed of changes -- talis changest vocab 16:31:48 [sandro] JeniT: Sparql push 16:31:52 [JeniT] 16:32:08 [cygri] cygri has joined #egov 16:32:56 [JeniT] 16:33:04 [sandro] seems out of scope 16:33:09 [sandro] JeniT: we need to do it anyway 16:33:27 [sandro] JeniT: (we = data.gov.uk) 16:33:28 [FabGandon] PhilA: also about SPARQL Push 16:34:01 [FabGandon] JeniT: we need that for data that we are publishing every week 16:34:13 [sandro] JeniT: We'll see data published on a weekly basis, so we need 16:34:13 [FabGandon] ... we need to a a design pattern for that 16:34:39 [FabGandon] sandro: just publishing the new data is not enough? 16:34:44 [FabGandon] JeniT: no 16:35:24 [FabGandon] ... links back to the named graphs. 16:36:34 [sandro] FabGandon: It's too big for this.... 16:36:57 [sandro] 5.4 Distributed Query 16:37:22 [FabGandon] sandro: too big to be handled here. 16:37:29 [sandro] same as above -- needs to be done, too big for us. 16:37:54 [FabGandon] SPARQL 1.1 has some elements of answer. 16:38:09 [sandro] JeniT: Maybe it goes into procurement guidelines, eg Sparql 1.1 service descriptions suitable fo rhtis 16:38:16 [sandro] 5.5 Developer-Friendly API and Serialization 16:38:23 [sandro] linked-data api 16:39:01 [FabGandon] sandro: JSON syntax for RDF should be part of the charter of RDF 1.1 16:39:25 [sandro] PhilA: should be relatively easy to get out the door 16:39:57 [sandro] JeniT: Yes, 3 impls, could be fast, but does need wider review -- eg for impementations. 16:40:46 [FabGandon] PhilA: it is manageable and we should pursue this 16:40:47 [sandro] PhilA: this is really important, and doable. 16:40:59 [FabGandon] ... important in terms of deployment 16:41:20 [FabGandon] sandro: will still exist even if we don't do anything within W3C 16:41:44 [FabGandon] PhilA: from a visibility point of you this is important 16:42:48 [sandro] sandro: I'm worried about arbitrary decisions in the design coming back to be a problem in the WG 16:42:59 [sandro] JeniT: the JSON might be a problem. 16:43:39 [sandro] JeniT: I think we're a lot of the way there, but leaning towards its own WG. 16:44:26 [FabGandon] PhilA: need to talk about outreach 16:44:31 [sandro] [edit] 2.5 Outreach 16:44:41 [FabGandon] ... it needs to happen somehow 16:44:50 [sandro] PhilA: somehow this has to happen, perhaps via EU funding 16:45:10 [FabGandon] ... some way to distribute the output of the group among the governments 16:46:05 [FabGandon] sandro: counter argument: the focus of the WG is the how not the why. 16:46:44 [FabGandon] ... the demos of the "how" will make the job of the people doing the "why" easyer 16:47:10 [sandro] robin: In general, WGs are pretty bad at selling their own stuff, being so involved in the technical work. 16:47:50 [sandro] ... people who were writing great blogs went silent when they joined the WG. 16:47:55 [FabGandon] robin: may be outreach should happen outside the WG 16:49:21 [FabGandon] sandro: could still be included in the charter. 16:50:03 [sandro] PhilA: marketing is important in making markets 16:52:05 [FabGandon] sandro: I don't have any exact data about the number of members for the WG. 16:55:24 [sandro] JeniT: great value to have new folks in WG, so people experience having to explain this stuff 16:56:48 [John_] John_ has joined #egov 16:57:04 [martin] martin has left #egov 16:57:42 [FabGandon] FabGandon has left #egov 17:09:04 [PhilA] rrsagent, generate minutes 17:09:04 [RRSAgent] I have made the request to generate PhilA 17:10:29 [PhilA] PhilA has left #egov 17:29:25 [timbl] timbl has joined #egov 17:30:02 [tlr] tlr has joined #egov
http://www.w3.org/2010/11/02-egov-irc
CC-MAIN-2016-36
refinedweb
13,480
62.78
I am trying to serve a static html file, but returns a 500 error (a copy of editor.html is on .py and templates directory) This is all I have tried: from flask import Flask app = Flask(__name__, static_url_path='/templates') @app.route('/') def hello_world(): #return 'Hello World1!' #this works correctly! #return render_template('editor.html') #return render_template('/editor.html') #return render_template(url_for('templates', filename='editor.html')) #return app.send_static_file('editor.html') #404 error (Not Found) return send_from_directory('templates', 'editor.html') Title: 500 Internal Server Srror Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application. Reducing this to the simplest method that'll work: staticsubfolder. static_url_patheither. /static/to verify the file works If you then still want to reuse a static file, use current_app.send_static_file(), and do not use leading / slashes: from flask import Flask, current_app app = Flask(__name__) @app.route('/') def hello_world(): return current_app.send_static_file('editor.html') This looks for the file editor.html directly inside the static folder. This presumes that you saved the above file in a folder that has a static subfolder with a file editor.html inside that subfolder. Some further notes: static_url_pathchanges the URL static files are available at, not the location on the filesystem used to load the data from. render_template()assumes your file is a Jinja2 template; if it is really just a static file then that is overkill and can lead to errors if there is actual executable syntax in that file that has errors or is missing context.
https://codedump.io/share/3VHdKBTuEI5q/1/flask-how-to-serve-static-html
CC-MAIN-2017-13
refinedweb
266
51.55
How Gnomers might save some time (and carpal tunnels) by seeing that C language + GObject == GNU Objective-C How Gnomers might save some time (and carpal tunnels) by seeing that C language + GObject == GNU Objective-C The, like many programs,: GTK+ and its object system are still easy to use and relatively straightforward. I think it is an excellent user-interface library. But if there is one real criticism to be made of GTK use, it is this: at times the sheer verbosity of the C API. It is all the more annoying to know there is no good reason for it: these problems are a direct result of the rules of the C language, which provide a single global namespace for all non-static functions, and completely static typing. Languages are a touchy issue. I hope nobody will take this the wrong way. I don't wish to criticize C or GTK---no language feature can be judged without respect to that language's intent and scope. I merely intend to point out an opportunity to try different tools with this job. Here is my suggestion for improving the situation. Provide a runtime dynamic object library just as is already implemented with GTK+ and planned with GObject, but also provide a minimal set of syntax extensions on top of C, so that all three problems mentioned above just disappear (both in use of GTK/GNOME and in creation of application-specific objects.) No time to design and build something new, you say? But someone has already built a small syntax extension to C that fits the above requirements almost. To learn a new dialect of C is not an easy decision to make. But the GNOME project is already switching to a standardized, general-purpose object system for the 2.0 line of development. In this context, might not some developers be interested in trying something new? It won't be such a big step for those who wish to try. The book GTK+/Gnome Application Development already acknowledges that the original GTK object system is designed to be "runtime-oriented, more like Java or Objective C than C++." (p. 426) There would be no requirement for any piece of code to switch. We need sacrifice nothing that is available in C. This is about conveniences that just aren't available with the stock dialect. All I suggest is that we work to improve the state of GNOME/GTK objective-c bindings so that they stay up-to-date and so that Objective-C applications can work more closely with libraries and applications written in C. (As far as I can tell, the bindings haven't been changed since 1999. I am going to volunteer my help.) Once we have that, we can talk about a developer community and what to do from there. (Either that, or, and this is a long shot,.) The new features. Actually, I suspect C++ is part of the reason we are "stuck". After C++ began to go wrong and grow too large, it lost the original spirit of "C with Classes" Then there was no agreed-upon next step. There was a story here on Advogato a while back, about how C++ wasn't popular in the free-software world. It's like there were no options if you wanted language support for abstract data types or objects in free software---if you need a compiled language, the static C/C++ choice may give you either too little or way too much. Alternative compiled languages have been slow in coming due to lack of availability, but nearly all the free software world has access to Objective C in the form of GCC and GDB. I think it could work (Apple certainly does.) I would ask anyone who's interested to respond to this message and give your opinions and ideas. (Or flames, I have already discussed the idea with some hard-liners. You know who you are. :-) If enough application developers become interested, Objective C could become a more viable alternative to plain C for writing free software in the GTK/GNOME environment. [link to more info on objective c] [Apple's recent book on objective c] [Note about the state of language bindings (from 1999)] Is there anything that can be, or has been, done to truly help fix the situation? I am probably overoptimistic in the extreme, thinking that a new compiled language could arise to anything approaching popularity. But it seems like such a small step. Assuming that a new compiled language might become popular anyway, to me, Objective-C seems like a good candidate, especially considering its newfound popularity in the Mac world. Then again, as jwz pointed out to me, "MacOS was written in Pascal long after Pascal was dead." GTK+/GNOME object system is written in a type-system declared on top of C, which was especially designed to be wrappable. What this means is that unless you are adding new widgets (and most applications are not just adding new widgets) you can code the high-level logic in a higher level language like Python, Perl, Ruby or Guile and have a lot of clarity. This is one of the basic design goals of GTK+, and it achieves it admirably. If you are doing so much coding in C that the clunky calling convention is bothering you, then I think you are using the wrong language for the job. Note that even if you are adding a new widget with a lot of logic, you can still use Python or Perl by embedding the libraries into your widget, and only using C for the GTK+ interface. If they did, they wouldn't be cloning Microsoft Windows. Sure it'll never happen . But maybe it might be time for a new language... Or maybe I should say "Sure it'll never happen, until Microsoft does it." C-Sharp would seem to be a merger of Java and C++.... My basic point is that the free software community should think about moving away from C (and not even consier C++), and into something simpler, without all the stupid quirks we have been putting up with for years. How about even working on a Python compiler? BTW: I use Eiffel. It's not perfect, but it's nice, and far more importantly, clean. This is one of the basic design goals of GTK+, and it achieves it admirably. If you are doing so much coding in C that the clunky calling convention is bothering you, then I think you are using the wrong language for the job. This is exactly what I'm saying! Most GTK+ application development is done in C. It is not just me that could be using a better language, I think many of us are putting up with "the wrong language" simply because it's the one everyone else uses to do GTK applications. I understand and believe in the language-independence goals of GTK+, but until significant groups using other languages come up and organize themselves, then there will still be awkward choices between competing bindings for your given language and there will still be the danger that bindings could fall out of maintenance and break applications. etoffi: Someone above (I'm not pressing back =P) mentioned C with classes. How hard is that to integrate? It can even be aded with a preprocessor, so that the compiler doesnt have to be modified...... Now assuming this is what we want to do, it is already done. You can even pretend objective-C is a C preprocessor plus runtime library (which probably isn't far from the truth.) My point is that it exists now, already has support across the GNU development toolset (GCC, Gnustep stuff), is not linux specific (re: Apple and other communities), has been used on real projects. And on a GNU system, your chance of having the GNU objc stuff and GCC installed actually seems a bit better than writing it in Ruby or maybe even Python. I think the use of Objc would restrict the audience less than those, even for compilation. The idea of creating a new C variant and writing all the code for it and changing compilers does not seem better than using what exists, especially if what we ended up getting was a very static object system influenced by C++. As long as we're building from GTK+, we could use a dynamic system more like the one it does. No, it's not the time for a new language. And it will not be the time for a new language for some years. It's time to think about things. There has been a new hype language every year or two. There's been a new GUI toolkit every year or two. All kinds of shiny new stuff ... every year or two. But nothing really changed or is likely to change - most applications still are garbage and will be garbage for a long, long time. I don't underestimate the value of good tools and the right languages. They are crucial for getting excellent results. But so is a good design, good coding and good quality assurance, not to mention good internal documentation. They are crucial and rare, and that isn't likely to change soon. Of the last 25 problems in ftpcopy: That's although a larger number of problem was found during testing ... And this statistic is for a relatively simple command line utility. I'm not too proud of it, of course. The ChangeLog files of other free software projects show about the same picture, and and my experience with closed source software development isn't any better. Software quality isn't rarely a question of tools or languages but more of a good design, good coding and good testing and even more testing. btw: I've got that lesson before, more than once. It's too easy to forget and fall back into bad habits. If typing out long variables is a problem, get an editor with word completion. Code is written once, then read and edited many times. Objective C is (or was) interesting. Maybe you should consider joining the gnome language bindings effort to help add Objective C support. (James H. tells me there are already Obj-C bindings, but they are not up to date.). If speed matters, it seems you have three choices: C with home-built, non-standard management of function pointers (something I like), C++ with voluntary restrictions on using the more byzantine features (something I like as well, no offense intended to those with Byzantium ancestry), or the bleeding edge of ANSI C++ in its many incarnations. Or I guess C# is an option. But I don't need Microsoft telling me how to behave as a programmer. Do you? I've been using GOB for a bunch of the hacking I've been doing (on a download manager for GNOME). Its a really really nice way of writing GObjects. Its especially nice if you have CORBA GObject bindings... Just to clarify things, the name "Byzantium" is an incorrect name used by the Western Europeans. The real "Byzantium" called themselves Romans, not Byzantines... There is no way to alleviate this difference between C/C++ and languages like CLOS, Smalltalk, Java, Objective-C, etc.. There is nothing faster than an indirect function call from a static table of function pointers.</b>? Yes, and this is equally true for Python or Tcl as demonstrated by drawing editors like Sketch and Impress.? Bah, there is nothing magical about C that makes it easy to wrap, and the GTK scheme isn't particularly so in the grand scheme of things anyhow. The value is really in the ABI (application binary interface). IBM probably had the right idea with their SOM setup. Their object model originated in C, but was a defined *ABI* rather than just a bunch of macros. The resulting binary actually had properties that allowed a client (such as REXX) to open the dll and just start creating objects and calling methods willy nilly. No special bindings. They did their CORBA implementation (DSOM) the same way too. What IBM did when C++ came along was to just make the compiler emit code that was compatible with the SOM ABI, if you wanted. It is slower than normal C++ code of course, but the fact that your C++ program was interacting with, and originating fully functional SOM objects was hidden. They also had a set of macros not terribly unlike the GTK ones for C programmers. This was such a good idea beacause it freed people from working with the ugly C macros and let them write significantly nicer C++ code. I suspect that Objective-C would have been just as good a candidate, since I think it's object model is closer to SOM anyhow. The SOM model let any language capable of producing runnable machine code (I forget, but I think you could make ObjectREXX SOM objects, but you couldn't put those in a DLL that easially) create and consume objects constructed by any other language. Thats a tad better than 'Write in C and have limited utility from any other language' Anyhow, if you want to improve things with the GObject stuff, I'd say get them to write down, and stick to, a binary ABI that was at least as featureful as what IBM had with SOM, then just make your objective C compiler target that ABI. [this is, btw, a joke] makes sense only for languages that *doesn't* have it. Like C. So if you're developing in C++, you must *not* use an auxiliary object system if possible. If you're using a class-based language, then use _its_ classes. This means that if you are using a language like Objective-C, but having to invoke an auxiliary object system, or use wrappers that are inefficient... something's wrong. In fact, I kind of liked the gtk C-- wrapper when I first used it. But then I saw that it was half-done, and I had to abandon it. One of the great things about GUI coding is that OOP fits _extremeley_ well in the picture. You have models, views, controllers, messages being passed around, inheritance, components... Everything seems very good. But then if you are having to write a lot of redundant and repetitive code to get a single window on the screen, then it's not your mistake. If I'm using C++ bindings, it should feel like C++, and the code must be short. I should be able to use genericity, multiple inheritance, exceptions, and see that they help me do my work easier. Well, I don't want to say it, but when I last booted into KDE from my GDM I saw a really neat file and web browser, which was _fast_ and robust. Maybe the gnome guys are not going the right route... As someone said, they are only interested in more bloat that they imitate from MS products. For starters -- The upshot of this stuff is that writing code to load plugins for a program is nigh impossible (and writing libraries is highly fragile). I can hear the wailing already from the C++ fans -- "But don't COM and KParts let us do that?". Yes, they do; but they do it by lots of wacky tricks, most of which involve 'extern "C" {'. In Objective C/Smalltalk/Java/Lisp/Python/Scheme/caml/[insert your favorite actually sane language here] such hackery is not necessary. Even C makes it relatively easy (dlopen). The fact that C++ does not support this should not be worked around: it's an indication of a grievous design flaw in the language at a very basic level. Objective C is far simpler and gives developers what they need. If my word isn't good enough for you, take a look at an OS based on C++ -- BeOS, Microsoft Windows -- and compare it ton one based on Objective C -- NeXTSTEP^WMac OS X. If you're familiar with the APIs for both (or all three), you already know why Objective C is the right idea :-). Overall I agree with the author of the original article: Objective-C is a very attractive alternative to C with object-orientated extensions. Objective-C is underestimated by the majority. For more background onObjective-C check Andreas Beyer's page about StatistX which has a lot of interesting links. This includes the link to GToolKit which actually is a more current Objective-C GTK 1.2 wrapper. Programming has to do with clarity. Objective-C always gave me more clarity then C++. Today I do most development in python. I often hear the argument that Objective-C with the dynamic method lookup and python as "interpreted" language are hit by a performance loss by nature. I regard the additional productivity gain through clarity as being far superior to the performance gains when using something like C. (And for all other situations there are C extension as somebody already pointed out.) On the technical site there sometimes were some problems with gcc's Objective-C runtime support. There are not as many standard extension library as for python or java. Objective-C is proven for big projects (NeXTStep) though. Don't forget that any approach to dynamic method binding at run-time will always be slower by a factor of 2 to 3 over a binding strategy that resolves the proper method at compile/link time. If you only consider the cost of the dispatch of a message, that's true. On the other hand, programs usually do not limit themselves to dispatch messages to objects. They are believed to do something else. Thus in everydays programs, the performance lost is less than 10% which is not so important. Don't forget that NeXT computers were 68030 at 25MHz, programmed in pure Objective C. They were running a graphical interface that was quite complex for the epoch. The question isn't really whether it would be convenient to use Objective-C in conjunction with C to automate/tidy up certain tasks. I think it would. But in practical terms there are enormous obstacles to it becoming a viable applications development language. By 'viable' I mean consistent and up-to- date tool support, public and visible community/educational support, and platform support. Good things: Bad things that would be extremely difficult to overcome: In essence we'd be asked to justify to the universe why we do not just use C++/Java/Python/whatever. There's no way to win: you have to either point out a disadvantage of [foo] or point out something you need that [foo] can't give you. Either way it's a language war, and you can't even win that if you stick to C. It is the classic story of unused languages---technical qualities are nothing in the face of unpopularity and workable alternatives. Without an organized community it may as well be Modula-2. The only way it could succeed would be a lot like the way Perl and friends succeed: a significant and organized group begins publically using the language, educating others, creating community support, and agreeing upon one standardized language binding for each platform (upon which documentation and tutorials could be based.) I'm all for it, but that doesn't count. I got only one email from someone interested in using Objc. If people want anything to happen there'll have to be organization.. When talking performance, lumping Smalltalk and Objective-C in the same category is not the way to go. I used Obj-C for 6 years and Smalltalk (ST) for about 1. I found ST to be 1000% slower than optimized C and Obj-C about 10-20%. These numbers are for average programs I encountered. Objective-C is closer to C++ than any thing else in terms of speed. Also, someone mentioned that GObjects already had a higher level of dynamic binding than C++. Using C++ to access GObjects isn't going to make that go away.? Well I was a NeXTstep person, but "same difference"... Most of your Objective-C is already ordinary C. All your for(), if(), while(), float, int, arithmetic, pointers, arrays, etc. are vanilla C which gets translated to fast machine code. That's why Objective-C performs so well at run time. But at the same time, the method binding is fully dynamic which is why it was so easy to learn, use objects, do dynamic things with them, etc. Note that this flavor of "C integration" is substantially different than other languages like Python. In Obj-C, using C constructs is part of the deal. You never have to "step out of the box" to get it. (Which is good and bad. Good for speed, but occasionally Obj-C apps have the same seg fault/bus error problems that C++ apps do.) [in reference to C++] Is it really so difficult to use productively? In comparison to alternatives such as Objective-C and Python: Yes. ... We are borg. I will immediately buy 38 copies each of "Design Patterns" and "Dianetics" ... :-) ================================================== Glyph had all the right comments about C++, so now I don't have to write them. Now onto Obj-C. I used it for six years. Loved it. Shoved it at everyone I met. But now it's dead. I even said so in a sidebar for article I wrote for the Linux Journal: sidebar: Objective-C: I Knew Him Well article: Using Mix-ins with Python But they axed my last paragraph in the sidebar: Having used Objective-C for six years, I can testify that it's still a good language in many ways, but I also know that Python offers more technical advantages and on-going improvements combined with a lively, growing community. (Is that really too controversial?) One frustration I did have with Obj-C was that there were never any language improvements. Six years and not a drop. After I accepted the truth, I tried to move to Java because popularity does have some advantages, but that didn't cut it. I discovered Python and have never looked back. Python, like all languages, has warts. But the team is active and I get new improvments every year. And it's already better than Obj-C or Java. So I'm sorry if your thread turned into a language discussion, but in reality Objective-C is dead and Python is at least a good place to start (and possibly your best option). Friends who know me, believe. They know what an Obj-C nut I was! :-) I love python. I think it's awesome. But Obj-C code is nearly the same speed as C code, as you pointed out. Java and Python are still not anywhere close, last I checked. I would love for this not to be true though, so someone please tell me python is super fast :) A lot of times this isn't an issue, but certain classes of problems are speed concious. For instance, these days you can make Web applciation servers in python, in java, or in C. And it turns out they work pretty damn well in any of the languages speed-of-execution-wise. But what can I use besides C, to write Icecast in that would have some notion of objects and such? What can I do to avoid the ugly pitfalls that dto mentioned with GTK. For a lot of things now, I use python. But I still haven't found a way to move from C to anything else. ... But what can I use besides C, to write Icecast in that would have some notion of objects and such? What can I do to avoid the ugly pitfalls that dto mentioned with GTK. ... Overall, your point is valid. It is mitigated more often than you might think by the fact that many Python libraries such as file I/O, sockets, GUI, etc. are implemented in C. But there are certainly examples where that doesn't cut it. For example, I wouldn't write a stock market strategy simulator in Python-- that's too CPU intensive. And while some might say that I can always fall back to C, that's not only a pain, but I'm not sure how well it works for a "granular class hierarchy". The classic fall-back-to-C-extensions example for Python is the Numerical library where the object of interest is a matrix of densely packed floating point numbers. Obviously that worked out pretty well, but I usually don't have such large chunky objects comprised mostly of atomic data. Well that settles it: We'll just have to write our own language! :-) (Actually, I would if I had the time...) Just for the record, please don't confuse cause & effect here :) I said the bindings were dead because there is not a huge interest in them, not the other way around. maybe i should just let this die, but ... i dont see too much of a problem with objective-c. speed is not really an issue, as was mentioned above multiple times. people, we have gigahertz machines! get over it! (i am *not* advocating bloat, but just as an example, how fast does microsoft word load?). nowadays, we are moving towards everything being dynamic anyway (eg: dot-net, mozilla) only one comment on the new language? i brought it up because then we could start over -- no warts, and GObject could be built in. while we're at it, we could make a c-sharp frontend. just a thought. anyone looking for a nice language should take a peek at eiffel () The problem of "fragile base classes" (as defined by Ted Lewis in his book on OO Application Frameworks) disappears if you have access to all the source. The C++ compiler does a marvelous job of "re-manufacturing" your code when the slightest change (new member methods or variables) is made to the most fundamental of your base classes. Unless your missing some source you need to recompile. Sorry to equate Smalltalk with Objective-C, performance wise, if there is such a huge gap in performance. I was assuming some modern Smalltalk development environment would have a compiler comparable to those you can get for Common LISP or Java. Ack, I agree that sounded all wrong. I did not mean to imply that you are the cause of the language being unpopular---what I meant is that it does not sound like it's going anywhere if the official toolkit bindings aren't getting enough user interest. I'll remember to preview once more next time :-) I still think it could change, but only if a group of people works in unison to improve the situation. It's a big!
http://www.advogato.org/article/268.html
CC-MAIN-2014-49
refinedweb
4,508
71.55
--- Rhys Weatherley <address@hidden> wrote: > On Monday 13 January 2003 10:03 pm, Vergneau , Cyril wrote: > > > When browsing the GNU implementation of dotnet, I can't see the > > System.Windows.Forms namespace that I broadly use to develop GUIs > under MS > > dotnet. > > We made a decision a while ago that we will use Mono's > System.Windows.Forms > implementation once it matures > (). It > will be hard enough to get one open source implementation of Forms > working, > let alone two. So it is best to share that code. > > > Is it because DotGNU is only made for WebServices development? > > We decide an a case by case basis whether it is useful for us to > develop our > own library, or reuse someone else's. > > We do already support the Gtk# and Qt# widget sets for GUI > development, so web > services aren't our only focus. Who is working on GTK# and the testing of that? I would like to try compiling that with the GTK for win32 work i have been doing... Do i just get GTK# from mono? mike ===== James Michael DuPont __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
https://lists.gnu.org/archive/html/dotgnu-general/2003-01/msg00247.html
CC-MAIN-2022-27
refinedweb
192
76.11
#include <wx/treelist.h> Class defining sort order for the items in wxTreeListCtrl. Default constructor. Notice that this class is not copyable, comparators are not passed by value. Trivial but virtual destructor. Although this class is not used polymorphically by wxWidgets itself, provide virtual dtor in case it's used like this in the user code. Pure virtual function which must be overridden to define sort order. The comparison function should return negative, null or positive value depending on whether the first item is less than, equal to or greater than the second one. The items should be compared using their values for the given column.
https://docs.wxwidgets.org/3.0/classwx_tree_list_item_comparator.html
CC-MAIN-2018-51
refinedweb
106
56.55
straddstr() Concatenate one string on to the end of another Synopsis: #include <string.h> int straddstr( const char * str, int len, char ** pbuf, size_t * pmaxbuf ); Since: BlackBerry 10.0.0, and updates the values of pbuf and pmaxbuf: - If len is zero, straddstr() calls strlen() to determine the length of str. In this case, str must be null-terminated. - The straddstr() function null-terminates pbuf whenever pmaxbuf is nonzero, even if the source string isn't null-terminated (but len must be nonzero in this case). - If len is nonzero, null bytes in the input have no special meaning (i.e., straddstr() doesn't stop copying when it reads a null byte, but it still null-terminates pbuf). - If the full string can't be copied, it's truncated, but pbuf is still null-terminated. Returns: The value of len if it's nonzero; otherwise, the length of str (i.e. strlen( str )). 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/s/straddstr.html
CC-MAIN-2015-48
refinedweb
175
75.1
Moving to .NET Core: HttpModules to Middleware Quite often, we need to inject custom behavior into the request processing pipeline. There are a number of ways to do this in a .NET Framework project, depending on where in the pipeline your behavior needs to take place, and how that behavior affects the rest of the pipeline. One of the most versatile ways to inject behavior was by building a custom HttpModule. While powerful, HttpModules are hard to test, and don’t integrate well with the rest of the code for your project.. In this post, we’ll convert an HttpModule that does custom request logging to custom middleware, and discuss the benefits and potential pitfalls that this powerful new tool brings. Our Starting Point First off, let’s start by taking a look at this sample HttpModule. This module listens to all requests and responses, and logs the calling IP, the request path, the response status code, and the length of the response in bytes. public class WebRequestLoggerModule : IHttpModule { private readonly ILog logger = LogManager.GetLogger("WebRequest"); public void Init(HttpApplication context) { context.BeginRequest += AddContentLengthFilter; context.EndRequest += LogResponse; } private void AddContentLengthFilter(object sender, EventArgs e) { var application = (HttpApplication)sender; application.Response.Filter = new ContentLengthCountingStream(application.Response.Filter); } private void LogResponse(object sender, EventArgs eventArgs) { var application = (HttpApplication)sender; var request = application.Request; var response = application.Response; var responseStream = response.Filter as ContentLengthCountingStream; logger.Info($"Calling IP: {request.UserHostAddress} Path: {request.Url.PathAndQuery} Status Code: {response.StatusCode} Length: { responseStream.Length }"); } public void Dispose() { } } Omitted from this code is the ContentLengthCountingStream. It turns out that the only way to get the length of a response (in both WebAPI and .NET Core) is to override Stream and count the number of bytes that are written to the buffer. It’s also worth noting that UserHostAddress is probably not going to be the IP Address of your actual user, especially if you’re running a reverse proxy in front of Kestrel. This is sample code from the internet–please don’t use it in production! There are a couple of obvious deficiencies to note as we look at the way HttpModules interact with the request pipeline. First and most glaring is the lack of decent typing. BeginRequest and EndRequest are both EventHandlers, which means we get the downright terrible signature of (object, EventArgs). That little gift from C# 1.0 cannot be deprecated soon enough. In addition to the use of EventHandler, both BeginRequest and EndRequest are events, which means we don’t have any way to define the order in which events are handled. In practice, that’s usually fine, but it does mean that if you need something to happen at the very beginning or end of processing, you’re mostly out of luck. Middleware basics Middleware is the basic building block of the .NET core request pipeline. At it’s most basic, middleware is just a series of nested delegates that end by calling your controller. One obvious benefit this provides over the old HttpModule style of pipeline extensibility is a much greater degree of control. Instead of just hooking up event handlers, you can control the exact order in which middleware executes, and can easily short-circuit execution based on the state of the request. There are some limitations to this approach, which we’ll discuss later, but on the whole I’ve been very happy with the power and control afforded by middleware. The first example of middleware shown on Microsoft’s documentation (which is otherwise very good) looks like this:."); }); } } The lambda defined in app.Use is the simplest possible middleware, because it doesn’t actually do anything. context is a HttpContext, and contains information about the request and response, not unlike the HttpApplication in our HttpModule. next contains a delegate that either points to the next middleware (if it exists), or the controller. What they don’t tell you (but they should) is that while it is possible to write middleware like this, it is a terrible idea. There are three major problems with using inline lambdas to write your middleware. First, this makes the middleware basically impossible to test, since the only way to execute it is to actually run a request through the whole pipeline. Second, it adds logic to your Startup, which is already too long and complicated, so adding more configuration than you strictly need is a bad idea. Finally, it prevents you from taking advantage of your IoC container to inject dependencies. Converting our HttpModule to Middleware Fortunately, there’s a different way to build middleware that solves all of these problems! Let’s use that to convert our HttpModule into middleware that performs the same function. First, we’ll make a middleware class: public class WebLoggingMiddleware { private readonly RequestDelegate next; private readonly ILog log; public WebLoggingMiddleware(RequestDelegate next, ILog log) { this.next = next; this.log = log; } public async Task InvokeAsync(HttpContext context) { var wrappedContentStream = new ContentLengthCountingStream(context.Response.Body); context.Response.Body = wrappedContentStream; await next(context); log.Info($"Calling IP: {context.Connection.RemoteIpAddress} Path: {context.Request.Path} Status Code: {context.Response.StatusCode} Length: { wrappedContentStream.Length }"); } } Let’s dig into a couple of things that are going on here. First, you’ll notice that we’re injecting both a RequestDelegate and an ILog in the constructor. This gives us the ability to test our middleware in isolation, using test doubles to simulate the behavior of our dependencies. It’s important to note, however, that middleware is constructed once during application startup, so you can’t put any dependencies that are tied to the request in the constructor. Fortunately, the InvokeAsync method is also invoked using the IoC container, so if you have any scoped dependencies, you can add them as parameters to the method signature and things will work out just fine. Next, looking at InvokeAsync, you’ll notice that we change the response before calling await next(context);. If we wanted to add custom headers to the response, this is a great place to do it. You do need to make those changes before calling next, though, since by the time that call returns the request has already been serialized, so the response is read-only at that point. Finally, a happy consequence of having full control of the request pipeline. We still need to wrap the body with a ContentLengthCountingStream (the implementation is the same as with .NET framework) to get the length of the response in .NET core. On the other hand, because we add it to the response in the same method where we read the value from it, we can avoid casting the response body as a ContentLengthCountingStream. While admittedly not the most important consequence of having full control, it is still a nice benefit. Now that we’ve built and tested our middleware, it’s time to configure it. By adding an app.UseMiddleware<T>() to our configure method in Startup, we can add typed middleware to our pipeline. One of the things that I really appreciate about using middleware is that the order of middleware operations is explicit and easy to configure. Each call to app.UseMiddleware is executed in order, so if some of your middleware needs to short-circuit the execution pipeline, it’s easy to understand what is being skipped. Because we’re doing logging, and want to make sure that even requests that generate exceptions are logged, we’ll want to make sure that WebLoggingMiddleware is the first middleware we add to our application. Other than logging, you’ll probably want exception handling to be your first middleware, because you want to make sure that any exceptions thrown by your middleware are handled correctly. Middleware: The Better Way to Build Request Pipelines Middleware may be my favorite change in moving to .NET Core. Suddenly, the most esoteric and untestable part of building request pipelines in ASP.NET is transformed into a simple, ordinary code. It’s especially liberating to be able to take code that was tied so tightly to the framework, and let it stand on its own merits instead. It reminds me of the transition from highly invasive ORMs and base classes for data to micro-ORMs and POCOs (Plain Old Class Objects). In this instance, at least, the future is great! This is part three of an ongoing series about our transition to .NET Core. For more information, see part 1 and part 2
https://www.pluralsight.com/tech-blog/converting-http-modules-to-middleware/
CC-MAIN-2020-29
refinedweb
1,405
56.25
In this tutorial, we will learn to use the MPU-6050 MEMS module with ESP32 and ESP8266 to measure accelerometer, gyroscope, and temperature values using MicroPython firmware. Firstly, we will see an introduction of MPU6050 such as pinout diagram, pin configuration. Secondly, we will see how to upload the MPU-6050 MicroPython library to ESP boards using uPyCraft IDE or Thonny IDE. In the end, we will see how to get an accelerometer, gyroscope, and temperature readings from the MPU-6050 module with ESP32 and ESP8266. MPU6050 Sensor Module Introduction The MPU-6050 sensor module is a MEMS( Micro Electro-Mechanical System) module which contains an integrated circuit MPU-6050 IC. This chips contains three axis gyroscope, three axis accelerometer and digital motion control processor within a single IC package. On top of that, it also contains an integrated temperature sensor. All these sensors are manufactured on the same die of MPU6050. We can use this module for velocity, acceleration, orientation, displacement and other motion related parameters measurement. Now-a-days all modern smartphones come with a built-in inertial motion sensor. MPU-6050 also belongs to one of these categories of sensors. This sensor provides a complete solution for any six axis motion tracking system. One of the most important features of MPU-6050 MEMS sensors is that it contains a powerful and high processing power digital motion processor (DMP). DMP performs all complex calculations internally before letting the users read data from the sensor on the I2C port. That means we do not have to perform high power calculations on the microcontroller after reading data from the MPU6050 chip. I2C Output Interface As discussed earlier, MPU6050 provides output data on an I2C bus. Therefore, we can use a 12C bus interface of MPU6050 to transfer a 3-axis accelerometer and 3-axis gyroscope values to ESP32/ESP8266. In other words, we can use any microcontroller which has an I2C port to read sensors’ output data. There is a specific dedicated address assigned to each parameter value in the MPU6050 I2C interface. We can use these addresses to get specific values from a sensor such as acceleration, gyro, and temperature. One of the advantages of using the I2C interface of this sensor is that we can interface multiple MPU5060 modules with a single microcontroller. MPU6050 Pinout The MPU6050 chip consists of 24 pins. But only 8 pins are exposed on the pinout of the module. This MEMS sensor module consists of 8 pins and these pins are used for different configurations and used to read data from the sensor. - First one is a VCC pin that is used to power the sensor and 3 to 5 volts dc voltages are applied to power on this sensor. But usually, a 5V power source is provided directly from a microcontroller. - The second [pin is a GND pin which is connected to the source ground and ground pin of a microcontroller. - Pin number three is a SCL (serial clock) pin which is connected to a microcontroller SCL pin to which we want to interface MPU6050 sensor. SCL is a clock pulse pin used in I2C communication. The clock source is provided by the master device which is a microcontroller in our case. - Fourth pin is a SDA (serial data) pin which is used to transfer data to a microcontroller. We connect SDA pin of MPU6050 with a SDA pin of a microcontroller - Fifth one is a XDA (Auxiliary Serial Data) pin which is used to connect external I2C modules with MPU6050 such as magnetometer. But the use of this pin is completely optional. - Sixth one is a XCL (Auxiliary clock) pin which is also connected to another 12C interface sensor to enable its pin from this sensor module. - AD0 (Pin7) : AD0 (Address select pin) which is a 12C slave address select pin.For example, if we use more than one MPU6050 modules with a single microcontroller, this pin is used to vary the slave address for each MEMS sensor. By doing so, each MEMS sensor can be easily distinguished on an I2C bus with its unique address. - INT(Pin8) : The INT (interrupt) pin which is an interrupt digital output pin and used to give indication to a microcontroller that the data is available to read from a MPU6050 sensor module. The following picture shows the pinout diagram of MPU6050 MEMS module: Interface MPU-6050 with ESP32 and ESP8266 As you see, the MPU6050 has 8 terminals but in order to connect with ESP32 and ESP8266 NodeMCU, we will only require the first four pins highlighted in yellow. These are VCC, GND, SCL, and SDA. The table shows the connections between the two modules. The VCC pin is connected with the 3.3V from the ESP32/ESP8266 module to power up. Both the grounds of the two devices are connected in common. The SCL pin of MPU6050 is connected with the default SCL pin of ESP32/ESP8266. Likewise, the SDA pin is connected with the default SDA pin of ESP boards._3<< ESP8266 I2C Pins The following figure shows the I2C pins of ESP8266 NodeMCU: More information on ESP32 and ESP8266 pins is available here: Components Required We will need the following components to connect our ESP board with the MPU6050 sensor. - ESP32/ESP8266 - MPU-6050 MEMS Module - Connecting Wires - Breadboard Schematic Diagrams Follow the schematic diagrams below for both the ESP modules and connect them accordingly. If you are using ESP32 for this project, connect the ESP32 device with MPU-6050 as shown in the schematic diagram below: Similarly, if you are using ESP8266 NodeMCU for this project, connect the ESP8266 device with MPU-6050 as shown in the schematic diagram below: MPU-6050 MicroPython Library By default, MicroPython does not have an implementation of the MPU-6050 library. But, MicroPyhon provides I2C API of ESP32 and ESP8266 which can be used to read values from the MPU-6050 sensor. Fortunately, there is one library available which is developed by Adam Ježek and can be downloaded from this link. Hence, download the following library and upload it to ESP32/ESP8266 board with the name of mpu6050.py. import machine class accel(): def __init__(self, i2c, addr=0x68): self.iic = i2c self.addr = addr self.iic.start() self.iic.writeto(self.addr, bytearray([107, 0])) self.iic.stop() def get_raw_values(self): self.iic.start() a = self.iic.readfrom_mem(self.addr, 0x3B, 14) self.iic.stop() return a def get_ints(self): b = self.get_raw_values() c = [] for i in b: c.append(i) return c def bytes_toint(self, firstbyte, secondbyte): if not firstbyte & 0x80: return firstbyte << 8 | secondbyte return - (((firstbyte ^ 255) << 8) | (secondbyte ^ 255) + 1) def get_values(self): raw_ints = self.get_raw_values() vals = {} vals["AcX"] = self.bytes_toint(raw_ints[0], raw_ints[1]) vals["AcY"] = self.bytes_toint(raw_ints[2], raw_ints[3]) vals["AcZ"] = self.bytes_toint(raw_ints[4], raw_ints[5]) vals["Tmp"] = self.bytes_toint(raw_ints[6], raw_ints[7]) / 340.00 + 36.53 vals["GyX"] = self.bytes_toint(raw_ints[8], raw_ints[9]) vals["GyY"] = self.bytes_toint(raw_ints[10], raw_ints[11]) vals["GyZ"] = self.bytes_toint(raw_ints[12], raw_ints[13]) return vals # returned in range of Int16 # -32768 to 32767 def val_test(self): # ONLY FOR TESTING! Also, fast reading sometimes crashes IIC from time import sleep while 1: print(self.get_values()) sleep(0.05) Uploading MPU-6050 Library with uPyCraft IDE Now, we will look at how to install the MPU-6050 library to be used in MicroPython._7<< - Then replicate the following MPU-6050 library in that file. - Name the file mpu6050.py and save it by choosing your desired directory. - Now press the button DOWNLOAD AND RUN in the tools section. You have now successfully uploaded the MPU-6050 library to ESP32/ESP8266 using uPyCraft IDE. After that, we can use the above library functions to read the accelerometer, gyroscope, and temperature values from the MPU-6050 sensor. You can use a similar procedure to upload files using Thonny IDE. Uploading MPU-6050 Library in Thonny IDE If you are using Thonny IDE , open a new file and copy the code as we did in uPyCraft IDE. - Save the file as mpu6050.py - In addition, head over to Device> Upload Current Script with Current Name You have successfully uploaded the MPU-6050 library to ESP32/ESP8266 using Thonny IDE. MicroPython MPU-6050: Getting Accelerometer, Gyroscope, and Temperature values As we have already uploaded the MPU-6050 library to ESP32/ESP8266 boards. Now we can use the functions available in the MPU-6050 library to get sensor readings. Let’s now look at an example to show the working of the sensor. We will connect our MPU-6050 sensor with the ESP module via the I2C protocol as shown above in the connection diagrams. We will see a MicroPython script code and after uploading it to our ESP boards, we will see readings of Accelerometer, Gyroscope, and Temperature printed on the MicroPython shell terminal. MPU-6050 MicroPython Code Now let’s look at the MicroPython script for MPU-6050 to get sensor readings. Copy the following code to the main.py file and upload the main.py file to ESP32/ESP8266. This microPython script reads Accelerometer, Gyroscope, and Temperature values from MPU-6050 over I2C lines and prints them on the MicroPython shell console. from machine import I2C from machine import Pin from machine import sleep import mpu6050 i2c = I2C(scl=Pin(22), sda=Pin(21)) #initializing the I2C method for ESP32 #i2c = I2C(scl=Pin(5), sda=Pin(4)) #initializing the I2C method for ESP8266 mpu= mpu6050.accel(i2c) while True: mpu.get_values() print(mpu.get_values()) sleep(500) How the Code Works? Importing Libraries Firstly, we will be importing the Pin class and I2C class from the machine module. This is because we have to specify the pin for I2C communication. We also import the sleep module so that we will be able to add a delay of 10 seconds in between our readings. Also, import the MPU6050 library which we have previously uploaded to ESP32 or ESP8266. from machine import I2C from machine import Pin from machine import sleep import mpu6050 Defining ESP32/ESP8266 GPIO Pins for MPU-6050. i2c = I2C(scl=Pin(22), sda=Pin(21)) #initializing the I2C method for ESP32 #i2c = I2C(scl=Pin(5), sda=Pin(4)) #initializing the I2C method for Now, create an object of accel() class from mpu6050 module with the name of “mpu”. mpu= mpu6050.accel(i2c) Inside the while loop, get the sensor reading with using an object “mpu” on get_values() function. After that print the values on micropython shell console. mpu.get_values() print(mpu.get_values()) sleep(500) Demo To test the MicroPython script for MPU-6050 with ESP32 and ESP8266, upload the main.py file to ESP32/ESP8266. After uploading the MicroPython script, click on Enable/Reset button of ESP32 or ESP8266: You will see the Accelerometer, Gyroscope, and Temperature values on shell console: The values Accelerometer/Gyroscope are between -32768 to 32767. More MicroPython tutorials: - MicroPython ESP32/ESP8266: Send Sensor Readings via Email (IFTTT) -: OpenWeatherMap API with ESP32/ESP8266 – Sensorless Weather Station - MicroPython: PWM with ESP32 and ESP8266 2 thoughts on “MicroPython: MPU-6050 with ESP32/ESP8266 (Accelerometer, Gyroscope, and temperature)” Is it the same configuration with a PH sensor module? I don’t think so.
https://microcontrollerslab.com/micropython-mpu-6050-esp32-esp8266/
CC-MAIN-2021-39
refinedweb
1,877
55.54
great way as regular Python modules so the Python docs are an excellent reference for how it all should work. In Python terms, you can place our library files in the lib directory because it's part of the Python path by default. One downside of this approach of separate libraries is that they are not built in. To use them, one needs to copy them to the CIRCUITPY drive before they can be used. Fortunately, there is a library bundle. The bundle and the library releases on GitHub also feature optimized versions of the libraries with the .mpy file extension. These files take less space on the drive and have a smaller memory footprint as they are loaded. Due to the regular updates and space constraints, Adafruit does not ship boards with the entire bundle. Therefore, you will need to load the libraries you need when you begin working with your board. You can find example code in the guides for your board that depends on external libraries. Either way, as you start to explore CircuitPython, you'll want to know how to get libraries on board. The quickest and easiest way to get going with a project from the Adafruit Learn System is by utilising the Project Bundle. Most guides now have a Download Project Bundle button available at the top of the full code example embed. This button downloads all the necessary files, including images, etc., to get the guide project up and running. Simply click, open the resulting zip, copy over the right files, and you're good to go! The first step is to find the Download Project Bundle button in the guide you're working on. The Download Project Bundle button downloads a zip file. This zip contains a series of directories, nested within which is the code.py, any applicable assets like images or audio, and the lib/ folder containing all the necessary libraries. The following zip was downloaded from the Piano in the Key of Lime guide. When you open the zip, you'll find some nested directories. Navigate through them until you find what you need. You'll eventually find a directory for your CircuitPython version (in this case, 7.x). In the version directory, you'll find the file and directory you need: code.py and lib/. Once you find the content you need, you can copy it all over to your CIRCUITPY drive, replacing any files already on the drive with the files from the freshly downloaded zip. Once you copy over all the relevant files, the project should begin running! If you find that the project is not running as expected, make sure you've copied ALL of the project files onto your microcontroller board. That's all there is to using the Project Bundle! Adafruit provides CircuitPython libraries for much of the hardware they provide, including sensors, breakouts and more. To eliminate the need for searching for each library individually, the libraries are available together in the Adafruit CircuitPython Library Bundle. The bundle contains all the files needed to use each library. You can download the latest Adafruit CircuitPython Library Bundle release by clicking the button below. The libraries are being constantly updated and improved, so you'll always want to download the latest bundle. Match up the bundle version with the version of CircuitPython you are running. For example, you would download the 6.x library bundle if you're running any version of CircuitPython 6, or the 7.x library bundle if you're running any version of CircuitPython 7, etc. If you mix libraries with major CircuitPython versions, you will get incompatible mpy errors due to changes in library interfaces possible during major version changes.. There's also a py bundle which contains the uncompressed python files, you probably don't want that unless you are doing advanced work on libraries. The CircuitPython Community Library Bundle is made up of libraries written and provided by members of the CircuitPython community. These libraries are often written when community members encountered hardware not supported in the Adafruit Bundle, or to support a personal project. The authors all chose to submit these libraries to the Community Bundle make them available to the community. These libraries are maintained by their authors and are not supported by Adafruit. As you would with any library, if you run into problems, feel free to file an issue on the GitHub repo for the library. Bear in mind, though, that most of these libraries are supported by a single person and you should be patient about receiving a response. Remember, these folks are not paid by Adafruit, and are volunteering their personal time when possible to provide support. You can download the latest CircuitPython Community Library Bundle release by clicking the button below. The libraries are being constantly updated and improved, so you'll always want to download the latest bundle. The link takes you to the latest release of the CircuitPython Community Library Bundle on GitHub. There are multiple versions of the bundle available. in an examples directory (as seen above), as well as an examples-only bundle. These are included for two main reasons: - Allow for quick testing of devices. - Provide an example base of code, that is easily built upon for individualized purposes. First open the lib folder on your CIRCUITPY drive. Then, open the lib folder you extracted from the downloaded zip. Inside you'll find a number of folders and .mpy files. Find the library you'd like to use, and copy it to the lib folder on CIRCUITPY. If the library is a directory with multiple .mpy files in it, be sure to copy the entire folder to CIRCUITPY/lib. This also applies to example files. Open the examples folder you extracted from the downloaded zip, and copy the applicable file to your CIRCUITPY drive. Then, rename it to code.py to run it. You now know how to load libraries on to your CircuitPython-compatible microcontroller board. You may now be wondering, how do you know which libraries you need to install? Unfortunately, it's not always straightforward. Fortunately, there is an obvious place to start, and a relatively simple way to figure out the rest. First up: the best place to start. When you look at most CircuitPython examples, you'll see they begin with one or more import statements. These typically look like the following: import library_or_module However, import statements can also sometimes look like the following: from library_or_module import name from library_or_module.subpackage import name from library_or_module import name as local_name They can also have more complicated formats, such as including a try / except block, etc. The important thing to know is that an import statement will always include the name of the module or library that you're importing. Therefore, the best place to start is by reading through the import statements. Here is an example import list for you to work with in this section. There is no setup or other code shown here, as the purpose of this section involves only the import list. import time import board import neopixel import adafruit_lis3dh import usb_hid from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode import time import board import neopixel import adafruit_lis3dh import usb_hid from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode Keep in mind, not all imported items are libraries. Some of them are almost always built-in CircuitPython modules. How do you know the difference? Time to visit the REPL. In the Interacting with the REPL section on The REPL page in this guide, the help("modules") command is discussed. This command provides a list of all of the built-in modules available in CircuitPython for your board. So, if you connect to the serial console on your board, and enter the REPL, you can run help("modules") to see what modules are available for your board. Then, as you read through the import statements, you can, for the purposes of figuring out which libraries to load, ignore the statement that import modules. The following is the list of modules built into CircuitPython for the Feather RP2040. Your list may look similar or be anything down to a significant subset of this list for smaller boards. Now that you know what you're looking for, it's time to read through the import statements. The first two, time and board, are on the modules list above, so they're built-in. The next one, neopixel, is not on the module list. That means it's your first library! So, you would head over to the bundle zip you downloaded, and search for neopixel. There is a neopixel.mpy file in the bundle zip. Copy it over to the lib folder on your CIRCUITPY drive. The following one, adafruit_lis3dh, is also not on the module list. Follow the same process for adafruit_lis3dh, where you'll find adafruit_lis3dh.mpy, and copy that over. The fifth one is usb_hid, and it is in the modules list, so it is built in. Often all of the built-in modules come first in the import list, but sometimes they don't! Don't assume that everything after the first library is also a library, and verify each import with the modules list to be sure. Otherwise, you'll search the bundle and come up empty! The final two imports are not as clear. Remember, when import statements are formatted like this, the first thing after the from is the library name. In this case, the library name is adafruit_hid. A search of the bundle will find an adafruit_hid folder. When a library is a folder, you must copy the entire folder and its contents as it is in the bundle to the lib folder on your CIRCUITPY drive. In this case, you would copy the entire adafruit_hid folder to your CIRCUITPY/lib folder. Notice that there are two imports that begin with adafruit_hid. Sometimes you will need to import more than one thing from the same library. Regardless of how many times you import the same library, you only need to load the library by copying over the adafruit_hid folder once. That is how you can use your example code to figure out what libraries to load on your CircuitPython-compatible board! There are cases, however, where libraries require other libraries internally. The internally required library is called a dependency. In the event of library dependencies, the easiest way to figure out what other libraries are required is to connect to the serial console and follow along with the ImportError printed there. The following is a very simple example of an ImportError, but the concept is the same for any missing library. ImportError Due to Missing Library If you choose to load libraries as you need them, or you're starting fresh with an existing example, you may end up with code that tries to use a library you haven't yet loaded. This section example. import board import time import simpleio led = simpleio.DigitalOut(board.LED) while True: led.value = True time.sleep(0.5) led.value = False time.sleep(0.5) import board import time import simpleio led = simpleio.DigitalOut(board.LED) while True: led.value = True time.sleep(0.5) led.value = False time.sleep(0.5) Save this file. Nothing happens to your board. Let's check the serial console to see what's going on. You have an ImportError. It says there is no module named 'simpleio'. That's the one you just included in your code! Click the link above to download the correct bundle. Extract the lib folder from the downloaded bundle file. Scroll down to find simpleio.mpy. This is the library file an M0 non-Express board such as Trinket M0, Gemma M0, QT Py M0, or one of the M0 Trinkeys, you'll want to follow the same steps in the example above to install libraries as you need them. Remember, you don't need to wait for an ImportError if you know what library you added to your code. Open the library bundle you downloaded, find the library you need, and drag it to the lib folder on your CIRCUITPY drive. You can still end up running out of space on your M0 non-Express board even if you only load libraries as you need them. There are a number of steps you can use to try to resolve this issue. You'll find suggestions on the Troubleshooting page.. There is a command line interface (CLI) utility called CircUp that can be used to easily install and update libraries on your device. Follow the directions on the install page within the CircUp learn guide. Once you've got it installed you run the command circup update in a terminal to interactively update all libraries on the connected CircuitPython device. See the usage page in the CircUp guide for a full list of functionality
https://learn.adafruit.com/dotstar-fortune-necklace/circuitpython-libraries
CC-MAIN-2022-27
refinedweb
2,164
65.83
StringBuilderClass As stated numerous times already, the immutable nature of strings can be a blessing and a curse. The latter is especially true if lots of string manipulations have to be made, which effectively results in the creation of lots of intermediary string objects. Although short-lived objects are cleaned up pretty effectively by the garbage collector, having a lot of those, each of which can be substantially big, is suboptimal too. This can often be avoided by making use of the System.Text.StringBuilder class. A few releases of Visual Studio ago, a using directive for the System.Text namespace was added to the default template for newly created code files. An obvious reason for its inclusion is the ... No credit card required
https://www.oreilly.com/library/view/c-40-unleashed/9780132678926/h4_1839.html
CC-MAIN-2019-39
refinedweb
124
56.25
go to bug id or search bugs for New/Additional Comment: Description: ------------ Compiling with PHP-FPM enabled on an older SPARC system will result in /tmp/cc6w5Fh0.s: Assembler messages: /tmp/cc6w5Fh0.s:39: Error: Architecture mismatch on "cas". /tmp/cc6w5Fh0.s:39: (Requires v9|v9a|v9b; requested architecture is sparclite.) Unfortunately my knowledge of SPARC assembly language isn't nearly good enough to fix that. I know that the v9 "cas" opcode does an atomic "compare and swap" operation but I wouldn't know how to translate that into v8 code. Test script: --------------- Copy /sapi/fpm/fpm/fpm_atomic.h to fpm_atomic.c and add bogus main() function: int main () { int result; atomic_t mylock; result = fpm_spinlock(&mylock, 1); } Compile using "gcc -mcpu=v8 fpm_atomic.c" will result in error message given. Expected result: ---------------- Should compile without error. Actual result: -------------- sparky:~# gcc -mcpu=v8 fpm_atomic.c /tmp/cciAbMrC.s: Assembler messages: /tmp/cciAbMrC.s:121: Error: Architecture mismatch on "cas". /tmp/cciAbMrC.s:121: (Requires v9|v9a|v9b; requested architecture is sparclite.) sparky:~# Add a Patch Add a Pull Request As the sparc documentation says (): The SPARC v9 manual introduced the newest atomic instruction: compare and swap (cas) I don't know how to fix this right now. If you know someone who can, he's welcome. I've already asked for help. wait and see Well, I blatantly copied from PostgreSQL's s_lock.h and came up with this: diff -Nau fpm_atomic.h.org fpm_atomic.h --- fpm_atomic.h.org 2009-12-14 09:18:53.000000000 +0000 +++ fpm_atomic.h 2010-11-15 01:50:31.000000000 +0000 @@ -82,7 +82,7 @@ #endif /* defined (__GNUC__) &&... */ #elif ( __sparc__ || __sparc ) /* Marcin Ochab */ - +#if (__sparc_v9__) #if (__arch64__ || __arch64) typedef uint64_t atomic_uint_t; typedef volatile atomic_uint_t atomic_t; @@ -118,7 +118,23 @@ } /* }}} */ #endif +#else /* sparcv9 */ +typedef uint32_t atomic_uint_t; +typedef volatile atomic_uint_t atomic_t; +static inline int atomic_cas_32(atomic_t *lock) /* {{{ */ +{ + register atomic_uint_t _res; + __asm__ __volatile__("ldstub [%2], %0" : "=r"(_res), "+m"(*lock) : "r"(lock) : "memory"); + return (int) _res; +} +/* }}} */ + +static inline atomic_uint_t atomic_cmp_set(atomic_t *lock, atomic_uint_t old, atomic_uint_t set) /* {{{ */ +{ + return (atomic_cas_32(lock)==0); +} +/* }}} */ #else #error unsupported processor. please write a patch and send it to me Rationale: If I'm reading the original code correctly, there's no actual locking done but instead the code only tests whether it could acquire a lock. 'ldstub' works such that it returns the current value of the memory region specified and sets it to all '1' afterwards. Thus, if the return value is '-1' the lock was already set by another process whereas if it's '0' we acquired the lock. Well, at least in my certainly flawed logic ;) Since ldstub is atomic I didn't see a need to explicitly "lock;" the code. The patch should leave the 'cas' code intact when being compiled on v9 type SPARC systems. Tested (for successful compilation only!) on Debian (etch) using gcc 3.3.5. Thus I believe further testing is necessary to verify this is actually working. Well, please test and incorporate if you feel the code is doing what it's supposed to do. May I know as to why you need to compile with v8 ? compiling with v9 does not automatically make your application 64-bit . if that is the reason you want to choose -v8 in here. v8 sparc instruction is decade old - and is not being used in any hardware. so, i see no reason as to why we need to use / support this specific instruction set. Automatic comment from SVN on behalf of fat Revision: Log: - Fixed #53310 (sparc < v9 won't is not supported) we've decided sparc < v9 won't be supported. I've just updated the source code to warn specificaly about this. Of course you may ask: because I'm porting PHP to the ReadyNAS platform which happens to use a SPARC v8 compatible CPU and thus *needs* the v8 instruction set. Seeing that you've already made up your mind though, so I guess there's nothing more to add here. Makes me wonder why I can't get a response in > 24 hours as to my patch but you can't wait for me to answer for like 4 hours. you should be able to compile with a gcc version which provides the __sync_bool_compare_and_swap builtin function (>= 4.1). It's supported by FPM. If with this version of GCC FPM is not able to be compiled, there is a bug in FPM. We'll take care of it. It this a reasonable solution ? And you can still use FastCGI, btw. FPM is fairly new, and if new SAPIs have to support soon to be dead OSes, then we will cruelly need more developers to maintain everything :) As you may have read in my initial post, the compiler I (have to) use is gcc 3.3.5 which falls a bit short of 4.1 ;) Also, you may want to read the backend/port/tas/solaris_sparc.s file from the official PostgreSQL sources: ! "cas" only works on sparcv9 and sparcv8plus chips, and ! requies a compiler targeting these CPUs. It will fail ! on a compiler targeting sparcv8, and of course will not ! be understood by a sparcv8 CPU. gcc continues to use ! "ldstub" because it targets sparcv7. There they work around this by using a condition (for the SUN compiler) like this: #if defined(__sparcv9) || defined(__sparcv8plus) cas [%o0],%o2,%o1 #else ldstub [%o0],%o1 #endif and in their actual generic lock implementation (src/include/storage/s_lock.h) the code is this: #if defined(__sparc__) /* Sparc */ #define HAS_TEST_AND_SET typedef unsigned char slock_t; #define TAS(lock) tas(lock) static __inline__ int tas(volatile slock_t *lock) { register slock_t _res; /* * See comment in /pg/backend/port/tas/solaris_sparc.s for why this * uses "ldstub", and that file uses "cas". gcc currently generates * sparcv7-targeted binaries, so "cas" use isn't possible. */ __asm__ __volatile__( " ldstub [%2], %0 \n" : "=r"(_res), "+m"(*lock) : "r"(lock) : "memory"); return (int) _res; } #endif /* __sparc__ */ Now my general idea was that if there's a reason for PostgreSQL to keep that code around, there might be a reason for PHP to do so as well. Obviously I was wrong there. I also do not see the real advantage of 'cas' over 'ldstub' in the current scenario since both are atomic, both are supported (ldstub even on v7) and both do the job perfectly well. @pajoye@php.net Did it ever occur to you that I found this bug/problem because I *specifically wanted to use FPM* in the first place? Had I wanted to use FastCGI I'd have certainly done so. Seeing that there already was a solution for Sparc v9 I thought there might be interest in a solution that would allow PHP to run on older machines. Hardware that maybe you're laughing about. But hardware that's still in fairly wide use. And, come to think of it, hardware that may also be the only hardware people in poorer countries than the one you're obviously living in are able to get their hands on. So I first asked and then got my hands dirty and even provided a possible solution - and one that could be easily implemented, too. And what for? Only to get ignorance and witty remarks in return. Well, I almost forgot that the PHP project has such a bad reputation when it comes to bugs and patches. Thanks for reminding me why. Now you can safely go back to your ivory tower and think about supporting next decade's hardware only. For my part, I promise to keep any bugs/problems in PHP I may find in the future to myself and will do the same for any patches I may come up with. Btw: the boxes I'm talking about are running Linux (which you could have seen by looking at the "OS:" tag) and I really have no idea why you'd call that a "soon to be dead OS". If you have a problem understanding the difference between a CPU and an OS, may I ask what exactly makes you think you can give some valuable input here? As for the "cruelly needed developers" you mention: I don't see why you should need those as long as the community comes up with patches you could use. Ok, if you keep driving away people like this, I start to have an idea as to why ;) It was not badly meant, only trying to show you alternative. I can't know nor judge the reason why you need v8 support, but have been there many times in the past for my numerous projects. We have to make decisions about which platforms we can support, and also which we stop to support. There is nothing personal or aggressive in our replies, only trying to explain the status and the reasoning behind it. Sorry if you took it so badly, that's not the aim of our comments, or mines in particular. and I was wiling to write arch, not OS.... @stefan at whocares dot de Did you run your patch on a ReadyNAS box ? If you test it and tell us it works, there is not reason not to integrate it. As far as I know, it's not been tested but for compilation only. We don't want to leave someone behind, but as pierre told you there is priorities. We'll be glad if you help us. First of all: thanks for not taking my rant badly :) Of course I can run this code and, well "test" it. I would have been happier however if someone besides me had looked over the code and said "yes, that looks like it could work" ;) Right now it *is* running on two ReadyNAS (Sparc) boxes as well as on my SunFire 280R. It doesn't segfault which to me is a good sign and it's producing normale output from the small test scripts I have run. Haven't done extensive testing so far but will try running Wordpress and Drupal in the next couple of days. If there's any special test you'd like to see me run against the patched version of PHP, let me know. one simple test is to make php core the less as possible. You can create a file test.php wich does nothing but an "echo". Then you stress this page with FPM with ab (ab -c 100 -n 10000 While the test is running you check the status page and see how it's goin' on. it should be a good primary test. there is difference between these 2 instructions: ldstub -> operates on a 8 byte value casa -> operates on a 32-bit word now, if some one wanted to use these instructions to implement a atomic mutex lock, then one could argue that both instruction set are interchangeable. in this case, that is not the case. hence, i would argue that there is a valid case for using this specific 'compare and swap' instruction set. using 'ldstub instruction set' in this context is not what we want. few curl or http get requests cannot display the potential race conditions. not using 'atomic' operation will be the better approach for your scenario. Thank you for your input. Just so I understand better: You said "in this context is not what we want". Could you clarify that a bit? As far as I understand the code (and I don't claim to fully understand it) it just checks whether if a specific memory region contains a value of "0" and if so, it tries to set it to "1". At least I couldn't find any calls to the atomic "add" functions although they are provided for some architectures. Also you said: "not using 'atomic' operation will be the better approach for your scenario". Would you have an example / explanation on how to do that? I'd really be interested in that so I could eventually come up with a good and working solution. As per request here the results when running 'ab' against a patched version of PHP 5.3.3 running on the ReadyNAS. Environment: ============ Web Server: Nginx 0.8.53 PHP-FPM : Running with dynamic processes, 2 min, 2 minspare, 3 maxspare Please keep in mind that the CPU of the ReadyNAS is running at whooping 186 MHz, so the results obviously won't be lightning fast: Results: ======== desktop:~$ ab -c 100 -n 10000 This is ApacheBench, Version 2.3 <$Revision: 655654 $> Licensed to The Apache Software Foundation, Benchmarking develnas (be patient) Completed 1000 requests Completed 2000 requests Completed 3000 requests Completed 4000 requests Completed 5000 requests Completed 6000 requests Completed 7000 requests Completed 8000 requests Completed 9000 requests Completed 10000 requests Finished 10000 requests Server Software: nginx/0.8.53 Server Hostname: develnas Server Port: 8880 Document Path: /test.php Document Length: 16 bytes Concurrency Level: 100 Time taken for tests: 110.629 seconds Complete requests: 10000 Failed requests: 0 Write errors: 0 Total transferred: 1700000 bytes HTML transferred: 160000 bytes Requests per second: 90.39 [#/sec] (mean) Time per request: 1106.289 [ms] (mean) Time per request: 11.063 [ms] (mean, across all concurrent requests) Transfer rate: 15.01 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.6 0 10 Processing: 105 1101 212.8 1122 2348 Waiting: 105 1100 212.8 1121 2348 Total: 107 1101 212.7 1122 2349 Percentage of the requests served within a certain time (ms) 50% 1122 66% 1129 75% 1139 80% 1145 90% 1547 95% 1552 98% 1564 99% 1571 100% 2349 (longest request) desktop:~$ well, what i meant by 'in this context' is -> the compare and set is a general purpose function within fpm and is not intended to simply test&swap a single byte . hence, it won't be appropriate to replace cas with ldstub instruction. also, what i meant by not using the atomic option is - fpm currently implements varieties of common api's by using assembly instructions. It is possible to do the same by using mutex lock and regular c code. this alternate way allows some one to run in varieties of architecture. though, this might run slightly slower. doing this way would be a better option for your case. Thanks for your input, greatly appreciated. It'd be nice if you could help me out a bit more. I grepped through the whole source and the only use of 'atomic_cmp_set' I could find was within fpm_atomic.h itself: (333)sparky:~/devel/build/php5-5.3.3# grep -R 'atomic_cmp: return atomic_cmp_set(lock, 0, 1) ? 0 : -1; sapi/fpm/fpm/fpm_atomic.h: if (atomic_cmp_set(lock, 0, 1)) { (333)sparky:~/devel/build/php5-5.3.3# Since you're saying it's a general purpose function I'm obviously missing something here and because I'm an enquiring mind I'd like to know what it is I'm missing. I agree that using C code would improve portability. But since the machine I'm building for is slow enough already, I'd prefer to stick with assembler if possible, stefan, wasn't sure if you're still subscribed to this, but I'd like to know if you found a workaround/patch/etc.? ALL of our servers are run on Sparcv8 / Solaris 11, so this issues is very important to me.
https://bugs.php.net/bug.php?id=53310&edit=1
CC-MAIN-2020-05
refinedweb
2,567
72.66
The PianoManager class. More... #include <pianomanager.h> The PianoManager class. This class holds the instance of the Piano and manages the recording process. Definition at line 39 of file pianomanager.h. Constructor, resets member variables. Definition at line 47 of file pianomanager.cpp. Definition at line 43 of file pianomanager.h. Find the next key to be recorded. Once a key has been recorded successfully, this function determines who ist next. Definition at line 225 of file pianomanager.cpp. Definition at line 45 of file pianomanager.h. Definition at line 46 of file pianomanager.h. Message listener and dispatcher. Implements MessageListener. Definition at line 101 of file pianomanager.cpp. Handle the event that a key has been successfully indentified. This function decides whether to accept or reject a keystroke identified by the FFTAnalyzer and then sets the key in the mPiano. Definition at line 177 of file pianomanager.cpp. Reset all recorded keys and send a message to redraw all elements. This function is called by selecting the menu entry "Reset recording". Its action depends on the operation mode: In the idle and recording mode all key-related data is cancelled. In the calculation the tuning curve is set to zero (ET). In the tuning mode the measured tuning levels are cancelled. Definition at line 69 of file pianomanager.cpp. Flag for forced recording. Definition at line 59 of file pianomanager.h. Local copy of the operation mode. Definition at line 60 of file pianomanager.h. Instance of the piano. Definition at line 57 of file pianomanager.h. Local copy of the selected key. Definition at line 58 of file pianomanager.h.
http://doxygen.piano-tuner.org/class_piano_manager.html
CC-MAIN-2022-05
refinedweb
272
54.59
. Issue Links - is related to HADOOP-5158 Port HDFS space quotas to 0.18 - Resolved - relates to HADOOP-3187 Quotas for name space management - Closed Activity - All - Work Log - History - Activity - Transitions Patch for diskspace quotas is attached. It works very similar to name space quotas implemented in HADOOP-3187 and design document attached applies to this jira as well. Description of "Space quotas" in the admin guide attached pretty much serves as the spec. DFSClient is modified so that it throws the actual exception (including QuotaExceededException) when these exception occurs in other threads (most of the time). TestQuota.java tests space quotas as well. Currently there are differences in dfsadmin command names. will fix them. User guide says : "A quota of zero forces the directory tree to remain empty of files." A directory with a space quota of '0' bytes can have zero length files (though setting the quota to 0 is not actually allowed).. Actually creating a file does not require block allocations. So space quota will be not be checked. It is possible to do dfs.create(); dfs.close(), even in a directory that reached its space quota. Is that what we want? > Also, did you want to include the updated documentation in this patch? sure, but not required in this jira. Irrespective of whether it is possible or not, I think we need clarify/decide the policy : Should creating an empty file take up any space quota? My vote is that creating a empty file does not take any disk-quota. (However, it does take up a namespace quota). Sorry, I confused the issue. Create should not require any space quota. The quota should be checked only when a new block is requested. I'll attach a new version of the guide with the clarification! Corrects a grammar mistake and clarifies that file creation does not require space quota. Updated patch resolves a conflict with a recent commit. Patch updated for trunk. - It is better to implement public ContentSummary(long length, long fileCount, long directoryCount) { this(length, fileCount, directoryCount, length, -1) } - DFSClient in locateFollowingBlock() you do not need to throw unwrapped exception in order to check whether it is a RemoteException. And also you do not throw if the remote exception is not of any of the 4 types considered. try { return namenode.addBlock(src, clientName); } catch (RemoteException re) { IOException ue = re.unwrapRemoteException(FileNotFoundException.class, AccessControlException.class, QuotaExceededException.class); if(re != ue) throw ue; ue = re.unwrapRemoteException(NotReplicatedYetException.class); if(--retries == 0 && re == ue) // not a NotReplicatedYetException throw re; LOG.warn("NotReplicatedYetException sleeping " + src + " retries left " + retries); try { Thread.sleep(sleeptime); sleeptime *= 2; } catch (InterruptedException ie) {} } - JavaDoc for QuotaExceededException should reflect new space quota related semantics. - In QuotaExceededException.getMessage() " file count=" instead of " namespace count=" may sound better. - FSDirectory does not need to import StringUtils. - FSDirectory.unprotectedAddFile() should probably not add blocks first and then remove them if the space quota is violated. The blocks can be added once the node is successfully created, you may need to pass the size of the file to addNode(). - numItemsInTree() followed by diskspaceInTree() is called on several occasions: INodeDirectoryWithQuota(), addChild(), removeChild(). This is very inefficient, tree traversal should be be done only once. You can use something like the TwoCounters class but with a more meaningful name, say DirectoryQuota. I think numItemsInTree() and diskspaceInTree() should be merged in one method preferably non-recursive. - unprotectedSetQuota() should take 2 longs rather than a long and a boolean private void unprotectedSetQuota(String src, long nsQuota, long dsQuota) as in other places, e.g. addToParent(). - I am not sure we need to add an extra pair of set/clear-DiskspaceQuota(), may be we just need an extra parameter in the old setQuota(src, nsQuota, dsQuota) - Should we check space quota when we start an append? - NameNode redundantly imports BlockCommand (not introduced by this patch). Thanks for the review Konstantin. Regd (8), (9) etc : Could you suggest a value for quota that implies 'do not modify quota'.. > 8 , 9 : We use Long.MIN_VALUE to indicate "don't modify". This reduces quite a bit of similar looking code. You could use the wrapper class Long and use null for "don't modify". i.e. private void unprotectedSetQuota(String src, Long nsQuota, Long dsQuota) - In FSDirectory.replaceNode() you calculate diskspaceConsumed() even if you do not need to updateDiskspace. +1 the rest looks good to me. -1 overall. Here are the results of testing the latest attachment against trunk revision 694562. passed core unit tests. +1 contrib tests. The patch passed contrib unit tests. Test results: Findbugs warnings: Checkstyle results: Console output: This message is automatically generated. Attached patch does the following : - includes updated hdfs_quota_admin_guide.xml from Rob - Konstantin's review : invoke diskspaceConsumed() only when required (it is not required only in some error cases). - fix findbugs warning. ant test-patch is also run. Regd Nicholas' comment : Using Long object also works. Not sure if there is any real difference. From the user spec: ? Are there administration commands that are going to work directly on the fsimage without a namenode? This seems like a very poor requirement. -1 overall. Here are the results of testing the latest attachment against trunk revision 695690. ? my impression as well. I am not very sure why that was a requirement. Imo, you should be able to start name-node with quotas turned off (in config) and then be able to correct quotas for the faulty directory. Does the patch allow that? We should also check namespace quotas for the same problem. That's weird to set quotas with the configuration turned off? I hope this is implemented as Konstantin said, but some unit tests for this use case would probably help future implementors I'm going to jump on the pile and ask that a test plan be included for this feature. I don't see any global conf to disable quota restrictions. This is the case before and after this patch. If the image is wrong for some reason, then it won't start.. it looks like. > I'm going to jump on the pile and ask that a test plan be included for this feature. It is the same as in HADOOP-3187. The unit test covers pretty much all of them. Does it sound good enough? Only the scale test is not done. On second thought my proposal is not good since it is exactly the way to produce such incorrect state. Instead, we should just remove the restriction and let the server start with a warning. A unit test would be hard to write for the case since there are no valid ways to reproduce the condition. I'm guilty of having caused the confusion. In any case, the consensus seems to be for policy to be the same for both space and name quotas, and that the proper policy is to log any violations that are observed at start up, but to resume normal operation. I reviewed the patch, and the offending words about not starting are not in the new documentation. The new documentation as written only requires that the quota violation be logged. Konstantin said > A unit test would be hard to write for the case since there are no valid ways to reproduce the condition. you could a functional test with a vmware/xen image, though it would take a lot of work. The alternate tactic is to have a mock implementation of the code to determine disk space use, and simulate failures when a node comes up. We do have a test that uses a fixed NameNode image (used for testing upgrade from previous versions). It takes work to maintain as well. The quota violation can happen only with software bug and it is not fatal, I don't think it is a must to have a unit test for it in this jira. I will manually test of course. Steve, what I meant is that you cannot (naturally, using hdfs methods) create an image which violates a quota. You can obviously write an arbitrary number instead of the existing quota value directly in the fsimage file if you know where, but this is not a "valid" way. BTW, this issue is about hdfs (distributed) space quotas, not sure that determining "disk space use" helps a lot. Updated patch has following changes over the previous patch : - Quota violations are tolerated while loading filesystem during start up. - updateCountForINodeWithQuota() called during initialization is rewritten. - updateCountForINodeWithQuota() is now called after loading edits, rather than right after loading fsimage. - Added one more test case to handle the case when quotas specified are too large. - user_guide is slightly updated. The handling of quota violations are tested by running a modified NameNode that does not generate a QuotaExceededException. will have another comment on this. Konstantin, could you take another look at the patch? thanks. tes-patch output from my machine : [exec] +1 overall. [exec] +1 @author. The patch does not contain any @author tags. [exec] +1 tests included. The patch appears to include 22. Patch updated : minor change for INodeDirectoryWithQuota.setQuota(). It verifies only if the new quota is more restrictive. Thanks Konstantin. Updated patch modifies setQuota() as Konstantin suggested. It looks better now. setQuota() does verifies only the the quota that is modified. So if space quota is not modified then it will not be checked. This is essential to deal with problems in quota management (previous run of HDFS). +1 this looks good now. How to test with quota violations in fsimage : =================================== - Comment out two places where QuotaExceededException is thrown in INodeDirectoryWithQuota - Run a fresh HDFS and create a few files and directories such that it exceeds quotas for a few directories. For e.g. : bin/hadoop fs -mkdir quota3-3k bin/hadoop dfsadmin -setQuota 3 quota3-3k bin/hadoop fs -mkdir quota3-3k/emptyDir bin/hadoop fs -put /dev/null quota3-3k/emptyFile bin/hadoop dfsadmin -setSpaceQuota 3072 quota3-3k bin/hadoop fs -put ~/cws/tmp/5Mb quota3-3k/ bin/hadoop fs -mkdir quota3-3k/quota2 bin/hadoop dfsadmin -setQuota 2 quota3-3k/quota2 bin/hadoop fs -mkdir quota3-3k/quota2/emptyDir bin/hadoop fs -put /dev/null quota3-3k/quota2/emptyFile bin/hadoop fs -mkdir quota3-3k/quota-5k bin/hadoop dfsadmin -setSpaceQuota 5120 quota3-3k/quota-5k bin/hadoop fs -put ~/cws/tmp/5Mb quota3-3k/quota-5k bin/hadoop fs -mkdir quota3-3k/quota-5k/emptyDir - Stop the cluster and start it again. - The cluster should restart fine. You should see some warnings for quota3-3k etc in NameNode log. - Adding any more files or data to such directories should fail. - You should be able to either increase the quotas or delete some files to satisfy the requirements. - Once these are fixed, there should not be any more warnings when NameNode restarts. I just committed this. Integrated in Hadoop-trunk #611 (See) Attaching TestPlan for Space Quota feature. Draft user guide.
https://issues.apache.org/jira/browse/HADOOP-3938?focusedCommentId=12631491&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-40
refinedweb
1,819
58.58
#include <SPI.h>const int dataReadyPin = 9;void setup() { Serial.begin(9600); SPI.begin(); SPI.setDataMode(SPI_MODE0); pinMode(dataReadyPin, INPUT);}void loop() { if (digitalRead(dataReadyPin) == LOW) { unsigned int result1 = 0; byte inByte = 0; for (int c = 0; c <= 3; c++) { result = result << 8; inByte = SPI.transfer(0x00); Serial.print(inByte); Serial.print("<<"); result = result | inByte; } Serial.print("="); Serial.println(result); delay(1000); }} 1+139+170+255+=437751+200+219+127+=561912+156+31+255+=81913+59+255+255+=655353+225+95+255+=245750+175+159+127+=40831 <== Problem !4+7+15+255+=4095 I don't think that is a SPI mode 0 device. It appears to be a mode 1 device. It has a clock that is LOW with HIGH pulses (CPOL = 0) and propagates on the rising edge (CPHA = 1). for (int c = 0; c <= 3; c++) Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=131086.msg986081
CC-MAIN-2016-07
refinedweb
174
58.79
This guide shows how to enable Cloud Run on existing GKE clusters. Note that enabling Cloud Run for Anthos on Google Cloud installs Knative Serving into the cluster to manage your stateless workloads. For more information, see Architectural overview of Cloud Run for Anthos on Google Cloud. Prerequisites This page assumes that you have already set up your environment and have a cluster with the following minimum configuration: - Nodes with 2 vCPU - Scopes:, Enabling an existing cluster for Cloud Run You can use either the gcloud command line or the console to enable Cloud Run for a cluster: Console To enable an existing cluster for Cloud Run: Go to the Google Kubernetes Engine page in the Cloud Console: Go to Google Kubernetes Engine Click on the cluster you want to enable for Cloud Run. Click Edit Select Enable Cloud Run for Anthos on Google Cloud. Click Save. After the update completes, the cluster will support Cloud Run. Command line To enable an existing cluster for Cloud Run: Enable the cluster using the command: gcloud container clusters update \ CLUSTER_NAME \ --update-addons=CloudRun=ENABLED,HttpLoadBalancing=ENABLED \ --zone=ZONE Replace - CLUSTER_NAME with the name you want for your cluster. - ZONE with the zone you are using for your cluster, for example, us-central1-a. Wait for the enabling to complete: upon success, you will see a message similar to Updating your-cluster-name...done.. Enabling deployments on a private cluster You can skip the following instructions, if you're using Cloud Run for Anthos on a GKE cluster with the following versions: - 1.16.8-gke.7+ - 1.15.11-gke.9+ To deploy a service to Cloud Run for Anthos on a private GKE cluster, you must allow TCP connections from master servers to nodes on port 8443 and manually specify port 8443 in your list of allowed TCP connections by editing the firewall rules in your project: View the cluster master's CIDR block. Enabling deployments. You can deploy your Cloud Run for Anthos on Google Cloud services on an internal IP address in your VPC network by changing Istio's Ingress Gateway to use Internal TCP/UDP Load Balancing instead of Network Load Balancing. You must be an admin on your cluster to do this. To configure the Ingress Gateway: Update the Istio Ingress Gateway to use Internal TCP/UDP Load Balancing: kubectl -n gke-system patch svc istio-ingress -p \ '{"metadata":{"annotations":{"cloud.google.com/load-balancer-type":"Internal"}}}' It might take a few minutes for the change to take effect. Run the following command to poll your GKE cluster for change: kubectl -n gke-system get svc istio-ingress --watch - Look for the value of EXTERNAL-IPto change to a private IP address. Ctrl+Cto stop the polling when you see a private IP address in the EXTERNAL-IPfield. To verify internal connectivity after your changes: Deploy a service called sampleto Cloud Run for Anthos on Google Cloud Enabling metrics on a cluster with Workload Identity When enabling Workload Identity, Cloud Run for Anthos doesn't report certain metrics to Google Cloud's operations suite. To enable. Enabling automatic Istio sidecar injection To enable automatic Istio sidecar injection on your deployed service's namespace, you must use a separate Istio installation. Disabling Cloud Run for a cluster You can disable Cloud Run for a cluster at any time, using the console or the command line. Console To disable Cloud Run on a cluster: Go to the Google Kubernetes Engine page in the Cloud Console: Go to Google Kubernetes Engine Click the cluster where you want to disable Cloud Run. Select Disable Cloud Run for Anthos on Google Cloud. Optionally disable any addons you will not use in your cluster without Cloud Run. This may include Istio. Click Save. Command line To delete a cluster: Invoke the following command: gcloud container clusters update \ CLUSTER_NAME \ --update-addons=CloudRun=DISABLED \ --zone=ZONE Replace - CLUSTER_NAME with the name you want for your cluster. - ZONE with the zone you are using for your cluster, for example, us-central1-a. Wait for the enabling to complete: upon success, you will see a message similar to Updating your-cluster-name...done..
https://cloud.google.com/run/docs/gke/enabling-on-existing-clusters?hl=da
CC-MAIN-2020-34
refinedweb
696
55.68
Jonathan A. Rees, 22 Aug 2011 (revised 29 Aug 2011 and 15 Feb 2012) This note is about the continuing lack of consensus over the referential use of 'hashless' URIs (i.e. without #) for which retrieval behavior is defined. Two conventions for using such URIs referentially are being put forward, each as the preferred way to meet a notational need. The two conventions are incompatible, creating an interoperability risk. Here are some hashless URIs for which retrieval is defined: urn:ietf:rfc:2648 data:,Moby%20Dick (The documentation for the data: scheme is not explicit about retrieval, but based on what RFC 3986 says about retrieval, combined with what Web browsers actually do with data: URIs, it seems reasonable to say that obtaining the data from a data: URI constitutes retrieval.) "Referential use" is where you use a URI in something resembling a sentence, such that it seems to refer to something, similarly to how the string (word?) "Paris" often refers to the capital of France in English sentences. For example (the notation used here is Turtle): <urn:ietf:rfc:2648> dc:creator "R. Moats". Here the URI "urn:ietf:rfc:2648" is used referentially. It refers to RFC 2648, in a sentence that says that someone named "R. Moats" is a "creator" of the RFC (the precise sense of "creator" being given by the Dublin Core vocabulary). In principle one could use a URI referentially in any language or notation, but for the purposes of this discussion, the only languages that currently matter in practice are RDF and its derivatives. There is a natural inclination to align "identification" in the sense used in RFC 3986 and so on with "reference" in the sense used above. It is not clear that this idea commands consensus, or is forced by recognized specifications. Because the nature of "identification" in the RFCs is unclear I'll stay away from it. There is a document on the web, and we want to refer to it (maybe in an RDF statement). E.g. we want to know what to write for ___ in ___ dc:title "HTML 4.01 Specification". when we want ___ to refer to the document that's retrieved using the URI "". Applications: provenance, metadata, FOAF, annotation, content ratings (e.g. POWDER), etc. - any time you want to say something about a document. In general, for any hashless URI permitting retrieval, we'd like a way to refer to the document "at" that URI. Ideally there is a deterministic procedure that goes from such a URI to the way-of-referring. This is not a precise problem statement since "the document that's retrieved using" is vague. But that is something a concrete proposal would tighten up. There is something we want to refer to, but we need to refer to it somehow; that is, we need to decide what to call it. At the same time we need to put an explanation that we're using this manner of referring (i.e. what we called it) somewhere, so that others will know what we're referring to when they see the reference. That's pretty obtuse, but the idea is simple. Here's an example. We want to know what to put for ___ in ___ eq:magnitude 6.9 . when we want some ___ to refer to the Loma Prieta earthquake; and we need to know where to put the explanation that ___ is meant to so refer, so that others can find it. Applications: linked data / semantic web / RDF generally. Now each of these needs can be met in various ways, and when methods are chosen that don't conflict, there is no issue. Following are the particular methods that, considered together, create the difficulty. For any hashless URI permitting retrieval, use that URI to refer to the document found there. In the example, we'd say <> dc:title "HTML 4.01 Specification". That is, we transform a URI into the way of referring to its document by putting pointy brackets around it (in Turtle; or the corresponding notation in other notations). The document it refers to is the one for which retrieved representations are specific versions (instances, specializations). Tim Berners-Lee has described the D2 approach here (2002 email), here (2004 email), [+8/28] here (2007 email), here (design note), and in several other places. My memo Information resources and Web metadata gives a rigorous treatment of "the document found there" based on what I think Tim must be trying to say. Choose any hashless URI, say "", arrange for retrievals using that URI to yield an explanation of what that URI is supposed to refer to, and then use the resulting URI to refer to it. For example, one would arrange for retrievals using "" to yield a description similar to The URI "" refers to the earthquake of 17 October 1989 with epicenter near Loma Prieta, California. or, expressed in RDF, <> eq:epicenter <geo:37.040,-121.877> . <> eq:date "1989-10-17" . either of which would suffice. Then to talk about the Loma Prieta earthquake, write <> eq:magnitude 6.9 . For one formulation and defense of this idea see Ian Davis, Is 303 Really Necessary? There are numerous details to be filled in here: are there any non-explanation retrievals; if so how are they distinguished from explanations; what languages are permitted; and so on. It is possible to assume notation S2 and then employ notation D2 as an opt-in, by providing an explanation that says (or implies) that the URI refers to the document found at the URI. But this is not adequate to satisfy need D1, which requires a way to refer, given an arbitrary hashless URI, to the document found at that URI. It should be clear that these answers are mutually exclusive. If for some URI you think, based on D2, that its referent has certain properties, then you will be confused or make mistakes when you talk to someone who, based on S2, thinks its referent (something different) has different properties. What would an actual skirmish look like? To construct a scenario in which the result is not just confusion (a type error) but an incorrect answer, we need a URI that is interpretable according to both D2 and S2, and a statement expressed using the URI that has consequentially different meanings depending on whether D2 or S2 is assumed. The setup is as follows: A document, call it X, is found at "". X is a description of a different document, Y. Suppose there is RDF in X that uses the URI "" to refer to document Y. (This is a very frequent occurrence, for example for journals, digital repositories, media sites such as Flickr, catalogs such as Amazon, and so on; the description page is usually called a "landing page" and it normally gives metadata and perhaps an offer to sell a document, and a link to a PDF or some other way to obtain the intended document.) Now consider the statement <> xhv:license <>. According to D2, this says that document X is licensed. According to S2, this says that document Y is licensed. Which of these is the case matters a lot, since if you get it wrong you could be misled into making an unlicensed use of either X or Y. It doesn't matter where the statement is placed; it could be in X (perhaps placed there by an D2-assuming tool unaware that X's author assumed S2), in Y, or in some other document (such as a manifest). There are many examples of this particular conflict in the wild, e.g. see any Flickr photo page or any music page at Jamendo. Retrievals using one of these URIs contain RDF that uses the URI to refer to something other than the document found at the URI. A D2 client such as Tabulator will infer something other than what the author of the page meant. [+8/28] There is some evidence that S2, rather than D2, is meant to apply in the case of some resolvable URNs as well. For example when "urn:nbn:de:0002-938" is resolved using a resolving service, the result is a landing page, not the named document. It is not completely clear that what the "resolution" service does constitutes a retrieval in the sense of RFC 3986, but the specification governing the NBN URN namespace is clear that a description (landing page) maybe substituted for content. [+8/28] In the case of the URI "data:,Moby%20Dick", we would have a reference to something having two words according to D2, or a reference to something having over a million words according to S2. If the conflict is resolved in favor of D2, need S1 can be met by some other method, such as fragment identifiers, a new "thing explained by" URI scheme, blank node notation, etc. (see the ISSUE-57 memo). If resolved in favor of S2, need D1 can be met using URNs, DOIs, the handle system, a new URI scheme, blank node notation, etc. But the conflict persists without resolution because the same notation is the strongly preferred answer to both needs. Many arguments for S2 over D2 have the form of criticism of D1 or D2. [+8/28] The legitimacy of need D1 has been questioned; it is sometimes seen as marginal compared to what "ordinary" linked data practice needs, and therefore not deserving of such valuable syntactic space. Furthermore D2 is considered to be either confusing, or useless, or wrong in detail. D2 is also seen as an uphill battle. It is very easy to disregard (as evidenced by the Flickr case ), is not the outcome of a formal consensus process, and has weak support, if any, in applicable specifications. In addition it currently has no enforcement points, so its continued use has to be maintained by social, not technical, pressure. [+8/28] S2 is often defended by citing the lack (in the applicable RFCs) of any restriction on what a URI can "identify," by pointing to the sovereignty of the "URI owner" according to AWWW, and by noting the very loose interpretation of "representation" implied by Roy Fielding's REST writings. The above summary is of course just a tiny and shallow sampling of what has been expounded on the subject over the years. D2 has widespread uptake for two reasons. First, it is entirely natural in some situations, such as the HTML4 example above and for POWDER. Second, it was promoted indirectly by the TAG's httpRange-14 resolution. (D2 and clause (a) of the httpRange-14 resolution are closely related, but not equivalent. D1/D2 as formulated here are my own belief about what the httpRange-14 resolution was intended to accomplish, and how it has been interpreted it in practice; but it does not actually accomplish what I think it was meant to.) D2 was promoted in turn by those who were persuaded by it (e.g. Cool URIs for the Semantic Web, the pedantic-web group, Creative Commons). D2 uptake takes the form not only of use of hashless URIs to refer to documents, but also the avoidance of hashless URIs when the implication that the referent is the document implied by D2 is to be avoided. For example, Crossref uses 303 redirects to avoid the implication that its URIs refer to what's retrieved: When there is a landing page, the URI needs to refer to the document linked or described from the landing page, not the landing page itself. S2 likely had uptake prior to the httpRange-14 debate because it too is entirely natural. It is often assumed to be the way things should work (in RDF) by people who have never heard of the httpRange-14 idea. main purpose of my recent ISSUE-57 report was to start working toward sweetening answer D2 for S2 advocates, so that they might be more willing to accept D2. A gap in my personal understanding of S2 is why the widely used method of fragment identifiers is rejected, but I am assured that there are important situations it is unacceptable. Note: S1 and S2 are not mutually exclusive - in the special case of documents that contain their own metadata (and can be determined to do so), they can be realized at the same time. Harry Halpin (email), Manu Sporny (email), Ian Davis (blog post), and others point the finger at the httpRange-14 resolution as a major impediment to linked data uptake - perhaps so much so that without official sanction of S2, RDF-based linked data may lose out to some other emerging generic data notation. D2, being in some sense the dominant position, has had few active defenders other than TimBL, although my personal guess is that defenders would materialize should a move be made to amend it. What would be lost without it: an easy and natural way to refer to Web documents. Either Web architecture would require an overhaul, or reference in RDF would have to be divorced from webarch "identification". [+8/28] A compromise approach would consist of a way to recognize D2 URIs, a way to recognize S2 URIs, and a method to construct a reference to the document at any retrieval enabled hashless URI (including those not admitting D2). Some compromises have been put forth, but further work needs to be done before any is ready for advancement through anything like a consensus process. It has also been suggested that neither D2 nor S2 is a good solution to the problem it is intended to address, and that a new architecture for reference is needed in both cases. If this were agreed, a revolution would be required for RDF content, which at this point would be costly and probably impractical. The issue remains mainly academic, since for the most part the two worlds do not intersect. We don't currently refer to landing pages very much, and most documents don't look like explanations of what the URI where it's found refers to. It is possible that D2 and S2 can be used side by side by different communities for quite a while before a collision of the sort described above becomes a serious interoperability problem. On the other hand, when the conflict does happen, it will be very painful. I feel that in spite of the enormous volume of words spilled over this, communication between the "factions" has been poor and there has been little progress in developing mutual sympathy and understanding. More writing probably won't help, since nearly every contribution so far has focused on defending and/or attacking particular points of view. A teleconference or in-person meeting probably will be required if this thing is going to budge, because it's so difficult to develop joint solutions to complex problems in email. This is just my opinion. [+9/3] (Since writing that I've thought of one thing that might be done, and that's to articulate requirements so that proposals can be compared. Will discuss at F2F.) TAG members please review: Thanks once again to Alan Ruttenberg for helpful comments on a draft, and to Martin Dürst for correcting my terminology.
http://www.w3.org/2001/tag/2011/09/referential-use.html
CC-MAIN-2016-44
refinedweb
2,542
58.32
Creating your first web service is incredibly easy. In fact, by using the wizards in Visual Studio. NET you can have your first service up and running in minutes with no coding. For this example I have created a service called MyService in the /WebServices directory on my local machine. The files will be created in the /WebServices/MyService directory. MyService A new namespace will be defined called MyService, and within this namespace will be a set of classes that define your Web Service. By default the following classes will be created: System.Web.Services.WebService There are also a number of files created: The class for your service that is created by default is called (in this case) WebService1, and is within the MyService namespace. The code is partially shown below. WebService1 namespace MyService { ... /// <summary> /// Summary description for WebService1. /// </summary> [WebService(Namespace="", Description="This is a demonstration WebService.")] public class WebService1 : System.Web.Services.WebService { public WebService1() { //CODEGEN: This call is required by the ASP+ Web Services Designer InitializeComponent(); } ... [WebMethod] public string HelloWorld() { return "Hello World"; } } } A default method HelloWorld is generated and commented out. Simply uncomment and build the project. Hey Presto, you have a walking talking WebService. HelloWorld A WebService should be associated with a namespace. Your Wizard-generated service will have the name space. If you compile and run the service as-is you'll get a long involved message indicating you should choose a new namespace, so we add the namespace, and the WebService description as follows: [WebService(Namespace="", Description="This is a demonstration WebService.")] public class WebService1 : System.Web.Services.WebService { ... To test the service you can right click on WebService1.asmx in the Solution Explorer in Visual Studio and choose "View in Browser". The test page is shown below, When invoked this returns the following: If you downloaded the source code with this article then you will need to create a directory 'WebServices' in your web site's root directory and extract the downloaded zip into there. You should then have: \WebServices \WebServices\bin \WebServices\WebService1.asmx ... Navigating to won't show you the WebService because you need to ensure that the webservice's assembly is in the application's /bin directory. You will also find that you can't load up the solution file MyService.sln. To kill two birds with one stone you will need to fire up the IIS management console, open your website's entry, right click on the WebServices folder and click Properties. Click the 'Create' button to create a new application the press OK. The /WebServices directory is now an application and so the .NET framework will load the WebService assembly from the /WebServices/bin directory, and you will be able to load and build the MyService.sln solution. So we have a WebService. Not particularly exciting, but then again we haven't exactly taxed ourselves getting here. To make things slightly more interesting we'll define a method that returns an array of custom structures. Within the MyService namespace we'll define a structure called ClientData: ClientData public struct ClientData { public String Name; public int ID; } and then define a new method GetClientData. Note the use of the WebMethod attribute in front of the method. This specifies that the method is accessible as a WebService method. GetClientData WebMethod [WebMethod] public ClientData[] GetClientData(int Number) { ClientData [] Clients = null; if (Number > 0 && Number <= 10) { Clients = new ClientData[Number]; for (int i = 0; i < Number; i++) { Clients[i].Name = "Client " + i.ToString(); Clients[i].ID = i; } } return Clients; } If we compile, then navigate to the the .asmx page then we are presented with a form that allows us to enter a value for the parameter. Entering a non-integer value will cause a type-error, and entering a value not in the range 1-10 will return a null array. If, however, we manage to get the input parameter correct, we'll be presented with the following XML file: It's that easy. Often a WebService will return the same results over multiple calls, so it makes sense to cache the information to speed things up a little. Doing so in ASP.NET is as simple as adding a CacheDuration attribute to your WebMethod: CacheDuration [WebMethod(CacheDuration = 30)] public ClientData[] GetClientData(int Number) { The CacheDuration attribute specifies the length of time in seconds that the method should cache the results. Within that time all responses from the WebMethod will be the same. You can also specify the CacheDuration using a constant member variable in your class: private const int CacheTime = 30; // seconds [WebMethod(CacheDuration = CacheTime)] public ClientData[] GetClientData(int Number) { In the default list of WebMethods created when you browse to the .asmx file it's nice to have a description of each method posted. The Description attribute accomplishes this. Description [WebMethod(CacheDuration = 30, Description="Returns an array of Clients.")] public ClientData[] GetClientData(int Number) { Your default .asmx page will then look like the following: There are other WebMethod attributes to control buffering, session state and transaction support. Now that we have a WebService it would be kind of nice to allow others to use it (call me crazy, but...). Publishing your WebService on your server requires that your solution be deployed correctly. On the Build menu of Visual Studio is a "Deploy" option that, when first selected, starts a Wizard that allows you to add a Deployment project to your solution. This creates an installation package that you can run on your server which will create the necessary directories, set the correct parameters and copy over the necessary files. This doesn't really give you an idea of what, exactly, is happening, so we'll deploy our MyService manually. Deploying the application is done using the steps in Getting the demo application to run. We need to create a directory for our service (or use an existing directory) for our .asmx file, and we need to have the service's assembly in the application's bin/ directory. Either place the .asmx file in a subdirectory on your website and place the assembly in the /bin folder in your website's root, or place the /bin in the subdirectory containing the .asmx file and mark that directory as an application (see above). If you choose to create a separate directory and mark it as an application then Within this directory you need to add the following files and directories: Writing WebServices is extremely easy. Using the Visual Studio. NET wizards makes writing and deploying these services a point and click affair, but even if you wish to do it by hand then the steps involved are extremely.
http://www.codeproject.com/Articles/863/Your-first-C-Web-Service?msg=3401929
CC-MAIN-2015-06
refinedweb
1,108
55.54
In this problem, Bessie and Elsie each have $N$ unique integers ranging from 1 to $2N$. Over $N$ rounds, Bessie and Elsie will each select a different integer and the cow who selected the larger integer wins a point. Bessie knows what integers Elsie will select and wants to maximize her (Bessie's) score. Because Bessie knows the exact order in which Elsie will select her integers, Bessie can determine her exact strategy beforehand, choosing to win points on certain rounds and not win points on other rounds. Assume without loss of generality that Bessie is able to earn $K$ points using some strategy. We claim that there exists a strategy where Bessie wins points exactly when Elsie picks her $K$ smallest integers. The intuition for this is as follows - if there are two integers $x$ and $y$ where $x<y$, Elsie picks $x$ and Bessie loses, and Elsie picks $y$ and Bessie wins, then Bessie can swap the two moves - Bessie will win when Elsie picks $x$ and lose when she picks $y$. Therefore, it remains to see how many of Elsie's smallest integers Bessie can beat. Bessie can start by trying to beat Elsie's smallest integer. If none of Bessie's integers are larger than that one, Bessie can't win any points. Otherwise, Bessie needs to pick an integer to beat Elsie's smallest integer. Intuitively, the best choice is to pick the smallest integer that can beat it - the reason for this is that we want to save bigger integers for later on. After beating Elsie's smallest integer, Bessie can then try to beat her second smallest one, and continue beating Elsie's integers in order until she can no longer beat one. To efficiently find the smallest such integer that can beat a given one from Elsie, we can consider Bessie's integers in order. If one of her integers can't beat Elsie's smallest unbeaten integer, it will never be usable and we can ignore it. Otherwise, we use that integer to beat Elsie's integer. Here is my code illustrating this: import java.io.*; import java.util.*; public class highcard { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("highcard.in")); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("highcard.out"))); int n = Integer.parseInt(br.readLine()); boolean[] elsieOwns = new boolean[2*n+1]; for(int i = 0; i < n; i++) { elsieOwns[Integer.parseInt(br.readLine())] = true; } ArrayList<Integer> bessie = new ArrayList<Integer>(); ArrayList<Integer> elsie = new ArrayList<Integer>(); int points = 0; // because we loop over the values in increasing order, the two lists will be in sorted order for(int i = 1; i <= 2*n; i++) { if(elsieOwns[i]) { elsie.add(i); } else { bessie.add(i); } } int bessieIndex = 0; int elsieIndex = 0; while(bessieIndex < n && elsieIndex < n) { if(bessie.get(bessieIndex) > elsie.get(elsieIndex)) { points++; bessieIndex++; elsieIndex++; } else { bessieIndex++; } } pw.println(points); pw.close(); } }
http://usaco.org/current/data/sol_highcard_silver_dec15.html
CC-MAIN-2018-17
refinedweb
491
62.27
The JDBC API works with two and three tier architecture and support four types of drivers to help you work with DBMS without much difficulty. It uses java.sql and javax.sql package to work help you out. This post introduces you to the JDBC basics. Java DataBase Connectivity The JDBC api is provided with JAVA SE and EE as a core API. it is available in two packages, java.sql and javax.sql. However our scope of discussion will be limited to java.sql package. but before that let us know about the JDBC and its architecture. Later on we will tell you more about the type of drivers we use for the JDBC operations. The JDBC API and why we need it? The world has moved on from simple file based application to database oriented softwares. This makes the operation easy and data management and organization really easy. Most of the time we use the Relational Database. The relational database is easy to use and understand. This name relational indicates that the data in the database is related to each other in some way or other. But before we dive deeply in the Relational database concepts let us know more about why we need JDBC. So, we know there is something known as Databases and we also know we must use them to make the data management easier for long term as we can not rely on the temporary data. So JDBC API gives the power to interect with DBMS via SQL. you will write the SQL queries and get result set from the execution of that query. This process will occur through the JDBC API. There are two type of architecture for JDBC which we know as Two-Tier Architecture and Three-Tier Architecture. Two-Tier Architecture In two Tier Architecture the Application directly communicates to the DBMS throught the JDBC. In this case generally the DBMS and the Java application are both supposed to be but not necessarily on the same machine. As you can see in the Diagram the JDBC is with the Java application. The DBMS may be on the same machine or can be accessed through the Internet. Three Tier Architecture In Three Tier Architecture the application usually access the DBMS through a middle ware where this middle ware is a servlet application. The front end may or may not be Java applet. The data if first communicated to the middleware through a web protocol like http, and then servlet connects to the DBMS using the JDBC API as you can see in the Image. Note: The Images are taken from official java tutorials hosted by Oracle. You may read there to understand the concept more deeply, though we have tried to keep it as simple as possible. Type of Drivers The drivers are necessary as the DBMS software you are using may be different for different applications. There are four types of Drivers not named differently but in types as you may see below. Type 1: This is a JDBC-ODBC bridge type driver. In this type the JDBC API is mapped on the platform specific API. So this is always the platform dependent. You will need a different Driver if you want to move on to a different platform. Type 2: This is Partly written in Java and partly in the native language like C or C++. This makes it fast and more compatible but again not so good for the portable Apps. Type 3: These drivers are created in Java and they use a middleware to communicate with the database server. Type 4: This is the Final type of drivers which directly communicates to DBMS and are written in java which makes them best to be used with java application. Now that we know about the JDBC Basics you must know some basics for using JDBC. Please mind the following steps these are handy for you if you are looking forward to JDBC programmin. Step 1: Call the Driver for your DBMS type. For Example if you are using MySql the driver call will be executed using a string "com.mysql.jdbc.Driver". This string will call the driver for Mysql DBMS. Step 2: Because there is always a chance for the Exception as the driver string may not be found and throw the ClassNotFoundException or else the SQLException may be thrown if something goes wrong with SQL statements. So you better be prepared already. Put the code under try-catch block. Step 3: Now create the connection with the Database using the DriverManager class. Don't worry if you don't know this just yet. We'll explain in a bit. Step 4: Finally you can create the statement and execute that statement. Which will return a result set with the resuld from that query. Thats pretty much what you need. But first please pay attention to following Note. IMPORTANT: This is really important that you have the driver file included. What we mean by that is, for every type of database there is a driver class provided by the vendor. This is usually in the form of JAR files which must be added to the class path of the system. Of course there is other way that you can include it in the build file but that is out of our scope of discussion, yet You may google "Using Ant to build java application", this will help you with it. And if you are using the IDE software there is always an option to include external JAR file, which will help you out easily. The whole point is to avoid ClassNotFoundException on the Class.forName("driver-string"); when you try to call the driver for your DBMS. you can download the mysql driver which is known as MySql Connector here. We will be using mysql Database for our demonstration. This is necessary that you have installed mysql server software. We are using phpmyadmin which is GUI interface for the MySql. So be careful for the mysql and the configuration before proceeding. Now we are first creating the Database by the name of student. create Database student after creating database you may create a sample table student_info which we will be using for some sample operations. CREATE TABLE `student_info` ( `rollnum` int(11) NOT NULL AUTO_INCREMENT, `Name` varchar(20) NOT NULL, `Class` varchar(10) NOT NULL, PRIMARY KEY (`rollnum`) ) Now this will give you a table. however you may also create table using the JDBC program, which we are going to demonstrate now. Look at following program this will demonstrate the prepration you need before you may proceed to query writing. package jdbc; import java.sql.*; public class TestJDBC { public static void main(String[] args){ try{ Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver Accessed"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student","root",""); System.out.println(con); } catch(Exception e){ System.out.println(e); } } } The output of this program on our system is like this: Driver Accessed com.mysql.jdbc.JDBC4Connection@23d4616f Now the Driver was found if the classpath for the connecter would not be set it would have thrown a ClassNotFoundExceptino but it found the driver and then it was able to create the connection. Now what you need is to pay attention at the getConnection() string, which will connect to the database and will return a connection reference, where connection is an interface used to keep the connection alive until we are finished up with the operations. As you can see by the object we printing that the driver is of type JDBC4. We are leaving it here for this Tutorial but the next part will tell you more about the Queries and their types in MySql. you can read the next part here, The JDBC Query Processing Reference: Official java tutorials
http://www.examsmyantra.com/article/65/java/introduction-to-jdbc-api
CC-MAIN-2019-09
refinedweb
1,308
64.71
I think if you put this question to any Java developer, you will get an answer supporting the unit test instantaneously. They will tell you that if you can not do unit testing, the unit of code you have written is large and you have to bring it down to multiple testable unit. I have found these questions in Stack Overflow - Integration Testing best practices - Integration vs Unit Testing - Junit: splitting integration test and Unit tests - What is an integration test exactly? useful in getting a good understanding of both terminologies. Unit testing is widely followed in Java domain with most of the projects now also enforcing the code coverage and unit testing. Integration testing is relatively new and misunderstood concept. Even through it is practiced much less than, unit testing there can be various uses of it. Lets take a simple user story and revisit both. Lets consider it with a user story User will give an INPUT in a UI form and when the submit button is clicked, the PROCESSED output should be shown in the next page. Since the results should be editable, both INPUT and OUTPUT should be saved in the database. Technical Design Lets assume that our application will grow rapidly in the future and we will design it now keeping that in mind. As shown in the above image it is a standard 4-tier design with view, service, dao. It has a application layer which contains the logic of how to convert the input into output. To implement the story we wrote 5 methods(1 in service, 2 dao to save input and output, 1 contains the business and 1 method in view layer to prepare the input.) Writing some Unit test cases If we were to unit test the story, we need to write 5 tests. As the different layers are dependent, we might need to use mock objects for testing. But apart from one method in application layer that does the original process, is there any need to unit test the other part? For example the method, public void saveInput(Input input){ Session session = sessionFactory.getCurrentSession(); session.save(input); } When you unit test this, you will typically use a mock object of sessionFactory and the code will always work. Hence I don’t see much point in wiring a unit test here. If you observe carefully, apart from the application layer, all the other methods will be similar to what we have discussed. What can we achieve with integration test? Read here as a heads up for the integration test. As we have seen most of the unit tests for this story were not effective. But we can’t skip testing as we want to find out the code coverage and make our code self testing. According to Martin flower in his article about Continuous Integration you should write the code that can test the other code. I fell the good integration tests can do this for you. Lets write a simple integration test for this situation, @Configurable(autowire = Autowire.BY_NAME) @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class SampleIntTest { @Autowired private SamService samService; @Test public void testAppProcessing(){ Input input = new Input(); //prepare input for the testing. Output output = samService.processInputs(input); //validate outpt gainst the given input. if(!isValidate(input,output)){ Assert.fail("Validation failed!"); } } I have skipped the view layer here as it not so relevant. We are expecting the INPUT from the UI in a bean Input and that’s that we will have in the service layer. Here, With this few line of coding, you can achieve the full functionality of the application from the service layer. It is preferred to use a in-memory database like H2 for integration tests. If the table structure is complicated it may not be possible in that case,you can use a test instance of DB and prepare a script to delete all the data and run it as part of the test so that the DB state is restored back. This is important because in the next run the same data will be saved again. Another advantage of integration tests is that if you are changing the implementation the test need not be changed because it is concerned with the input and output.This is useful in refactoring the code without change in the test code. Also, you can schedule these tests to measure the stability of the application and any regression issues can be caught early. As we have seen, integration test are easy to write and are useful, but we need to make sure it does not replace the unit testing completely. When ever there is a rule base system(like the LogicalProcesser in our case) it should be mandatory because you can’t cover all the scenarios with the integration test. So as always JEE is about making choice asnd sticking to it. For the last few months we were practicing it in our teams and it is really going well. Currently we made integration test mandatory and unit tests and optional. Always review the code coverage and make sure you get good coverage in the core of the system(the LogicalProcesser in our case). Reference: When to replace Unit Tests with Integration Test from our JCG partner Manu PK at the “The Object Oriented Life” Blog. - Regular Unit Tests and Stubs – Testing Techniques 4 - Code coverage with unit & integration tests - Java RESTful API integration testing - Spring 3 Testing with JUnit 4 – ContextConfiguration and AbstractTransactionalJUnit4SpringContextTests - Mock Static Methods with PowerMock - Java Tutorials and Android Tutorials list
http://www.javacodegeeks.com/2011/11/when-to-replace-unit-tests-with.html
CC-MAIN-2014-15
refinedweb
932
61.26
Program to Find GCD, examples of different ways to calculate GCD of two integers (for both positive and negative integers) using loops and decision making statements. To understand this example to Find GCD, you should have the knowledge of following C++ programming topics: - C++ if, if…else and Nested if…else - C++ for Loop - C++ while and do…while Loop The largest integer which can perfectly divide two integers is known as GCD or HCF of those two numbers. Program to Find GCD using the while loop #include <iostream> using namespace std; int main() { int n1, n2; cout << "Enter two numbers: "; cin >> n1 >> n2; while(n1 != n2) { if(n1 > n2) n1 -= n2; else n2 -= n1; } cout << "HCF = " << n1; return 0; } Output Enter two numbers: 78 52 HCF = 26 In the above program, a smaller number is subtracted from the larger number and that number is stored in place of the larger number. This process is continued until two numbers become equal which will be HCF. Program to Find HCF/GCD using for loop ; } Output Enter First Number : 1 Enter Second Number: 5 Greatest Common Divison (GCD):1 The logic of this program is simple. In this program, the small integer between n1 and n2 is stored in n2. Then the loop is iterated from i = 1 to i <= n2 and in each iteration, the value of i is increased by 1. If both numbers are divisible by i then, that number is stored in variable hcf. When the iteration is finished, HCF will be stored in variable hcf. Related Programs - C++ Program to display factors of a Number. - C++ Program to check whether a number is a Palindrome or Not. -. Ask your questions and clarify your/others doubts on C++ Selection Sort Program by commenting. Documentation.
https://coderforevers.com/cpp/cpp-program/hcf-gcd/
CC-MAIN-2019-39
refinedweb
296
65.86
Punchagle - 100 (Algo) Write-up by GenericNickname Created: 2015-12-07 Problem There's a lot of images here, like, a lot. But they have significance. Each image contains a punchagle, similar to the punch cards used in old computers. You're given that each shape represents a number, 0-9, and when 1 to 3 shapes in a row are converted to numbers, they make an ASCII character decimal value. 0 = filled circle 1 = outlined circle 2 = filled square 3 = outline square 4 = filled triangle 5 = outlined triangle 6 = filled semicircle UP 7 = outlined semicircle UP 8 = filled semicircle DOWN 9 = outlined semicircle DOWN The flag is hidden somewhere in those, convert all the images and find it. sctf{FLAG} is the format. Files Hint Imaging libraries might help. Answer Overview Read the symbols off the images as their decimal values and then locate the flag in the output, probably with the aid of an imaging library (as indicated by the hint). Details There are many imaging libraries, but I decided to go with Pillow, which is for Python (Python 2.7 in my case). After examining some images, I realized it would be possible to just go through and match the numbers at the top of the images and then go through row by row and match the symbols. Pillow allowed me to do direct image evaluation, so it was just a matter of isolating the numbers and symbols, then trying to match them. I made this image by copying the symbols out of the triangles so I would have something to match against: To get the symbols into python, I loaded them as two arrays: symbols = [] numerals = [] symbolBase = Image.open("punchagle_symbols.png") for x in range(0, 10) : symbols.append(symbolBase.crop((x * 11, 0, x * 11 + 11, 11))) for x in range(0, 10) : offset = 0 #this offset is due to how it was easiest to recognize the numbers; #all numbers other than 1 and 4 only took up 5 pixels, so I special-cased 1 and 4 if x == 4 or x == 1 : offset = -1 numerals.append(symbolBase.crop((x * 6 + 1 + offset, 11, x * 6 + 6 + offset, 18))) After making my list of symbols, I wrote a function that would tell me what symbol index a particular image matched to, or -1 if it couldn't find a match: def getImageSymbol(syms, img) : for x in range(0, len(syms)) : if(syms[x] == img) : return x return -1 The nice thing about the triangles in this set is that it was very easy to determine where numbers and symbols were in the triangles, so I used a lot of hard coded values to read them. I used this function to read how many rows were in the triangles by checking first for 1 digit, and if it didn't match, then reading for 2 digits: #show flag is for debugging, can be ignored in normal running def getRowCount(numerals, test, show = False) : #attempt to find 1 number row count num = test.crop((test.width / 2 - 3, 32-7, test.width / 2 + 2, 32)) numRows = getImageSymbol(numerals, num) if (numRows == -1) : #if 1 number isn't readable, get row count from 2 numbers num1 = test.crop((test.width / 2 - 6, 32-7, test.width / 2 - 1, 32)) num2 = test.crop((test.width / 2, 32-7, test.width / 2 + 5, 32)) n1 = getImageSymbol(numerals, num1) * 10 n2 = getImageSymbol(numerals, num2) if(n1 == -1 or n2 == -1) : if show: num.show() num1.show() num2.show() return -1 numRows = n1 + n2 return numRows Once I knew how many rows there were, I went through each row and read the symbols off it with this function:) : sym = getImageSymbol(symbols, rowSyms.crop((20 * x, 0, 20 * x + 11, 11))) #this if can be ignored for now, it will be helpful for Punchagle 2 where symbols are omitted if(sym == -1) : tmp += 'x' else : tmp += str(sym) return tmp The rest of my program was a funtion for reading the triangles and walking through the directory to read all the images: def readTriangle(symbols, numerals, img) : rows = getRowCount(numerals, img) res = "" for x in range(1, rows + 1) : res += readTriangleRow(symbols, img, x) return res out = open('symbolOutput.txt', 'w') import os rootdir = 'images' count = 0 result = "" for subdir, dirs, files in os.walk(rootdir): for f in files: count += 1 if count % 100 == 0 : print count #to see how far we've gotten test = Image.open(os.path.join(subdir, f)) result += '\nTriangle: ' + f + '\n' result += readTriangle(symbols, numerals, test) out.write(result) out.close() The entire program can be downloaded here: image_symbols.py Now that I had symbolOutput.txt, I could search for the ASCII values that should show up where the flag is. The problem says that the flag starts with sctf{ so I looked for 11599116102123 in the output and identified the end by 125, which is }. The entire string of digits was 1159911610212311211410111611612199111111108114105116101125, which, when turned into ASCII yields the flag: sctf{prettycoolrite} Flag sctf{prettycoolrite} Extra Information This solution would not have worked if the flag had been across triangles, although it could have been modified to work by removing result += '\nTriangle: ' + f + '\n' from the output and ensuring that the file system was being read in the correct order.
https://sctf.ehsandev.com/algo/punchagle.html
CC-MAIN-2019-04
refinedweb
885
63.63
Important changes to forums and questions All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com. 4 years, 3 months ago. How to use MCP2515 for LPC1114FN28? Hi everyone! I' m not good at English so this question is confusing. I am confronted with a difficult problem. Please help me. My goal is construct system using CAN. And the system use only mbed LPC1114. First, I try to use MCP2515 connected to LPC1768. Because mbed LPC1114 have not CAN pin like mbed LPC1768(ex: p29,p30) . It can work good. I use mcp2515.h library (). This is very good library. It is useful function design. Second, I try to MCP2515 connected to LPC1114. This is not work. Error is bellow. Error: Identifier "CANFormat" is undefined in "mcp2515/mcp2515.h", Line: 90, Col: 45 Error: Identifier "CANMessage" is undefined in "mcp2515/mcp2515.h", Line: 91, Col: 52 Error: Identifier "CANMessage" is undefined in "mcp2515/mcp2515.h", Line: 92, Col: 54 Error: Identifier "CANMessage" is undefined in "mcp2515/CAN3.h", Line: 22, Col: 19 Error: Identifier "CANMessage" is undefined in "mcp2515/CAN3.h", Line: 23, Col: 17 Error: Identifier "CANMessage" is undefined in "main.cpp", Line: 16, Col: 6 I think this error came from CANMessage class inCAN.h. LPC1114 is DIP so it has not FPGA like LPC1768. I use two med platform. mbed LPC1768 (), mbed LPC1114 (), and two IC. MCP2515, MCP2551. and I change the library in can speed. because I use 20Mhz. I think to add the new header that define CANMessage. What I do this program. My code is bellow include the mbed library with this snippet #include "mbed.h" #include "CAN3.h" SPI spi(dp2,dp1,dp6);// mosi, miso, sclk CAN3 can(spi,dp10,dp11); DigitalOut led2(LED2); DigitalOut led1(LED1); Serial pc(USBTX, USBRX); int main() { char data[1] = {0}; can.frequency(125000); CANMessage msg(2002,data,1); msg.data[0] = 253; while(1) { can.write(&msg); pc.printf("Send:%d\r\n",msg.data[0]); led1 = !led1; wait(0.5); } } 1 Answer 4 years, 3 months ago. Hi, This is because the LPC1114FN28 doesn't support CAN in the device.h platform definition file. Therefore, CANFormat and CANMessage definitions are not included in the build. Following header file example is a small hack to avoid this issue (i.e. to use CAN related helpers with Non-CAN platform). can_suppor.h #if (DEVICE_CAN) == 0 enum CANFormat { CANStandard = 0, CANExtended = 1, CANAny = 2 }; typedef enum CANFormat CANFormat; enum CANType { CANData = 0, CANRemote = 1 }; typedef enum CANType CANType; struct CAN_Message { unsigned int id; // 29 bit identifier unsigned char data[8]; // Data field unsigned char len; // Length of data field in bytes CANFormat format; // 0 - STANDARD, 1- EXTENDED IDENTIFIER CANType type; // 0 - DATA FRAME, 1 - REMOTE FRAME }; typedef struct CAN_Message CAN_Message; class CANMessage : public CAN_Message { public: /** Creates empty CAN message. */ CANMessage() : CAN_Message() { len = 8; type = CANData; format = CANStandard; id = 0; memset(data, 0, 8); } /** Creates CAN message with specific content. */ CANMessage(int _id, const char *_data, char _len = 8, CANType _type = CANData, CANFormat _format = CANStandard) { len = _len & 0xF; type = _type; format = _format; id = _id; memcpy(data, _data, _len); } /** Creates CAN remote message. */ CANMessage(int _id, CANFormat _format = CANStandard) { len = 0; type = CANRemote; format = _format; id = _id; memset(data, 0, 8); } }; #endif And then, you can include this can_support.h from the mcp2515.h file. I hope this helps. Toyo
https://os.mbed.com/questions/68586/How-to-use-MCP2515-for-LPC1114FN28/
CC-MAIN-2020-29
refinedweb
572
69.38
Alternative Browsers Impede Investigations 720 rbochan writes "Allegations in an article over at CNET propose that alternate browsers such as Firefox and Opera impede law enforcement and investigation efforts because they "use different structures, files and naming conventions for the data that investigators are after", which can "cause trouble for examiners."" It's *not* rocket science, guys... (Score:5, Insightful) This is one of the dumbest articles I've read in a while... From TFA: Implying that 'alternate browsers' such as Firefox and Opera, 'hide' data? Shenanigans! These other browsers don't 'hide' anything...you just have to know where to look. Also from TFA: You can't be serious. If it's this easy to thwart the authorities, maybe I should tender my resume. God help these 'professionals' if a suspect's computer happens to run Linux...which brings up a disturbing thought...is the presence of a 'non-standard' browser or OS now going to be 'suspicious' to investigators, because they can't seem to penetrate its 'arcane secrets'? Re:It's *not* rocket science, guys... (Score:5, Funny) Re:It's *not* rocket science, guys... (Score:3, Funny) On the BeOS version of Firefox it's ALT+H, not CTRL+H! Re:It's *not* rocket science, guys... (Score:5, Funny) Re:It's *not* rocket science, guys... (Score:5, Funny) Good job. Now you've flagged yourself and the FBI is undoubtedly on its way. Giving away what is most likely a National Secrect! Please don't let them look here [mozilla.org]. Re:It's *not* rocket science, guys... (Score:5, Informative) Digital forensics is performed offline. You don't run the browser software to read its history. However, I fail to see how this would create problems for law enforcement. Most of the interesting data is readily available. And the data formats haven't changed that much since the days when Netscape was the dominant browser. Re:It's *not* rocket science, guys... (Score:5, Funny) Maybe their forensic tools can extract the browser history from the file and the software isn't aware a bookmarks file doesn't have to be named "favorites". At least I hope that's the issue. Tip for Kiddie Porn addicts: Keep your vids in someplace besides the "My Videos" folder. The authorities will never be able to find them if they're "hidden" in some other folder. Re:It's *not* rocket science, guys... (Score:3, Funny) The Spooks are confused as hell. In fact, the last time I was investigated, one of the Detectives said "Fuck this!", whipped out his own high powered magnet, and aced my computer. Ummm - it's not offline (Score:5, Interesting) Their parole office will drop by periodically and check their PC. They have some sort of forensic software that does this. I've heard some jurisdictions require that you only run Windows on your computer as a condition of your parole. Logically this translates to going back to prison for owning a knoppix cd. There simply aren't the resources to train all parole officers in computer forensics, expose them to various obscure operating systems, or to perform regular offline analysis of offenders hard drives. The resources are (probably) there for big cases, but when there are probably close to half a million sex offenders on parole - it's just not practical. Re:Ummm - it's not offline (Score:3, Insightful) I agree (Score:3, Informative) You can find clues of these things though. Look at the vnc history, try pinging the broadcast address on the subnet, look in the arp cache, see if there are clues in the registry that another drive was mounted. I suspect it would be very hard to thwarte a computer forensics expert, but i'm sure the VAST majority of petty criminals can be caught by someone with a weeks worth of trai Re:Ummm - it's not offline (Score:3, Insightful) It's up to the government to get with the times and update their forensics software. If their software vendor can't do it for them (no pun intended) then change vendors. Bwahaha. If your a sex offender you HAVE to use M$ (Score:5, Funny) Male voiceover "Microsoft, used by 100% of all sex offenders. Its not only the law, it their punishment." Oh! I just fell off my chair. Re:Ummm - it's not offline (Score:4, Insightful) Welcome to Oops! Here, we have aa drunken frat boy who took a whiz in a parking lot. Public indecency, sex offender. Over here, we've got a highschooler who mooned his principal on graduation day. Sex offender. So lets all say it together! "OOPS!" Keep that in mind while you're busy waving around your burning crosses and what not. Not everyone who is a "sex offender" is a child rapist, or even really all that offensive. Re:Ummm - it's not offline (Score:5, Insightful) But for now, you can murder somebody, and you don't have to register, but mooning somebody, peeing outside, or being 20 and having sex with a 17 year old who said she was 19 can get you labeled as a sex offender for life (depends on the state) and that's just plain wrong.I suspect that varies from state to state. In any event, even if you molest your child, you're still their parent, so it would seem appropriate that you should still have `paternal rights' (which is a remarkably vague concept anyways.) They (Child Protective Services and similar government organizations) don't generally take children away from their parents and never ever give them back except maybe in the most extreme cases. Being placed in a foster home or orphanage, especailly forever, is seriously disruptive to a child's life, so they're not going to do that if there's any other alternative. They'll have to look at each case individually and try and work out what's best for the children. In most cases, that probably involves staying with the parent(s), and instead getting counselling for the parents or something. Infants generally have no problems getting adopted. But once the kids grow up a bit, things change, especially if they're not white. Few people want to adopt them, and so they get shuffled between foster parents and orphanages. Not a good way to grow up. Re:It's *not* rocket science, guys... (Score:5, Interesting) Re:It's *not* rocket science, guys... (Score:5, Informative) ------------ #!/usr/bin/perl -w use File::Mork; my $mork = File::Mork->new('history.dat', verbose=> 1) || die $File::Mork::ERROR."\n"; foreach my $entry ($mork->entries) { while (my($key,$val) = each %$entry) { print "$key = $val\n"; } print "\n"; } ------------ BTW, I do realize that your post was sarcastic... as is this one. Works perfectly if run in the same directory as history.dat and produces output like: ID = 388D URL = [google.com] Hostname = google.com LastVisitDate = 1125064549 FirstVisitDate = 1125064549 Name = Google It should be left to guru perl coders making $500,000/yr or more to do fancy things like convert timestamps to dates. I guess it's a good thing that there are no tools available for Windows that auto-clear IE history, cookies or cache files! What would law enforcement do?? Re:It's *not* rocket science, guys... (Score:5, Funny) Now THIS is funny - from the File::Monk man page: THE UGLY TRUTH LAID BARE ^.. [livejournal.com] [jwz.org] In brief, let's count its sins: * Two different numerical namespaces that overlap. * It can't decide what kind of character-quoting syntax to use: Backslash? Hex encoding with dollar-sign? * C++ line comments are allowed sometimes, but sometimes *. Pure comedy. Re:It's *not* rocket science, guys... (Score:3, Funny) Luckily it also popped-up everything I had open with a restart. Re:It's *not* rocket science, guys... (Score:5, Funny) Lt.Jones: "You you know Smith, I sometimes wonder if we just were competant with computers if we could well, you know, understand basic computer forensics instead of relying on software to do it for us?" Sgt.Smith: "Shutup Jones, theres a way we do things here, it's the microsoft way, all other ways are abhorant and methods of the terrorists." Lt.Jones: "Good call Smith!" *sigh* It's only sad because it could be true. Police forces need to hire security professionals and train them to be computer forensics. Not hire police officers and rely on them to learn the ins and outs of computer security. Re:It's *not* rocket science, guys... (Score:5, Insightful) Simple as that. Re:It's *not* rocket science, guys... (Score:5, Insightful) But I wish more software was designed with leaving a small or non-existant trail as a design consideration. When I speak on the phone, none of it get's recorded unless someone makes a special effort to do so. I would hope my computing experience could be the same. And I really hate the idea that a bunch of you people are thinking I'm some kind of major criminal for wanting it that way. If you happen to be one of the ones that think I should be happy to have everything logged, then please set up a web cam in your bedroom and tape everything that happens. After all, there really isn't any chance of it falling into the wrong hands and law enforcement might need to check those tapes to make sure you're not snorting coke in there. Cops are good people and none of them will laugh about what you're doing witht that banana. I promise. TW Re:It's *not* rocket science, guys... (Score:3, Insightful) Re:It's *not* rocket science, guys... (Score:3, Insightful) That's just begging for a virus/trojan that might infect a PC to steal confidential data. Re:It's *not* rocket science, guys... (Score:5, Informative) There you go, transparent encrypted directory. Also, Truecrypt [truecrypt.org] is capable of encrypting stuff too. Re:It's *not* rocket science, guys... (Score:5, Insightful) Which means it is transparent to the logged in user, which means it is transparent to the virus/ trojan horse/ spyware. And your point? Re:It's *not* rocket science, guys... (Score:5, Informative) Yeah and then a few weeks later... (Score:3, Informative) Yeah, it happened at work, and it was not pretty. Re:Yeah and then a few weeks later... (Score:4, Informative) yes it does (Score:5, Informative) Re:It's *not* rocket science, guys... (Score:3, Interesting) Right click the directory you want to un-encrypt, select properties, security, and press teh advanced button. Select the 'Owner' tab, then add your user account and administrator as owners. Remove all other owners. Check Replace owner on subcontainers and objects Switch the the Permissio does this say something about education? (Score:3) If I were the authorities I would be insulted by this article and it implying they aren't smart. In a related story ... (Score:5, Funny) Said an officer who wished to remain anonymous: "We're not even sure there was a murder without some trace of lead at the scene. A bullet Re:does this say something about education? (Score:3, Insightful) To condense some of the comments on the original CNet page: you wouldn't expect the cop to identify the cause of death in a murder investigation, you'd leave it to an expert (the coroner). You wouldn't expect the cop to check a car engine for tampering, you'd leave it to an expert (a mechanic). As such, there shouldn't be any expectation that the cop should have to go through Another article with the same logic (Score:5, Interesting) Re:Another article with the same logic (Score:5, Insightful) No, it doesn't. (Score:3, Funny) Forget about locking doors... (Score:3, Funny) If you wear pants, that means that you've got something to hide. Re:Another article with the same logic (Score:3, Informative) google cache: Re:Another article with the same logic (Score:3, Insightful) Probably, cuz it says "This is satire" right there in the footer Re:It's *not* rocket science, guys... (Score:5, Funny) Re:It's *not* rocket science, guys... (Score:5, Interesting) Re:It's *not* rocket science, guys... (Score:3, Insightful) This being said..... If we are to value the market economy, we can't let the incompetence of law enforcement be used as an excuse to bully us into using a product released by a convicted monopolist..... Re:It's *not* rocket science, guys... (Score:3, Interesting) So what's your solution? (Score:5, Funny) Re:It's *not* rocket science, guys... (Score:5, Insightful) we hired an Ex FBI computer forensics expert, he "retired" 3 years ago at the age of 37. the man knows absolutely nothing about computer forensics. I started talking to him during lunch to ask him how he would recover evidence from a company PC that a user was using to surf kiddie porn with. He said you grab the IE history folder and temp internet folder. I asked so what do you do when that user uses the option to empty the contents of that folder or uses XP power tools to set it to empty it on a regular basis. or installed one of those "hide your tracks" programs you get spams about every other week? He responded that highly skilled hackers like that are not common in the business world and then he would have to send the drive in for electron microscope examination. The man shit his pants when the situation finally came around that he was unable to retrieve evidence from a ex employee's laptop. I gave them a printout of cookies to all the websites the guy visited and a detailed record of his ill-gotten web useage for the last week he was here. I used my leet haxor skillz and unleased a secret tool called proxy server logs as well in my 20 minutes. He took 7 days to retrieve nothing. and at that time I was a lowly know-nothing IT guy. moral of the story? if you have 1/2 a brain it is really easy to elude the police in "computer crime" and hide all your evidence easily. the only thing going for the police is that the typical criminal is working with 1/16th of a brain. Re:It's *not* rocket science, guys... (Score:5, Interesting) For example: I have a friend who works in IT for a law enforcement agency. He constantly gets calls from their computer forensics specialist asking for help on why his station won't boot. Usually it's because he overwrote his boot sector while ananyzing a drive (I don't understand either). Unfortunately the prevailing opinion is that teaching a street cop technology is easier than teaching a tech the intracate details of law enforcement. The higher ups don't realize that any IT persons job is basically an daily investigation. I think the answer is to pair up the two, but again, none of these agencies has asked me. Re:It's *not* rocket science, guys... (Score:3, Funny) They'd give the computer back to its owner out of compassion for him being such a geek that he needed to look at pr0n all day in lieu of getting laid. At least, that's what happened to me... New Firefox Ad: even the popo can't touch this (Score:5, Insightful) In other words, they seem to be slamming Firefox, but actually it is pretty good advertisement for Firefox. They should put on their front page. "Even the brightest police investigators can't look at your browser history! Get Firefox today, the most secure browser." Re:New Firefox Ad: even the popo can't touch this (Score:5, Funny) Re:New Firefox Ad: even the popo can't touch this (Score:3, Informative) Re:New Firefox Ad: even the popo can't touch this (Score:5, Funny) Re:New Firefox Ad: even the popo can't touch this (Score:3, Interesting) Now extend that to advertising your software as creating barriers to law enforcement investigations. Conspiracy to obstruct justice in an investigation to which national security is attached? The one thing they should not do is promote this as a feature of their browsers! Meanwhile, with the open source browsers, this should give ideas to people who do want to hid Re:It's *not* rocket science, guys... (Score:5, Informative) Cmon.. any advanced porn^H^H^H^H surfer knows to go to google, enter the url and click through google's url. That way you don't have a suspicious empty dropdown bar and you can simply delete the url and google's search url) from the history and for all intents and purposes, you never went there (just dump the cache). I guess these guys were never married. Simply having an attentive wife teaches you that FED defeating trick. The location dropdown bar and autocomplete can be a lot of trouble. Heh Re:It's *not* rocket science, guys... (Score:3, Funny) Not that I do that. Er, it works. Re:It's *not* rocket science, guys... (Score:3, Funny) Hopefully she not attentative enough to read your /. postings... Re:It's *not* rocket science, guys... (Score:5, Funny) I found this out really quick after the SO moved in. Right after she went to check the website of her university which starts with a 'C' and the first link that pops into the autocomplete bar is Cumfiesta. I just bought her a computer of her own. Re:It's *not* rocket science, guys... (Score:3, Insightful) Re:It's *not* rocket science, guys... (Score:3, Interesting) God help these 'professionals' if a suspect's computer happens to run Linux I remember reading a while back that when the FBI seizes a macintosh computer they ship it to the Canadian Mounties for data recovery because the FBI does not know how to recover data from macintosh computers. I don't know if that is true, but I would not be surprised. Re:It's *not* rocket science, guys... (Score:3, Informative) One of my students is an Indiana State Trooper undergoing computer forensics training. Since he's enthusiastic about his classes, I get to hear about what he's being taught at all his Homeland Security-sponsored courses. And it turns out that he's learning some pretty complex things, at least as far as examining the contents of hard drives. He has programs that can analyze Windows or *nix systems with a good level of accuracy. He talks about looking at pa Re:It's *not* rocket science, guys... (Score:5, Funny) "It's an outrage! Why do people insist on impeding our efforts to be an all-seeing eye?" And In Other News (Score:5, Funny) Dear god no! (Score:5, Insightful) Browser concerns (Score:3, Interesting) Firefox and Opera may use a different method of file structure/ naming, but they *do* have a fundamental process and that process does not vary from system to system. If you use Firefox... (Score:4, Funny) Re:If you use Firefox... (Score:4, Funny) The poor bastards in law enforcement are powerless against it, and I am evil, evil, evil for not living my life with an eye toward making it pathetically easy for any traffic cop to fully investigate me for anything, as any good PATRIOT should. Muuuuuuuhahahahaha! KFG In other news... secret hideouts (Score:5, Funny) TOR (Score:4, Funny) Professional white-hat script kiddies (Score:5, Insightful) Effectively, they're professional script kiddies working for the common good instead of against it. The lesson? Training. You wouldn't put a detective in the morgue and hand him a scalpel, and you wouldn't drop him in a science lab. You'd hire a coroner, you'd hire someone trained in forensic science. If you're going to search someone's computer for evidence, hire an expert or train someone to become an expert. script kiddies are vermin, Color of hat regardless (Score:4, Insightful) Nobody should ever make it easy for script kiddies (especially because they have a Chicken Inspector Badge). Re:Professional white-hat script kiddies (Score:3, Insightful) They're too damn busy for the "little stuff", but not to busy to cross the street to write me a ticket for riding my bike on an empty sidewalk. Profit! (Score:3, Funny) Help me out, /.!!! 1. Submit patent. 2. ??? 3. Profit! This explains everything! (Score:3, Funny) Um, Duh? (Score:5, Interesting) Firefox and Opera store information on typed URLs in a different file than IE does, and the files are somewhat tough to decipher You would think since Firefox is open-source, it would be a trivial matter to determine the format of the cache files by examining the source code. Re:Um, Duh? (Score:3, Insightful) No? What good is the source code going to do him? Re:Um, Duh? (Score:3, Insightful) None...but if they divert some of the money they spend on, say, hiring Psychics(tm) hiring a programmer (or for that matter just "someone skilled with computers") THAT person may be helped by it, and can certainly develop some simple "how to find where Firefox puts stuff" training for them. Re:Um, Duh? (Score:3, Insightful) If they can hire a programmer who has a clue then just get him to write a script for Encase that automatically searches out and displays Firefox, Opera, Safari, and other browser caches and logs. It would not be very hard at all. Distribute said script to all the police departments, and have the forensic I laughed (Score:5, Funny) Now I weep for them. Wait a second! (Score:4, Funny) Totally hose 'em up... (Score:5, Funny) Guilt by association... (Score:3, Funny) I say, if these "citizens" don't want to be "spied" on, they are SUSPICIOUS! SEND THEM TO GUANTANAMO! Meanwhile, in Soviet Russa... In a word: (Score:3, Interesting) That's one of the reasons I use Firefox, Thunderbird, Sunbird, etc... Security by obscurity is not essentially valid, but it can be useful. The government can't force people to organize their thoughts or ideas written down on legal pads with sworn oaths as to dates & times, why should ANY information be handed to them. I run may trace eliminators, for this purpose. I encrypt my file system. If this is going to slow them down or prevent them from gathering evidence, it's done it's job. Just another reason not to buy into the Microsoft way. (I'm not being facetious, it's true: Microsoft has an agenda to be on the side of the law, they HAVE to be lobbying quietly to get stuff like this out and laws passed to enforce it.) It's not the software . . . (Score:5, Informative) Re:It's not the software . . . (Score:3, Interesting) "Officer MacGruff, are you an expert in computer forensics? Can you summarize your education? Can you describe your methodology?" This reminds me of the whole speed camera thing in AU, where they lost a major court case because, given 8 weeks, they couldn't find an expert willing to testify on the relability of hashes as MACs. Not because the testimony wasn't believed, mind, but that they didn't have any. Re:It's not the software . . . (Score:3, Informative) Specifically, poorly trained in tech matters. (one would hope, not poorly trained in investigation/law enforcement and the kind of stuff that should be their "core competancies") I work for a phone company, and often work with various police agencies' "special investigation" units. The officers that I deal with are usually 6-8 year veterans, and have been rotated into SI for a 3-4 year stint. When they have to deal with the interface hardware that they have at ou "you want to frustrate law enforcement, use a Mac" (Score:5, Interesting) A visit from the FBI By Scott Granneman, SecurityFocus Published Wednesday 28th January 2004 13:05 GMT [snip] I teach technology classes at Washington University in St. Louis, a fact that I mentioned in a column from 22 October 2003 titled, "Joe Average User Is In Trouble [securityfocus.com]"... [snip] Dave had some surprises up his sleeve as well. You'll remember that I said he was using a ThinkPad (running Windows!).. In the field, however, they don't have as much money to spend, so they have to stretch their dollars by buying WinTel-based hardware. Are you listening, Apple? The FBI wants to buy your stuff. Talk to them!. [snip] Dumb law enforcement vs. dumb criminals (Score:4, Insightful) And if the law enforcement can't figure out how to write a simple tool to decipher the files that are left behind from alternative browsers (especially one like Firefox that is open-source, meaning that the format of such files would be easy to determine), then that's just, well, pathetic. And finally, I think that this is a good thing. Most people in this world will probably never ever have to deal with law enforcement. But they do have to deal with snooping parents, snooping friends, snooping girlfriends, snooping spouses, snooping bosses, etc., so I welcome this as good news. This is a great idea! (Score:3, Funny) What are people thinking, that businesses and products might exist to serve the needs of the people paying for and using them? What nonsense! Only law enforcement matters! Seriously, even if this were a serious question, don't investigators get MORE useful data in the variations of people's setup? The more unique your suspect's setup, the easier it may be to track them. And of course it's perfectly simple to find the Firefox cache -- can someone just drop them an email? They can print it out, tack it to the wall, and quit with the whinging. In other news.... (Score:5, Funny) Police, baffled by the lack of a blue "e" can't figure out how they used the Internet. "And there's no START button! How are we supposed to find anything?" Why should we believe this? (Score:3, Insightful) The general police forces have managed to get a new story published on how they can not deal with any sort of semi-modern technology. Why should we believe it? If I were the police, and I'm sure the police have at least one or two people smarter than me. then I would go to great lengths to get this story published. Why? Not because I can't figure out Firfox, be because I -can- figure out Firefox. If my suspect thinks that I am too dumb to understand Firfox, then my suspect is far less likely to use powerful encryption. Without the powerful encruption, I -can- read Firefoxes files, and a significant proportion of criminals will think they are safe when they are not. Hell, I'm not even law enforcement but I still find it obvious how this story is a great advantage for the law enforcement community. Safari's the worst of them all. (Score:5, Informative) "Using Safari's new Private Browsing feature, no information about where you visit on the Web, personal information you enter or pages you visit are saved or cached. It's as if you were never there." My Response (Score:4, Insightful) Standardizing Bank Robbery (Score:4, Funny) Allegations in an article over at Police Magazine propose that alternate vehicles such as motorcycles and buses impede bank robbery law enforcement and investigation efforts because they "use different shapes, different numbers of seats, and different logos for the manufacturers that investigators are after", which can "cause trouble for get-away car examiners". Obviously, only Dodge Chargers, like the "General Lee" should be allowed to criminals, to make them easier to catch. A theory... (Score:3, Interesting) After looking over the site [htcia.org], I suspect that "The High Technology Crime Investigation Association (HTCIA)" is a front; it is really a for-profit money-making venture, not a legitimate professional association, as it presents itself. For a genuine professional association, they make too strong an effort to convince us that's what they are. It would work like this: A few guys collect the attendance and membership fees, keeping a big profit for themselves. The fees are paid by governments. The conference attendees, mostly law enforcement officials, receive some stupid advice. Masquerading as a professional organization instead of a for-profit business creates good will, helping them to fleece taxpayers. The content of the training seminars is especially suspicious. Really, how easy is it to uncover the "secret" history files of "alternative" web browsers? I timed myself, and it took me about 90 seconds using Google to work out some good keywords and find the answer. See the first link [holgermetzger.de] in my google search [google.com]. Something else suspicious about this professional training: Because the source code for Firefox is available for free to the public, which is not the case with Internet Explorer, it should be easier, not more difficult, to uncover where and how Firefox logs history. You gotta be kidding... (Score:4, Interesting) That said, I wonder what would prevent someone from creating a wireless fileserver and embedding it behind their drywall. Using an NFSmount or Share, an evildoer's PC wouldn't hold anything evil when the FED's nabbed it. Realistically I bet it would though - They can do some pretty amazing things with Forensics these days, and I wouldn't be surprised if they could take a ram chip and see previous states of 0's and 1's. evil! (Score:4, Interesting) Re:Quick People! (Score:3, Funny) I can see it now: "When you use Firefox, you are supporting terrorism!" It's the kind of funny that makes you want to laugh and cry simultaneously. -- n Cnet is MS Shill (Score:3, Funny) Re:What about Lynx (Score:3, Funny) Re:What's a security expert worth? (Score:3, Interesting)
https://tech.slashdot.org/story/05/09/01/1958220/alternative-browsers-impede-investigations
CC-MAIN-2017-09
refinedweb
5,063
64.51
A Hands-On Example of TensorFlow 2.0 and CNN using the Fashion MNIST Dataset In this tutorial, we will show how you easily build a Convolutional Neural Network in Python and Tensorflow 2.0. We will work with the Fashion MNIST Dataset. First things first, make sure that you have installed the 2.0 version of TensorFlow: import tensorflow as tfprint(tf.__version__) We get: 2.0.0 Load the Data We will load all the required libraries and we will load the fashion_mnist_data which is provided by tensorflow. import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D from tensorflow.keras.preprocessing import image import matplotlib.pyplot as plt import numpy as np import pandas as pd# Load the Fashion-MNIST datasetfashion_mnist_data = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist_data.load_data()# Print the shape of the training dataprint(train_images.shape) print(train_labels.shape) The shape of the train and images and labels is: (60000, 28, 28) (60000,) Let’s also define the labels # Define the labelslabels = [ 'T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot' ] Rescale the images to take values between 0 and 1. # Rescale the image values so that they lie in between 0 and 1. train_images = train_images/255.0 test_images = test_images/255.0 Display the first image: # Display one of the imagesi = 0 img = train_images[i,:,:] plt.imshow(img) plt.show() print(f'label: {labels[train_labels[i]]}') label: Ankle boot Build the Model The model will be a 2D Convolutional kernel (3 X 3) of 16 channels and relu activation. Then we will continue with a Max Pooling (3 x 3) and finally will be a fully connected layer of 10 neurons (as many as the labels) and a softmax activation function. model = Sequential([ Conv2D(16, (3,3), activation='relu', input_shape=(28,28,1)), MaxPooling2D((3,3)), Flatten(), Dense(10, activation='softmax') ])# Print the model summarymodel.summary() We get: Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_2 (Conv2D) (None, 26, 26, 16) 160 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 8, 8, 16) 0 _________________________________________________________________ flatten_3 (Flatten) (None, 1024) 0 _________________________________________________________________ dense_11 (Dense) (None, 10) 10250 ================================================================= Total params: 10,410 Trainable params: 10,410 Non-trainable params: 0 Compile the Model We will compile the model using the adam optimizer and a sparse_categorical_crossentropy loss function. Finally, our metric will be the accuracy. NB: We use the sparse_categorical_crossentropy because our y labels are in 1D array taking values from 0 to 9. If our y was labeled with one hot encoding we would have used the categorical_crossentropy. model.compile(optimizer='adam', #sgd etc loss='sparse_categorical_crossentropy', metrics=['accuracy']) Fit the Model Before we fit the model, we need to change the dimensions of the train images using the np.newaxis. Notice that from (60000, 28, 28) it will become (60000, 28, 28, 1) train_images[...,np.newaxis].shape(60000, 28, 28, 1) We will run only 8 epochs (you can run more) and we will use a batch size equal to 256. # Fit the modelhistory = model.fit(train_images[...,np.newaxis], train_labels, epochs=8, batch_size=256) We get: Train on 60000 samples Epoch 1/8 60000/60000 [==============================] - 51s 858us/sample - loss: 1.2626 - accuracy: 0.6541 Epoch 2/8 60000/60000 [==============================] - 51s 843us/sample - loss: 1.0360 - accuracy: 0.6748 Epoch 3/8 60000/60000 [==============================] - 50s 835us/sample - loss: 0.9219 - accuracy: 0.6908 Epoch 4/8 60000/60000 [==============================] - 50s 837us/sample - loss: 0.8543 - accuracy: 0.7028 Epoch 5/8 60000/60000 [==============================] - 50s 837us/sample - loss: 0.8096 - accuracy: 0.7139 Epoch 6/8 60000/60000 [==============================] - 49s 823us/sample - loss: 0.7762 - accuracy: 0.7214 Epoch 7/8 60000/60000 [==============================] - 52s 858us/sample - loss: 0.7496 - accuracy: 0.7292 Epoch 8/8 60000/60000 [==============================] - 49s 825us/sample - loss: 0.7284 - accuracy: 0.7357 Get the training history # Load the history into a pandas Dataframedf = pd.DataFrame(history.history) df Evaluate the model We will evaluate our model on the test dataset. # Evaluate the modelmodel.evaluate(test_images[...,np.newaxis], test_labels, verbose=2) We get: 10000/1 - 6s - loss: 0.5551 - accuracy: 0.729910000/1 - 6s - loss: 0.5551 - accuracy: 0.7299 As we can see, the accuracy of the test dataset is 0.7299. Make Predictions Finally, let’s see how we can get predictions. # Choose a random test imagerandom_inx = np.random.choice(test_images.shape[0])test_image = test_images[random_inx] plt.imshow(test_image) plt.show() print(f"Label: {labels[test_labels[random_inx]]}") # Get the model predictionspredictions = model.predict(test_image[np.newaxis,...,np.newaxis]) print(f'Model Prediction: {labels[np.argmax(predictions)]}') And we get that this image is a Sneaker! Model Prediction: Sneaker Takeaway That was an example of how we can start with TensorFlow and CNNs by building a decent model in a few lines of code. The images were on grace-scale (not RGB) but the logic is the same since we expanded the dimensions. We can try other architectures playing with the convolutional kernels, pooling, layers, regularization, optimizers, epochs, batch sizes, learning rates and so on.
https://medium.com/geekculture/get-started-with-tensorflow-2-0-and-cnn-fed15708a373?source=post_internal_links---------2----------------------------
CC-MAIN-2021-25
refinedweb
840
51.75
Details Description Script fragments containing & characters are encoded into & before the script is evaluated. I checked the code from the server side and it is correct, so the problem is on the javascript part. Activity - All - Work Log - History - Activity - Transitions The issue is that the new serialisation code produces wrong results for non javascript elements. I personally think the only viable option simply is to revert to a parsing for the body and a full innerHTML. Everything else does not work out. The bugfix opened another bug. Now deeper elements in replace body and head are ignored entirely. We have to work differently here. Ok the root cause of this problem, and it only can happen in the head replacement code is following. a) Browsers do not allow a direct head replacement. b) Instead the head is more or less generated and then parsed by an xml construct (and if not a direct head replacement is tried). The xml construct parses the code as xml and during this parsing step a deserialize xml is called to get the script text data. This works but it encodes & into amp, now, we do not need that for script tags in most cases, a simple xml.text should suffice which does not encode the &. So I will add the xml.text as fallback if present, this should resolve the issue. The normal update cases are not touched by this issue, hence it has not crawled up so far. The double import was caused by a check for jsf.js which did only executed half the code it should, I now have changed the code accordingly, so that it imports jsf.js only if it is not present in the window namespace (which is basically never unless someone causes such a condition manually) Another thing I noticed, jsf.js is reloaded, this should not happen according to the code. I will investigate into that as well. Ok the example Leo gave me triggering this issue causes an internal error in the javascripts exposing itself as error message in jsf.js. I have yet to debug into this error, but I assume it is the mentioned problem of a script eval failing. This is not a bug. The only time this happens in my testcases here is whenever a innerHTML is issued from the script itself with an & sign. And there the browser simply has this behavior. Normal & are not affected. aka <script> node.innerHTML = "bla & bla" results in bla & bla due to browser behavior regarding innerHTML </script> <script> true && true; </script> will show up in the browser as final result true && true I will investigate this issue sometime next week i now have switched to the parsing code for the content and only revert to the xml code for the attributes parsing
https://issues.apache.org/jira/browse/MYFACES-3321?focusedCommentId=13116422&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-32
refinedweb
469
64.3
not actually to establish a blogging point where individuals can enrich their learns on facilitating and leveraging .NET-related activities most effectively Holy cow, I wrote a book! If you double-click a file for which there is no registered handler, Windows will offer to visit the Web service on shell.windows.com to locate a program that can open it. But where does this information come from, and how can you add your program to the database? Knowledge Base article Q929149, titled Windows File Association System On-Boarding Process, provides step-by-step instructions on how you can add your file extension. If you look at the existing entries on shell.windows.com, most of them have relatively straightforward and neutral descriptions. "This document is a PowerPoint presentation." "This document is a sound file." But there is at least one company that decided to use the file association service for a bit of grandstanding. "Invented by XYZ company and perfected over 15 years, ABC file format lets you capture information from any application, on any computer, and share it with anyone around the world." By the way, if the file association Web service offends you, you can disable it. With exquisite, slow-aged bits handcrafted from only the finest Italian bit-blocks, our prodigious pedigree provides you with a graphic file format that is second to none. When your data is written to disk, do not think of it as simply adding another file to your C:\Users\ directory, think instead of giving birth to a perfect, resplendent piece of Heaven upon this very Earth. I think a more appropriate blurb would be: Bulky as a brontosaurus and as slow as one stuck in a tar pit in winter, this application was forced upon unsuspecting computer and Internet users through clever marketing. Now it's become so entrenched that it's used nearly everywhere, most often where it's not needed, so suck it you worms and download or buy a copy today. Between the choices of: 1. Grandstanding description of a well documented file format with complete and free documentation of every aspect of the file format. 2. To the point description of an undocumented, proprietary file format. I'll choose 1 any day. I know you have no power over this, but still, I'll let that company be a bit pompous, I think they're entitled to it. Pierre, telling *Microsoft* of all people how "free and open" it is is probably a strategic mistake if you're trying to convince people to use it. As Raymond's pointed out, Microsoft got sued for implementing the "free and open" file format, since Adobe is full of asshats. Pick your battles, man. Really, I'm amazed Adobe had enough time to get a lawsuit together, what with all the turning Macromedia products into crap they've been doing. I can't believe I used to think Flash 8 had a bad UI; much like in It's a Wonderful Life, Adobe has now shown me via CS3 that things could have been oh so much worse. But would they sue you for registering a domain in your real name? Sadly, the answer is almost certainly "yes". Eventually you won't be able to walk outside without getting sued. Pierre, I assume you mean the file formats that aren't documented and available in, of all formats, PDF here: Microsoft "saw the light" so to say and has published a lot of their specifications: I think I've never seen that page return anything but "unknown", and it doesn't tell you how to "on-board" it, ensuring that it stays unknown. if you don't like Adobe's bloatware, try out the Foxit reader () - small fast, unobtrusive and "just works". The on-boarding form has this: "State or Province for contact [N/A if placed in Korea]" Anyone know why Korea is mentioned specifically there? "if you don't like..." Alternative viewers for the format don't change the fact it's based on pieces of paper and unsuitable for on-screen viewing. It's fine for stuff you want to print but I wish it would be taken outside and set fire to when it comes to web-based documents which most people view on the screen. Perhaps my point of view is biased because I very rarely print documents. (What's the point when the useful ones go out of date and the others only need to be read once and when you can't search a print-out?) > if you don't like Adobe's bloatware, try out the Foxit reader Or, if you're a Mac user, just double click or hit the space bar. On the topic of file extensions, who decides what a 'doc' file is ? The web service claims it's a MS Word file but there are other applications that use .doc (lots of them). Sure this works for the some well-known file formats, but who needs this service for that ? And even then it fails lots of times. I prefer the *nix tool 'file' that actually analyzes the content of the file to determine what filetype it is. For example: what is a txt file, it's a text file, sure, but what KIND of text file ? Is it DOS-style text, Unix-style text, UTF-8 ? Sure, notepad will try to open that Unix-style text file, but it'll look like crap. Mac's also usually ignore the extension and use filesystem metadata to determine the correct application to use (I think extensions are still used as a fallback) The best part of this is that you can determine on a per-file basis which app should open the file. E.g. if you want to open files for finished projects in a lightweight viewer, just set the viewer as the default and set the heavy-weight editor as the application on the file for your current project. I think both those approaches are a lot better than just using file extensions. Especially trying to execute every file that's named .exe or .com when double clicked is a really bad idea (has been used as an attack vector for trojans in numerous occasions). Is this something that's even seen as an issue at Microsoft or is it just 'the way it is' ? (I can imagine that this is something that can be done as part of the WinFS project) @Aaargh! The point of the webservice is to help the user when the associated application is NOT installed. If you already have it installed it would just load up the default app for the file. Wow, I've been wanting to disable that for years now, but had no idea what to look for. Thanks Raymond! And for anyone else out there who doesn't want to read that rather longwinded article on msdn: Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System] "NoInternetOpenWith"=dword:00000001 hmm I wonder who that company is. Anyone got a PDF might confirm it? ;) @aaargh Uhm, what? You do realize that an extension is essentially a piece of metadata? And if you analyze the file to figure out what type it is, you still need to have some sort of association to open the file. Lets say you figure out a file is a jpeg. What application opens jpegs? As far as who decides what a ".doc" file is? The application decides what extension to give to a file, and the user decides what the default program for opening that extension. I'm not exactly sure what Microsoft does when there is a collision, but as you can see from the .doc example multiple applications can be listed for a file type. Only two companies registered a claim to be able to handle mp3? Wow. I'd have expected every half baked music player under the sun would be trying to get in on that web service action. Marketing departments everywhere must be slipping. I, too, always wanted to disable it for ages as I thought it was completely broken. It never seemed to work for me on any XP box. Surprisingly, the last time i tried to use it on Vista it actually worked. For average users it is probably quite useful It doesn't offend me, it just wastes my time. I have never yet had it return anything useful, and 90% of the time I just want to use Wordpad to see if the file is human-readable. It would be great if it was easier to turn off. > "The point of the webservice is to help the user when the associated application is NOT installed. " Sure, but 'file' works fine for apps you don't have installed. In fact. lots of files it can recognize won't even be useful on the platform it runs on. (e.g. it will recognize a ELF binary and will tell you exactly for which platform is it meant). Also, the metadata in an OS X file doesn't need the actual app to be useful, because it will point you to the correct app. You can see this from the terminal using the 'mdls' command. For example, running 'mdls' on an OmniGraffle file shows, among other things, this line (whitespace removed): kMDItemContentType = "com.omnigroup.omnigraffle.graffle" From there it's easy to find the correct application to open it. It's even more useful than that, it even shows you the *kind* of document you're dealing with. For example, a JPEG will have this 'content type tree' in the metadata: kMDItemContentTypeTree = ( "public.jpeg", "public.image", "public.data", "public.item", "public.content" ) Even if you don't have a JPEG decoder, you can still determine it's an image. > You do realize that an extension is essentially a piece of metadata? Sure, 3 letters, that won't ever cause a collision (yes, you *can* use more, however, almost no one does). Even if you use more, adding proper namespace will cause confusingly long filenames. Plus you can't easily have multiple identifiers like the 'content type tree' above. > Lets say you figure out a file is a jpeg. What application opens jpegs? JPEG's are common, so lots of apps. But if it's a 'weird' file format, like OmniGraffle, I think "com.omnigroup.omnigraffle.graffle" will point you in the direction of the app you need just fine. @chrismcb and ola: Aaargh does actually know what he's talking about. You're missing the point that recognising what a file is and opening it with something are two different actions. IMO a vanilla KDE setup that knows that .doc is a Microsoft Word document (even if there are three files elsewhere in the world that use that extension for something else) is more useful than a vanilla Windows install that doesn't, even though neither can actually open the thing. And as Aaargh (I presume you're named after the castle?) pointed out, the file extension isn't always adequate - such as the case of UTF-16 text files or ones with Unix line breaks, which Windows will associate with Notepad despite it not handling them at all well. Yes, the web helper thing does help this problem a bit, but frankly I'd prefer the system to just know what things are rather than have to go through the myriad of popups about "do you want to use the helper application or select from a list that arbitrarily won't contain the program you want to use?". If it is essential to have it web-based rather than have a local list of common formats, why not have both? Have a bigger dialog that displays the list of local programs _and_ fetches a remote list in the background. "Aaargh does actually know what he's talking about. You're missing the point that recognising what a file is and opening it with something are two different actions." I don't see how that's even slightly relevant to the topic at hand. You find Windows' meta data to be lacking. Not surprising: there's very little meta data in the way of file handling. None the less, if you have applications on your machine that could handle the file then why do you want it to go to the internet? Isn't that exactly at odds with the common complaint that Windows uses too many resources? > "if you have applications on your machine that could handle the file then why do you want it to go to the internet? " The point is that the metadata is an attribute that is stored with the file, and is usually copied with it (While Windows/Linux filesystems usually don't support this kind of metadata, OS X still tries to store it with the files, you've probably seen .DS_Store files on network shares or __MACOSX directories in ZIP files). You don't need to have to have any app installed to be able to recognize the file type, and identify the application that would be needed to open it. My point is that using the file extension to identify the file type (and thus the app) is not a very reliable way of determining the correct application to use, whether it's installed on the system or not) Wow, do people ever actually NOT use the "Select the program from a list" radio button in favor of "Use the Web service to find the appropriate program"? I almost always want some sort of pseudo-text editor to open strange files with. @Peter I didn't miss that point, but Aaargh seems to me. Aargh seems to be implying that windows sucks because it doesn't know what a file is. But unix is infinitely better because some random programs know how to decipher some files. Or Mac is better because it has a little more meta data. The thing is, they are all the same thing. Some are a bit richer than others. But if I come up with a new data type, does "file" know about my data type? I don't know how rich the metadata is on the Mac, but does it point me to a resource to install the file? JPegs are common, but that doesn't help me open the file. I have no freaking clue what "graffle" is, so that doesn't help me either. Having it named "com.omnigroup.omnigraffle.graffle" Doesn't help much. Sure I can search for omnigroup, omnigraffle, graffle. But I can also search for "jpg" Right now the OS pops up a list of common "viewers" and gives you a way to search for more. Should this "search for more" be more automated? That is a design decision. Perhaps as more and more people have broadband that is a better solution. But as it stands now, IF the application is installed on Windows, then the OS knows about the file type. But if the application isn't installed on it, someone needs to figure out what that type is. Should we push this information down to the OS? This is very useful to know, thanks. (Although I must admit that I have never once picked the option to consult the web service.) What seems strange to me is that it looks awfully difficult for open-source organisations to get their strange extensions on the list, seeing as they generally don't have company names or offices. Having the database be aware of things like .ogg or .mkv would be very useful for the people who get confronted with those formats. What I find amusing is that some programs will rename the type of generic files, for example, by changing the type of .JPG files to "ABBCCC Image File" WTF? ABBCCC did not define the JPEG file format, so why do they think it's appropriate to put their name on it? Must be some stupid egotistic marketers.... "...'file' doesn't know about Contoso Accounting Template files." BTW, is that specification available under Microsoft's open spec promise? What I find disturbing is that although the web service seems to recognize a lot of the file types if you use the en-US locale, under the nl-NL locale it recognizes almost nothing! Screw the Dutch (and possible any non-english speaker?) > Having it named "com.omnigroup.omnigraffle.graffle" Doesn't help much. REALLY ? It wouldn't occur to you to try omnigroup.com ? > My point is that using the file extension to identify the file type (and thus the app) is not a very reliable way of determining the correct application to use, whether it's installed on the system or not) How reliable is metadata? The term "volatile" comes to my mind. Interoperability matters. Being able to transfer files between heterogenous systems through archives (tar, zip, 7z...), network file systems (FTP, SMB, NFS...) or file systems on shared media (mainly FAT16 and FAT32) matters. File extensions work for that. Extended attributes & other file system specific metadata don't work. Now, open your HTML file with a pure text editor and save it with another name. Is the file type preserved? If it is, then, the text editor was specially programmed to handle that case. If, for some reason, you need a very reliable way to tag files with a type and exchange these files, don't use file system metadata. File extensions aren't perfect either. For that, store the data AND metadata in the same file: Use the MIME standard. I could try omnigroup.com, but how will I know that omnigroup.com has anything to do with that filetype? And if they do, what program of theirs is going to help me? Consider adobe where they have 4 or 5 big titles each with its own set of file formats. Adobe reader isnt going to help me with flash files, and my photoshop 7 is just about the worst way to view a pdf file even tho it can pull individual pages out of one. Quite honestly if I am using shell.windows.com its because I tried clicking on a document in the hopes that a reader/client would display it. I do not care about omnigroup's or adobe's latest marketing hoopla. I care about easily finding a viewer/client for the specific document. > "I could try omnigroup.com, but how will I know that omnigroup.com has anything to do with that filetype? How do you known that Microsoft has anything to do with .doc ? The namespace will usually give you enough information, but you will probably still need a service like the one this thread is about. Only using this mechanism you could actually expect it to come up with the correct application instead of a best-guess based on a 3 letter extension. > And if they do, what program of theirs is going to help me?" As the namespace com.omnigroup.omnigraffle implies, the correct application is "OmniGraffle". "You don't need to have to have any app installed to be able to recognize the file type, and identify the application that would be needed to open it." You already said above that you need an app to recognize the metadata. So basically, if I'm already using another app to find out which app I want to use then what's all this metadata really buying me? A very slight amount of convenience? So, wait, I got lost here. Does Microsoft suck because it doesn't store enough metadata? Or does Microsoft suck because their version of "file" is online and allows anyone to register their file extensions? Just trying to figure out if the bashes are for not being bloated enough, or for being too open. >What I find amusing is that some programs will rename the type of generic files, for example, by changing the type of .JPG files to "ABBCCC Image File" I hate those things. Or I hate explorer. Both I guess. If an image editing/viewing application is going to associate every image type with itself, the least it can do is differentiate the file types as "ABBCCC JPG Image File" so I can groupe all jpg files in explorer. Likewise, my biggest pet peeve with explorer is the idiotic way it groups files by this "type" and no longer allows me to group by actual file extension. Someone at Microsoft wasn't thinking with that one and obviously no-one at any of the image editing software companies was thinking either (more likely they couldn't care less). While mention "on-boarding" (which is nasty) can I also mention another microsoftism I encountered today which is far far worse? I give you "to surface", as used of the windows 7 jump list. "Jump Lists surface commonly used nouns (destinations) and verbs (tasks) of a program" I think they mean "to present as available functionality", but it hurts my eyes so much I just had to vent my spleen to someone. on Windows Server 2008 (so probably on Vista too), it can be set from Local Group Policy Editor > Computer Configuration > Administrative Templates > System > Internet Communication Management > Internet Communication settings > Turn off Internet File Association service. Oh dear. I think I just surfaced my lunch. @Z: The Group Policy editor can be used to edit this setting on Windows XP (SP2) as well. Simon MacMullen wrote "Only two companies registered a claim to be able to handle mp3? Wow." Think about how often that page is viewed: Every time someone tries to play an MP3-file on a Windows computer that doesn't have software to deal with the format... Not so often. (I don't think this service is targeted to Windows 3 users.) @wound The verb to surface means "to bring to the surface" or to "rise up." In this case the surface is the user interface of the program, it is what the user sees. you are right, surfacing a command is to make the command available to the the user. But it makes it available such that the user SEES the command, it is brought to the surface. Sorry if using English words in a way that is correct makes you barf. This "feature" has never worked because software vendors don't want support it. But I don't care why it doesn't work, just admit its not working and remove it from the OS. It takes too many clicks. And after that it doesn't ever find anything, plus it requires the user to ponder for a few moments about how Windows is hard and annoying to use. @chrismcb Not quite. "Surface", in the sense of "to rise to the surface" is an intransitive verb, which means it cannot be used in the passive voice. It is only transitive in the sense of "to put a surface on something" (e.g. the workmen surface the road.), but since it is the program which adds elements to the jump list, and not the other way around, this usage is incorrect. chrismcb wrote: >So, wait, I got lost here. Does Microsoft suck because it doesn't store enough metadata? MS sucks because they are polishing a turd. The on-line file associator is a good idea; continuing to use the filename to associate with a program is bone-headed. Raymond wrote: >Yeah, that's user-friendly. "Okay, so in order to figure out what application you need to open this file, first run...[snip] You're being deliberately obtuse. Honestly, I barely even consider that to be a solution anyway. How do you know to use this other application - does it show up automatically? If I am skilled to read meta-data then I am probably skilled enough to use and replace "jpeg" with whatever extension I want. But hey, if I could do that then why not provide that feature at my finger tips in an automated fashion. Oh wait... Since I'm french, I use the french version of Windows XP and thought, for years, that this service was utterly useless. Recently, I discovered that the english database contains many file extensions. But, really, the french database does contain almost zero extensions. txt, bmp, wav, zip, avi, wmv, gz, 7z... None of them are listed. So I just discovered that this feature is actually useful for some guys on earth.
http://blogs.msdn.com/oldnewthing/archive/2009/01/13/9311703.aspx
crawl-002
refinedweb
4,100
72.26
Array operations in C – Part 2 The next set of array operations are: - Insertion - Deletion - Searching - Merging - Insertion of an element into the array: - Insertion of an element in the array, could either be at the start , at the end or anywhere in between as well. - We take the location at which the user wants to insert the element into the array. - Next, we check if the position entered is valid or not. For the user the position would start from number 1. Thus in terms of array index, actual array index position is position – 1 - If the position is invalid same is communicated to the user and program is terminated. - The position is invalid if position is < 1 i.e. less than starting of array and position > n+1 , i.e. if your array has 4 elements; the user might want to insert element at 4th position which is nth position, else also insert it as the n+1th element i.e. 5th element or after the current arrays end. - If position is valid, the element is inserted at required location and resultant array is displayed. Code: #include <stdio.h> int main() { int array[100], position, i, n, value; printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter array elements:\n", n); for (i = 0; i < n; i++) scanf("%d", &array[i]); printf("Enter the location where you wish to insert an element\n"); scanf("%d", &position); if(position > n+1 || position < 1) { printf("The position entered is invalid\n"); } else { printf("Enter the value to insert\n"); scanf("%d", &value); for (i = n - 1; i >= position - 1; i--) array[i+1] = array[i]; array[position-1] = value; //inserting value at the required location printf("Resultant array is:\n"); for (i = 0; i <= n; i++) printf("%d\n", array[i]); } return 0; } Output: Case 1: Insertion location valid Enter number of elements in array 6 Enter array elements: 12 13 14 15 16 17 Enter the location where you wish to insert an element 3 Enter the value to insert 20 Resultant array is: 12 13 20 14 15 16 17 Case 2: Insertion location is invalid Enter number of elements in array 4 Enter array elements: 10 11 12 13 Enter the location where you wish to insert an element 6 The position entered is invalid Deletion of an element from the array: - For deletion of an element from the array, we need to accept the location from which user wishes to delete the element. - When the location is entered by user, we store it in a variable – position. - For user location starts from position : 1. However array index starts from 0. Hence, when we delete the element we need to delete element present at location = position -1. - What we essentially do is, shift the element next to the element to be deleted to the location = position -1, i.e. the next element is placed in position of deleted element and so on we keep shifting the remaining elements by one position to the left. - If an invalid location is entered, deletion is not possible an the same is conveyed to the user. Code: #include <stdio.h> int main() { int array[100], position, i, n, num; printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter array elements:\n"); for (i = 0; i < n; i++) scanf("%d", &array[i]); printf("Enter the location from where you wish to delete the element:\n"); scanf("%d", &position); num = array[position-1]; if (position >= n+1 || position < 0) /*n+1, since user will count element as position 1 onwards. Internally though indexing starts from 0, which user would not know.*/ printf("Deletion not possible as entered location is invalid.\n"); else { for (i = position - 1; i < n - 1; i++) //since array index starts from 0; thus position in terms of array index is position-1 array[i] = array[i+1]; printf("Resultant array after deletion of element %d from location %d:\n", num, position); for (i = 0; i < n - 1; i++) printf("%d\n", array[i]); } return 0; } Output: Case 1: Entered location is valid Enter number of elements in array 5 Enter array elements: 14 15 16 17 18 Enter the location from where you wish to delete the element: 3 Resultant array after deletion of element 16 from location 3: 14 15 17 18 Case 2: Entered location is invalid Enter number of elements in array 5 Enter array elements: 14 15 16 17 18 Enter the location from where you wish to delete the element: 6 Deletion not possible as entered location is invalid. - Searching element of an array: - Searching an element of an array is to check if a user entered element is present in the array or not. If present we display the position at which the element was found in the array. - There are various searching techniques that can be used to find an array element. - We are going to learn to implement the same using Linear Search. - Linear search is not efficient as it scans for each element sequentially, however it is the easiest to understand and implement for beginners. Approach: - We accept the array input from user. - The user will enter the element that needs to be searched in the array. - We scan the entire array sequentially to search for entered element ‘num‘. - On discovering the element in the array at location i, we display it to the user. - If the element occurs at more than one place as well, the search continues until end of array is reached. - Once end of array is reached, loop is exited. - If even after scanning entire array element is not found, ( i==n) then same is conveyed to user. Code: #include <stdio.h> int main() { int array[100], num, i, n; printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter array elements: \n"); for (i = 0; i < n; i++) scanf("%d", &array[i]); printf("Enter a number to search\n"); scanf("%d", &num); for (i = 0; i < n; i++) { if (array[i] == num) /* When required element is found */ { printf("The element: %d is present at location %d.\n", num, i+1); if(i == n-1) //if end of array then exit search break; } } if (i == n) printf("The element %d is not present in the array.\n", num); return 0; } Output: Case 1: Element present in array Enter number of elements in array 10 Enter array elements: 10 20 30 40 50 60 20 10 30 10 Enter a number to search 10 The element: 10 is present at location 1. The element: 10 is present at location 8. The element: 10 is present at location 10. Case 2: Element not present in array Enter number of elements in array 4 Enter array elements: 10 20 30 50 Enter a number to search 40 The element 40 is not present in the array. - Merging of two arrays: - Two arrays are taken as input from the user in order to merge them into a resultant array ‘res‘. - The arrays can be sorted or unsorted. - You can either after taking the input from the user, sort the array else after merging sort the array. - In our case, we first merge the array and then sort them. - For sorting, we use the basic bubble sort technique to sort the array in ascending order as previously seen in sorting an array program. - Since in our case, we sort the array post merging, initially you can simply save elements of arr1 and arr2 into result in the entered order itself. - However, we have written the code for merge considering that if the array input by user is already sorted then the merge function alone would suffice the need. - The function, compares the elements of the two arrays and inserts the elements in the ascending order into res array. - Since, we do not know if user will always enter a sorted array, we sort the resultant array res post merging as well. Code: #include<stdio.h> void merge(int arr1[20], int arr2[20], int n1, int n2) //merging arrays { int i, j, k; int res[40]; i = 0; j = 0; k = 0; // Merging starts while (i < n1 && j < n2) { if (arr1[i] <= arr2[j]) { res[k] = arr1[i]; i++; k++; } else { res[k] = arr2[j]; k++; j++; } } /* Some elements in array 'arr1' are still remaining where as array 'arr2' is exhausted */ while (i < n1) { res[k] = arr1[i]; i++; k++; } /* Some elements in array 'arr2' are still remaining where as array 'arr1' is exhausted */ while (j < n2) { res[k] = arr2[j]; k++; j++; } sort(res, (n1+n2)); //Displaying elements of array 'res' printf("\nMerged array is :"); for (i = 0; i < n1 + n2; i++) printf("\n%d", res[i]); } void sort(int arr[20], int n) //to sort the resultant array { int i, j, swap; for (i = 0 ; i < n - 1; i++) { for (j= 0 ; j < n - i - 1; j++) { if (arr[j] > arr[j+1]) /* For decreasing order use < */ { swap = arr[j]; arr[j] = arr[j+1]; arr[j+1] = swap; } } } } int main() { int arr1[20], arr2[20]; int i, n1, n2; printf("Enter no of elements in 1st array :\n"); scanf("%d", &n1); printf("Enter elements of 1st array : \n"); for (i = 0; i < n1; i++) { scanf("%d", &arr1[i]); } printf("\nEnter no of elements in 2nd array :\n"); scanf("%d", &n2); printf("Enter elements of 2nd array : \n"); for (i = 0; i < n2; i++) { scanf("%d", &arr2[i]); } merge(arr1, arr2, n1, n2); return 0; } Output: Enter no of elements in 1st array : 4 Enter elements of 1st array : 96 54 32 174 Enter no of elements in 2nd array : 5 Enter elements of 2nd array : 20 35 201 11 4 Merged array is : 4 11 20 32 35 54 96 174 201 Report Error/ Suggestion
https://www.studymite.com/blog/operation-on-arrays-in-c-2/?utm_source=related_posts&utm_medium=related_posts
CC-MAIN-2021-39
refinedweb
1,648
50.8
Pickle isn't slow, it's a protocol This work is supported by Anaconda Inc tl;dr: Pickle isn’t slow, it’s a protocol. Protocols are important for ecosystems. A recent Dask issue showed that using Dask with PyTorch was slow because sending PyTorch models between Dask workers took a long time (Dask GitHub issue).. We could have fixed this in Dask by special-casing PyTorch models (Dask has it’s own optional serialization system for performance), but being good ecosystem citizens, we decided to raise the performance problem in an issue upstream (PyTorch Github issue). This resulted in a five-line-fix to PyTorch that turned a 1-50 MB/s serialization bandwidth into a 1 GB/s bandwidth, which is more than fast enough for many use cases (PR to PyTorch). def __reduce__(self): - return type(self), (self.tolist(),) + b = io.BytesIO() + torch.save(self, b) + return (_load_from_bytes, (b.getvalue(),)) +def _load_from_bytes(b): + return torch.load(io.BytesIO(b)) Thanks to the PyTorch maintainers this problem was solved pretty easily. PyTorch tensors and models now serialize efficiently in Dask or in any other Python library that might want to use them in distributed systems like PySpark, IPython parallel, Ray, or anything else without having to add special-case code or do anything special. We didn’t solve a Dask problem, we solved an ecosystem problem. However before we solved this problem we discussed things a bit. This comment stuck with me: This comment contains two beliefs that are both very common, and that I find somewhat counter-productive: - Pickle is slow - You should use our specialized methods instead I’m sort of picking on the PyTorch maintainers here a bit (sorry!) but I’ve found that they’re quite widespread, so I’d like to address them here. Pickle is slow Pickle is not slow. Pickle is a protocol. We implement pickle. If it’s slow then it is our fault, not Pickle’s. To be clear, there are many reasons not to use Pickle. - It’s not cross-language - It’s not very easy to parse - It doesn’t provide random access - It’s insecure - etc.. So you shouldn’t store your data or create public services using Pickle, but for things like moving data on a wire it’s a great default choice if you’re moving strictly from Python processes to Python processes in a trusted and uniform environment. It’s great because it’s as fast as you can make it (up a a memory copy) and other libraries in the ecosystem can use it without needing to special case your code into theirs. This is the change we did for PyTorch. def __reduce__(self): - return type(self), (self.tolist(),) + b = io.BytesIO() + torch.save(self, b) + return (_load_from_bytes, (b.getvalue(),)) +def _load_from_bytes(b): + return torch.load(io.BytesIO(b)) The slow part wasn’t Pickle, it was the .tolist() call within __reduce__. As a reminder, you can implement the pickle protocol by providing the __reduce__ method on your class. The __reduce__ function returns a loading function and sufficient arguments to reconstitute your object. Here we used torch’s existing save/load functions to create a bytestring that we could pass around. Just use our specialized option. Hard for users.. Hard for other libraries Other libraries that need to interact definitely. Sometimes Specialized Options are Appropriate There are: Speed: Sharing:. blog comments powered by Disqus
http://matthewrocklin.com/blog/work/2018/07/23/protocols-pickle
CC-MAIN-2020-05
refinedweb
572
66.23
Hi, I am really desperate at this point! I am getting many errors, related to show.html.erb in the app\views\stories\ folder. They all relate to: NoMethodError in Stories#show undefined method `votes' for nil:NilClass Extracted source (around line #3): 1: I posted a thread before, in which I mentioned that I got: undefined method `names' for nil:NilClass also present in the same file...I am losing my mind..Some help please!!! assuming that you have a object named 'story' in your DB, you need to check your story controller and check if there is a appropriate method to call that object. Thanks ReggieB! I shall try this out! The error indicate that @story is currently a nil object. The nil Object is of the class NilClass, and this doesn't have a names method. The reason you are getting this is because @story is not being loaded with a Story object elsewhere in your code. For example: because @story is not being assigned in your controller. This may be because the code that assigns it is absent, or is not working as you expect. For example, there should be something like this in the controller: def show @story = Story.find(params[:id]) end Just in case someone else comes across this, I had the same error. My solution may help you. The instruction on p212 confused me (the code example is actually an excerpt). My mistake was to replace all the code instead of appending it. Try checking app/models/story.rb has the following code... class Story < ActiveRecord::Base validates_presence_of :name, :link has_many :votes def to_param "#{id}-#{name.gsub(/\\W/, '-').downcase}" end end Hope this helps! C.
http://community.sitepoint.com/t/problems-with-show-html-erb/74326
CC-MAIN-2014-52
refinedweb
283
67.76
This page is based with thanks on the wiki page on subclassing by Pierre Gerard-Marchant -. Subclassing ndarray is relatively simple, but you will need to understand some behavior of ndarrays to understand some minor complications to subclassing. There are examples at the bottom of the page, but you will probably want to read the background to understand why subclassing works as it does. The creation of ndarrays is complicated by the need to return views of ndarrays, that are also ndarrays. For example: >>> import numpy as np >>> arr = np.zeros((3,)) >>> type(arr) <type 'numpy.ndarray'> >>> v = arr[1:] >>> type(v) <type 'numpy.ndarray'> >>> v is arr False So, when we take a view (here a slice) from the ndarray, we return a new ndarray, that points to the data in the original. When we subclass ndarray, taking a view (such as a slice) needs to return an object of our own class. There is machinery to do this, but it is this machinery that makes subclassing slightly non-standard. To allow subclassing, and views of subclasses, ndarray uses the ndarray __new__ method for the main work of object initialization, rather then the more usual __init__ method. __new__ is a standard python method, and, if present, is called before __init__ when we create a class instance. Consider the following: class C(object): def __new__(cls, *args): print 'Args in __new__:', args return object.__new__(cls, *args) def __init__(self, *args): print 'Args in __init__:', args C('hello') The code gives the following output: cls is: <class '__main__.C'> Args in __new__: ('hello',) self is : <__main__.C object at 0xb7dc720c> C(object): def __new__(cls, *args): print 'cls is:', cls print 'Args in __new__:', args return object.__new__(cls, *args) def __init__(self, *args): print 'self is :', self print 'Args in __init__:', args class D(C): def __new__(cls, *args): print 'D cls is:', cls print 'D args in __new__:', args return C.__new__(C, *args) def __init__(self, *args): print 'D self is :', self print 'D args in __init__:', args D('hello') which gives: D cls is: <class '__main__.D'> D args in __new__: ('hello',) cls is: <class '__main__.C'> Args in __new__: ('hello',)). So, when creating a new view object of our subclass, we need to be able to set any extra attributes from the original object of our class. This is the role of the __array_finalize__ method of ndarray. __array_finalize__ is called from within the ndarray machinery, each time we create an ndarray of our own class, and passes in the new view object, created as above, as well as the old object from which the view has been taken. In it we can take any attributes from the old object and put then into the new view object, or do any other related processing. Now we are ready for a simple example. import numpy as np class InfoArray(np.ndarray): def __new__(subtype, shape, dtype=float, buffer=None, offset=0, strides=None, order=None, info=None): # Create the ndarray instance of our type, given the usual # input arguments. This will call the standard ndarray # constructor, but return an object of our type obj = np.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides, order) # add the new attribute to the created instance obj.info = info # Finally, we must return the newly created object: return obj def __array_finalize__(self,obj): # reset the attribute from passed original object self.info = getattr(obj, 'info', None) # We do not need to return anything obj = InfoArray(shape=(3,), info='information') print type(obj) print obj.info v = obj[1:] print type(v) print v.info which gives: <class '__main__.InfoArray'> information <class '__main__.InfoArray'> information This class isn’t very useful, because it has the same constructor as the bare ndarray object, including passing in buffers and shapes and so on. We would probably prefer to be able to take an already formed ndarray from the usual numpy calls to np.array and return an object. Here is a class (with thanks to Pierre GM for the original example), that takes array): # reset the attribute from passed original object self.info = getattr(obj, 'info', None) # We do not need to return anything arr = np.arange(5) obj = RealisticInfoArray(arr, info='information') print type(obj) print obj.info v = obj[1:] print type(v) print v.info which gives: <class '__main__.RealisticInfoArray'> information <class '__main__.RealisticInfoArray'> information Let’s say you have an instance obj of your new subclass, RealisticInfoArray, and you pass it into a ufunc with another array: arr = np.arange(5) ret = np.multiply.outer(arr, obj) When a numpy ufunc is called on a subclass of ndarray, the __array_wrap__ method is called to transform the result into a new instance of the subclass. By default, __array_wrap__ will call __array_finalize__, and the attributes will be inherited. By defining a specific __array_wrap__ method for our subclass, we can tweak the output. The __array_wrap__ method requires one argument, the object on which the ufunc is applied, and an optional parameter context. This parameter is returned by some ufuncs as a 3-element tuple: (name of the ufunc, argument of the ufunc, domain of the ufunc). See the masked array subclass for an implementation. One of the problems that ndarray solves is that of memory ownership of ndarrays and their views. Consider the case where we have created an ndarray, arr and then taken a view with v = arr[1:]. If we then do del v, we need to make sure that the del does not delete the memory pointed to by the view, because we still need it for the original arr object. Numpy therefore keeps track of where the data came from for a particular array or view, with the base attribute: import numpy as np # A normal ndarray, that owns its own data arr = np.zeros((4,)) # In this case, base is None assert arr.base is None # We take a view v1 = arr[1:] # base now points to the array that it derived from assert v1.base is arr # Take a view of a view v2 = v1[1:] # base points to the view it derived from assert v2.base is v1 The assertions all succeed in this case..
http://docs.scipy.org/doc/numpy-1.3.x/user/basics.subclassing.html
CC-MAIN-2016-30
refinedweb
1,039
63.59
08-31-2016 12:07 PM Dear all, I'm trying to fit a dataset with proc model and ordinary differential equations, but somehow it does not work. SAS complains that I don't have the values A1 and A2 in the dataset, but they can't be in the dataset. Any ideas? The dataset and the code is attached below. Many thanks in advance. Thorsten ata step01; INPUT time conc; datalines; 0.1 1.50 0.2 3.20 0.4 4.30 0.6 5.10 0.8 5.40 1 5.20 1.2 5.00 1.4 4.80 2 4.00 3 2.50 4 1.50 5 1.00 6 0.62 7 0.40 8 0.25 10 0.10 run; proc model data=step01; ENDOGENOUS A1 400 A2 0 ; dert.A1 = -ka * A1; dert.A2 = ka * A1 - (CL/V2)*A2; CONC=A2/V2; FIT CONC start=(KA 2.5 CL 20 V2 50) ; run; quit; 09-01-2016 11:00 AM I got what look like satisfactory results by changing the ENDOGENOUS statement to a PARAMETERS statement. I'm pretty sure that SAS expects endogenous variables to be part of the input dataset here, so by shifting to PARAMETERS, it fits those at t=0. Steve Denham 09-05-2016 03:59 AM Dear Steve, many thanks. It works perfectly. Does anyone know how I can add a second input/pulse (i.e. a drug dosing) to the first differential equation after a certain time, e.g. 12 hours? How can I integrate this into a dataset? Many thanks Thorsten 09-21-2016 04:19 PM Thorsten, I was surprised to see that Steve's suggestion to change the ENDO statement into a PARMS statement does allow PROC MODEL to estimate this one compartment model; however, I would not recommend this approach as it exploits an unintended side effect in PROC MODEL and may not work in the future. The more standard way of estimating this model would be to include the unobserved values, a1 and a2, in the data set: data step02; set step01; a1 = .; a2 = .; run; proc model data=step02; endo a1 400 a2 0; ... I would also like to point out that neither of these approaches may be exactly what you want. Presumably, in your model the dose is administered at time = 0. In your code the STEP01 data set's first observation is at time=0.1. That means when PROC MODEL integrates these ODEs it uses a1=400, and a2=0 as the initial conditions at time=0.1. To set the initial conditions a1=400, and a2=0 at time=0 you should add an extra observation with time=0 and conc=0 to the top of your data set. Regarding adding a pulse, or bolus, dose to the first equation you could use code like the following: dert.A1 = -ka * A1 + dose*dirac(time - tbolus); after first defining a dirac function using PRC FCMP: proc fcmp outlib=work.funcs.f; function dirac(args[*]) varargs; x = args[1]; if dim (args) = 1 then delta = 1e-6; else delta = args[2]; if abs(x) < delta then f = (delta - abs(x))/(delta*delta); else f = 0; return (f); endsub; run; options cmplib=funcs; You would need to define the TBOLUS, and DOSE variables either in your data set, or your model program. Marc 09-26-2016 01:25 PM Sweet answer to use FCMP to come up with a Dirac function for a pulse input. That's something I wish I had known about $) years ago (of course, there was no PROC MODEL then, let alone PROC FCMP). Steve Denham
https://communities.sas.com/t5/SAS-Forecasting-and-Econometrics/Parameter-estimation-with-proc-model-and-ODEs/td-p/295556?nobounce
CC-MAIN-2017-34
refinedweb
612
82.44
hey all, I'm trying to integrate sqlalchemy into my project build rather than install it separate. so in my project i have "<project_dir>/lib/sqlalchemy/*" i put a the __init__.py in "lib" but when i try to do from lib.sqlalchemy import * i get: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /home/dankles/workspace/ac/src/AniChou/<ipython console> in <module>() /home/dankles/workspace/ac/src/AniChou/lib/sqlalchemy/__init__.py in <module>() 8 import sys 9 ---> 10 import sqlalchemy.exc as exceptions 11 sys.modules = exceptions 12 ImportError: No module named sqlalchemy.exc How ever if I'm in the "lib" dir and type: from sqlalchemy import * I get no such problem this is probably a newb question, but I'm cunfused and don't know what to do... :rolleyes:
https://www.daniweb.com/programming/software-development/threads/190867/load-modules-from-subdirectories-of-current-project
CC-MAIN-2017-43
refinedweb
132
66.44
[Solved] Is it possible to read file from resources files with QSettings? @#include "mainwindow.h" #include "ui_mainwindow.h" #include <QSettings> #include <QDebug> #include <QResource> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QSettings * qsettings = new QSettings(":/config",QSettings::IniFormat); QString status = qsettings->value("General/preview","").toString(); qDebug() << status; QResource::registerResource("res.rcc"); QSettings settings1(":/config.ini"); QString sColor1 = settings1.value("preview").toString(); //File has "success=red", sColor reads to "red" QResource::unregisterResource("res.rcc"); qDebug() << sColor1; } MainWindow::~MainWindow() { delete ui; } @ !! If there no way so what i can use in qt for read file from resources and then parse it by keys like in QSettings? - SGaist Lifetime Qt Champion Hi and welcome to devnet, Might be a silly question but do you also want to save these settings later ? If so you can't do it through Qt's resources system since it's read-only. However what is commonly done when you have a default ini file like that is to copy it to the appropriate place the first time the program is started (using QStandardPaths to retrieve that place) and then use it from there. Hope it helps Hi, thank you! Seems that problem is in qmake because everyting ok when i launch it. - SGaist Lifetime Qt Champion The file wasn't compiled ? Sorry, i think that i said not clearly. I mean that build or run don't help. I don't know the full sequencing for getting this problem again but qmake solve this. This may be same like with adding QDialog class to project and after getting unresolved linking error until launch qmake.
https://forum.qt.io/topic/49458/solved-is-it-possible-to-read-file-from-resources-files-with-qsettings
CC-MAIN-2018-26
refinedweb
273
58.79
You and family law. A short guide - Timothy Baldwin - 2 years ago - Views: Transcription 1 You and family law 2 1 Contents About this booklet...2 Separation and divorce...4 Family violence...9 Family dispute resolution...13 Children...17 Dividing your property...22 Where to get help...27 Disclaimer Legal Aid Queensland believes the information provided in this guide is accurate as at February 2009 guide has been adapted from the Victoria Legal Aid guide You and family law a short guide. You and family law 3 2 About this booklet Who is this booklet for? This booklet is for anyone who needs basic information on family law. It is for people who are thinking about separation or who have experienced separation. Family law covers all aspects of family relationships breakdown, divorce, care of children, financial support of children and former partners, and property division. You will also find information here on ways to try to sort out your arrangements without having to go to court, and where to go for help. What does the law say? In Australia the law does not look at whose fault it is that the relationship broke down. The law s main concern is what is best for the children. Where possible, children should have a relationship with each parent and other important people in their lives. There is no rule that sets out where the children live and how much time the children spend with each parent. Each family is different. In dividing property the law looks at everything the couple owns and earns, and then divides these according to what it considers fair. It is not about who is right and who is wrong. It is about making arrangements for the future. The law changes all the time. To check for changes you can: call the Legal Aid Queensland Client Information Service visit Legal Aid Queensland s website Legal Aid Queensland 4 3 Where can I get help? Any relationship breakdown is stressful. It can be especially hard if there are children involved. You might also find it difficult to cope financially. Making decisions at this time is not easy, but there is help available. Getting legal advice and other support can help you understand what choices you have. Talking to a lawyer does not mean you have to go to court, although lawyers can help you do this if you need to. If possible, try and talk to your former partner about making arrangements for the future. If you can agree on a plan this can be better for everyone. You can get help to make an agreement from Legal Aid, a family relationship centre or other dispute resolution service. They can also refer you to services that can help your relationship with your former partner. If you feel worried for your safety, intimidated, or feel that you cannot make decisions equally with your former partner you can get help. See the Family violence chapter on page 9. Interpreters can be arranged for legal advice, family dispute resolution or court. See the Where to get help chapter on page 27. Contact Legal Aid Queensland: To speak to a client information officer call Also see the Where to get help chapter on page 27. You can get more detailed information about family law from our website You can also download You and family law a complete guide from our website. You and family law 5 4 Separation and divorce What is separation? Separation is when you stop living together as a couple, even if you are still living in the same house. You do not need to get permission or your partner s agreement. If you are new to Australia or are worried about your residency, get legal help. How do I get separated? To get separated you do not have to apply to a court or government organisation, or fill in any forms. You will not get a certificate saying you are separated. You will need to: Tell organisations such as Centrelink, the Child Support Agency and Medicare that you are separated. Make proper arrangements for any children involved, and tell your family and friends. Sort out your financial affairs work out how debts and loans will be paid, whether you have joint bank accounts, what your superannuation or insurance entitlements are and change your Will. Tell your banks, superannuation and insurance companies of your separation too. This will help if you need to prove you are separated. Also get legal help. See the Dividing your property chapter on page 22. Does one of us have to leave the family home? It is your decision if you want to leave. Or your partner may have left you. If your partner has used violence or threats, you may feel you have no choice. If you are in this situation you can get help. Legal Aid Queensland 6 5 You can also get help to apply for a domestic violence protection order at a magistrates court. You can ask for an order that stops your former partner from coming to where you live or work. Orders can also protect children. The Family Law Courts can also make orders about who can stay in the home. Get legal and other help. See the Family violence chapter on page 9. If you have a domestic violence protection order against you and it says you must not be at your home, then you must leave. You should obey the order and get legal and other help. Do I lose my rights if I leave? If you do leave the family home, you will not lose your rights to the house or your things. You may also be able to return at a later time. It is best to think about your and your children s safety first, and also get legal help. See the Family violence chapter on page 9. What should I take if I leave? If you do need to leave your home urgently, it is best to take all your legal and financial papers with you, such as: birth and other certificates Wills passports visas bank and cheque books personal things you are worried about leaving behind things you may need for yourself and your children if they are going with you. You and family law 7 6 Can I take the children with me? Yes, but remember the law says children have a right to a relationship with each parent. If the move will make it more difficult for the other parent to see the children, you need to try to get the other parent s agreement first. If possible, get legal advice, even if you have your former partner s agreement. If you feel you or the children are at risk of being hurt, get help quickly. In an emergency call the police on 000. A domestic violence crisis service can also help you. Get legal help as soon as possible. See the Where to get help chapter on page 27. What is divorce? Divorce is the official ending of your marriage. Your partner does not have to agree, and the law does not look at whose fault it is. Do I have to get a divorce? No. However, if you or your former partner wants to remarry, you must be divorced. You can make arrangements for children and property without being divorced. If possible try to make these arrangements soon after separation. Tell organisations like Centrelink, banks, superannuation and insurance companies. If you stay married this affects your rights and obligations with finances and your Will. See How do I get separated? on page 4. Get legal and financial help, particularly before signing an agreement. If you do get a divorce, you must apply to the court for a property settlement within a certain time. Get legal advice. See the Dividing your property chapter on page 22. Legal Aid Queensland 8 7 How do I get a divorce? You can apply for a divorce at the Federal Magistrates Court. You or your partner must be an Australian citizen or resident. You can still apply for a divorce if you were married overseas, or if you do not know where your partner is, as long as you live in Australia. If you are concerned your marriage might not be legal, get legal help. Contact the court for more information and a divorce kit, with the forms you need. There is a fee for applying for a divorce, but in some circumstances you may not have to pay. Do I need a lawyer to get a divorce? Most people apply without using a lawyer. You can decide if you want a lawyer to help you. You may need legal help to sort out arrangements for children or property. When can I get a divorce? Your marriage must have broken down, with no chance of you getting back together. You must be separated from your partner for at least 12 months and one day. If you were married for less than two years extra conditions apply. You can be living in the same house, as long as you live separate lives. You may have to prove this. If you are concerned your marriage might not be legal, get legal help. You and family law 9 8 What if there are children of the marriage? The court will want to make sure proper arrangements have been made for the children, before allowing the divorce. See the Children chapter on page 17. What happens if we get back together? You can become a couple again for up to three months in one period without affecting the 12-month separation period. How long does it take? Allow several months for the divorce to become final. If your situation is complicated, it may take longer. Legal Aid Queensland 10 9 Family violence What is family violence? Family (domestic) violence is any behaviour between family members that causes fear. It can also include stalking. This includes: threats to injure you or any children or damage your property physical violence (including violence that does not cause actual injury, for example, pushing, shoving, holding down) damage to property (including animals) indecent behaviour, for example, coercive sexual behaviour, forced sexual intercourse intimidation and harassment, which may include: persistent phone calls verbal abuse stalking financial abuse, for example, refusing to provide money for food and necessities social abuse, for example, isolating a person from family and friends psychological abuse, for example, constant put downs. No one has the right to hurt or threaten another person. These laws protect everyone who lives in Australia. If you are on a visa and there is family violence, get legal help immediately. Violent behaviour is against the law and you can take action to stop it. Help is available. You and family law 11 10 What can I do if there is family violence? If there is violence or you have been threatened, get help from the police. If you are at immediate risk of harm get help from the police immediately. The children must also be protected from physical and psychological harm. This includes seeing family violence as well as being hurt themselves. You can contact specialist family violence services to help you and the children work out a plan to leave the relationship safely. You can call DV Connect on , 24 hours a day, seven days a week. Legal Aid Queensland, a family relationship centre or the Family Relationship Advice Line can refer you to other specialist family violence services in your area. See the Where to get help chapter on page 27. How do I get a protection order? You can apply for a domestic violence protection order in the magistrates court yourself or get someone to help you such as the police, a lawyer, friend or welfare worker. Legal aid is available for making applications for protection orders. If you are applying for a protection order you are called the aggrieved and the person you want the order against is called the respondent. A domestic violence protection order can: restrict or prohibit the respondent from contacting you restrict or prohibit the respondent contacting your relatives and friends restrict the respondent s contact with children prohibit the respondent from having a weapon remove the respondent from your home if you have been living together (an ouster order). Legal Aid Queensland 12 11 To apply for a domestic violence protection order your relationship with the respondent must be one of the following: spouse or former spouse de facto partner or former de facto partner (including a same-sex de facto partner) you are both parents of the same child (including an unborn child) you are relatives by blood or marriage: this can include an extended definition of relative used by some cultural groups such as people from Aboriginal and Torres Strait Islander backgrounds this does not include children under 18 you are in an intimate personal relationship an intimate personal relationship is: an engagement to be married a dating relationship where your lives are or were enmeshed such that the actions of one affects the actions or life of the other whether or not there is a sexual relationship informal care relationships where one person is dependent upon another who helps them with an activity of daily living. What if the order is broken? Breaking a protection order is against the law. If the other person breaks an order call the police. Can I change (vary) or get rid of (revoke) the domestic violence protection order? You can apply to vary or revoke the order (whether you are the applicant or the respondent), but if the police have taken out the order, they can oppose this. You and family law 13 12 What if a domestic violence protection order has been taken out against me? Do not break the order, even if you do not agree with it. Read it carefully. For example, you may be able to stay in the home, but ordered to stop harassing, hurting or threatening the other person. You must go to court an order can be made even if you do not go. Get legal help. The effects of an order are serious. Get support from family, friends or a support service. You can get a free factsheet about responding to a protection order from Legal Aid Queensland by calling or ordering online at How do orders affect contact with the children? If a protection order is made against a parent, they may still be able to have contact with their children. The protection order may allow them to see the children under a family law parenting order, or if the parents agree visits should happen. Some protection orders can change family law parenting orders about time spent with children. Get legal help to work out your options for sorting out how visits might work. See the Children chapter on page 17. If you feel the children are at risk of physical or psychological harm from seeing or communicating with their other parent, get legal help and other support quickly. Legal Aid Queensland 14 13 Family dispute resolution What is family dispute resolution? Family dispute resolution means trying to sort out your family arrangements rather than going to court. Often this is done informally in the community using family or other people to try and sort out arrangements. The term dispute resolution describes different ways people try to come to an agreement, including negotiation, counselling, mediation and arbitration. The people who offer these services are independent professionals. They are trained to help people sort through their problems and try to reach agreement. Family dispute resolution may or may not be confidential. Always ask. When can I try family dispute resolution? You can try family dispute resolution at any stage, even before separation or after a court case has started. Dispute resolution helps people sort through their problems and try to reach agreement. You and family law 15 14 Do I have to go to family dispute resolution? If you want court orders about children (parenting orders), you usually have to try family dispute resolution first. The court will tell you how to do this. If you want court orders about property, the court may get you to try family dispute resolution too. You need to prove to the court you have tried family dispute resolution, or that it is not suitable in your situation, for example, if there is family violence. You may need a certificate from the family dispute resolution service that says this. You can also apply directly to the court without a certificate if there has been family violence, child abuse or in urgent situations. Get legal advice. Going to family dispute resolution does not mean you have to come to an agreement. Do not feel forced into signing an agreement. You can still get legal help to make decisions. For example, you can get legal advice about what an agreement means before signing it. If we make an agreement, is this legally enforceable? You can make an agreement legally enforceable by asking the court to make it a consent order. Get legal advice on what the agreement means. If you make a parenting plan after you already have court orders, your parenting plan must be followed in the areas where it is different from the orders, unless the court says not to. See the Where to get help chapter on page 27. Legal Aid Queensland 16 15 What if there is family violence? Tell the service if you are worried about your safety. Family dispute resolution services take family violence very seriously. They may only take on cases involving family violence if certain conditions are met. For example, there must be no domestic violence protection order that stops each person being involved in dispute resolution or counselling. They may be able to do conciliation or family dispute resolution with each person in a separate room or building, or over the phone. What if my former partner refuses to go? Family dispute resolution cannot work unless each person involved agrees. If one person refuses to go, you may need the court to sort out your dispute. You will need to explain to the court that you have asked for family dispute resolution, but that the other person refused. If you are applying for a parenting order, the family dispute resolution practitioner can give you a certificate that says this. What if we try and it does not work out? If you have tried family dispute resolution and it has not worked you then have the option of going to court. If the other parent has applied to the court, you must be notified and you must go to court if you can. If you cannot go to court on a certain day, let the court know and get legal help. Courts are not attached to the government, police or any other agency. Most cases are open to the public, unless the court says otherwise. They hear from each person involved and then make a decision. For more information on what going to court means, contact Legal Aid Queensland and the courts. You and family law 17 16 What does family dispute resolution cost? Some dispute resolution services are free. Others charge different rates depending on your financial situation. Contact the service directly and ask how much they charge. How do I find out where family dispute resolution is offered? Call the Family Relationship Advice Line on or visit to find a family relationship centre or other dispute resolution service. Organisations that offer legal advice and other help can also refer you. More information on family law can be downloaded from the Legal information area of our website Anyone important in the child s life can be included in a parenting plan. Legal Aid Queensland 18 17 Children What is the best way to sort out arrangements for the children once we have separated? If possible, try to come to an agreement with your former partner. If you can agree, then write this down. This can form a parenting plan. Get legal help to work out a plan. Grandparents, relatives or anyone important in the children s life can be included in a parenting plan. Legal Aid, a family relationship centre or family dispute resolution service might be able to help. See the Where to get help chapter on page 27. A parenting plan will not be recognised if it was made with threats or intimidation. What should I say in the written agreement or plan? You should cover such things as: where the children live who the children spend time and communicate with school or childcare medical issues religious or cultural practices financial support for the children how parental responsibility is to be shared how disagreements about parenting arrangements will be sorted out how those with parental responsibility will communicate with each other. It is best to get legal help if you have children under 18. You and family law 19 18 Do I need to go to court? If you can agree, you do not need to go to court. If you want the agreement to be legally enforceable you can apply to the court for orders by agreement (consent orders). The family law system encourages people to try to agree, if they can. Family dispute resolution can be cheaper than going to court and more flexible. You can still get legal help. See the Family dispute resolution chapter on page 13. What if there is no agreement? If there is no agreement, you can apply to the court for a parenting order. You will have to go to family dispute resolution before you apply for a parenting order. There are some exceptions to this. See the Family dispute resolution chapter on page 13. A parenting order can say where the children live, who they have contact with and other issues such as schooling. The court s main concern is for the children. The court will decide what is in the children s best interests and will consider the children s views. You will have to go to a court hearing. Parents, grandparents or anyone concerned about a child s welfare can apply for parenting orders. Legal Aid Queensland 20 19 Do the children have to spend equal amounts of time with each parent? The law says parents have equal shared responsibility unless the court orders otherwise. This does not mean children have to spend equal amounts of time with each parent although the court must consider this. Think about what arrangement is in the children s best interests and what is reasonably practical. That may be equal time, substantial and significant time (which includes weekdays, weekends, holidays and special events or some other amount of time). It is best to think about the quality of care, providing a settled environment and working towards a plan where both parents feel satisfied the children s needs are being met. Every child has different needs. Legal Aid Queensland has produced an online video Life after separation - putting the pieces back together which can guide you through the legal process to ensure the arrangements you make for your family are fair and in your children s best interests. The video can be watched online at or at Family Relationship Centres. You can also get information and factsheets about children and family law by calling , ordering online at or from the Legal Aid Queensland website. Who has to financially support the children? Every parent has a financial duty to support their children. The amount to be paid depends on: the level of care each parent provides the ages and costs of raising your children both parents incomes if either parent has a second family. You and family law 21 20 For more information or if you are having difficulties with child support payments, contact Legal Aid Queensland. You can also get free information about child support by visiting What if my children do not want to visit their other parent? This will depend on the children s ages and if there are court orders about spending time with the parent. If the children refuse to visit, you still have a duty to encourage them as this is seen in their best interest. If you believe that spending time with the other parent puts the children at serious risk of physical or psychological harm, get legal help quickly. The police and other authorities may also need to be told. What if court orders for parenting time are not being followed? If the order is for you to spend time or communicate with the children and the children are being stopped from doing this, then the order is being broken. Get legal help to make sure the orders are followed. If the children live with you and the other parent does not turn up to spend time with the children, you cannot make them. What if the arrangements are not working? Over time things change and arrangements may need to be worked out differently. It is best to talk about this with the other parent and try to sort it out. If there are court orders these will still apply, even if your situation has changed. Get legal help. A family relationship centre or other dispute resolution service may be able to help you to work out a new arrangement. Legal Aid Queensland 22 21 Can I take my children interstate or out of the country? Try to get written permission from your former partner. You may need this to apply for a passport for the children. Whether you get permission may depend on if you are simply travelling or planning to move (relocate). If you cannot get permission you may need to get a court order. The law says children have a right to a relationship with both parents, and other important people in their lives. Moving a long distance away or interstate or overseas will affect these relationships. If there are parenting orders, get legal help before doing anything that may break them. The court can make orders to find (locate) and return (recover) children. What if children are not returned after seeing their other parent? Even if there are no court orders you can still apply to the court to have the children returned. Even if there is an order that the children live with you, this does not mean the police automatically have the power to return them to you. You may need to get a court order to have them returned. Get urgent legal help if you think your former partner may take your children out of the country without your permission (abduction). You can take out orders to stop this happening. The courts have emergency after hours telephone numbers for these situations. Act quickly. See the Where to get help chapter on page 27. You can get more detailed information about children and family law at You and family law 23 22 Dividing your property Does it matter whether we were married? No. From March 2009, property settlement for de facto and married couples is very similar, as de facto relationships are now covered by Commonwealth law. Can we come to an agreement? Whether you were married or not, it is a good idea to try to come to an agreement about property if possible. If you need help, there are family dispute resolution services that can help you sort out an agreement. See the Family dispute resolution chapter on page 13. A family relationship centre may also be able to help if there are children s matters involved as well as property. Get legal help before you start negotiating, and again before you sign an agreement. Also get financial help, such as through a financial counsellor. An agreement can be made into a court order, which can be enforced. Agreements lodged with the court are more difficult to change (except by agreement). Even if both of you agree, the court will not make an order unless it is just and equitable, which means fair to both sides. The aim is to make orders that are final so you do not have to go back to court. Legal Aid Queensland 24 23 Do I need a lawyer? You can get a lawyer to help you negotiate with your former partner. If you reach an agreement you can ask to have consent orders made. Even if you do not use a lawyer to help with negotiations, get legal advice before signing any agreement. When should I apply for a property settlement? You can apply for a property settlement at any time after separation, but it is important to try to sort it out as soon as possible. Usually there will be debts to be sorted out, as well as assets to divide, so do not delay. If you get a divorce, you must apply to court for property orders within 12 months of the actual divorce date, or you need special permission. What property am I entitled to? There are many things that must be considered in deciding who gets what property, especially if children need support. It may not matter whose name is on the document (such as a home title) or who bought an item or made the debt. Even if you earn little or no income you can still be entitled to property. You and family law 25 24 What should the property settlement list? The settlement should list: real estate, including the family home money held as cash or in bank accounts investments insurance policies inheritances shares superannuation jewellery any other assets any debts including mortgages, loans, credit cards and personal debts. Property includes assets and liabilities owned individually, with another person or by a family trust or family company. Even if you earn little or no income you can still be entitled to property. Legal Aid Queensland 26 25 How does the court decide who gets what? There is a three-step process under the Family Law Act. Step 1 Identify and value all property of the relationship or marriage (including debts). This property can include things you got before or even after the marriage. Step 2 Take into account what each person has given to the relationship (contributions) including earnings, savings, gifts, inheritances or property owned before the relationship, improvements to property, and contributions as a homemaker and parent. Step 3 Consider the other factors set out in the law, including: how much money each person could earn in the future age and health of each person care and financial support of children responsibility for looking after other people length of the relationship. The law looks at all of these things in deciding what is a fair division. The law does not look at who left the relationship. You and family law 27 26 What if I leave the house do I lose my rights to property? No. If you leave the house, you do not lose your rights to a share of the house, or other property. But get legal help, if possible, before you leave. Also think about what you might want to take with you. See the Family violence chapter on page 9. How can I protect my property? Keep track of all assets and debts until financial arrangements are complete. You may want to take photographs, and other records. It may be possible to have a caveat put on a property title. A caveat is a warning to other people that you have an interest in the property. You can also get court orders (injunctions) to stop property being sold or money being spent. Act quickly and get legal help soon. You can get more detailed information about property and family law from the Legal information area of our website Legal Aid Queensland You and family law. A short guide You and family law A short guide Contents 2 About this booklet 4 Legal words and phrases explained 7 Separation and divorce 11 Domestic violence 18 Family dispute resolution 21 Children 26 Dividing your, Does someone owe you money? A guide to help you claim a minor debt of $25,000 or less Does someone owe you money? A guide to help you claim a minor debt of $25,000 or less Contents 2 How can this guide help me? 2 What is a minor debt? 4 Do I need to get legal advice? 5 Before you make a Marriage, families & separation FAMILY COURT OF AUSTRALIA FEDERAL CIRCUIT COURT OF AUSTRALIA This brochure will tell you This brochure provides information for people considering, or affected by separation or divorce. This brochure includes What happens when your relationship ends? Family Law Aboriginal What happens when your relationship ends? This brochure assists Aboriginal families work out what s best for the kids 1 What is family law? Most family law matters in Australia are Personal Safety Intervention Orders Personal Safety Intervention Orders A guide to resolving disputes and protecting your safety. This booklet is about personal safety intervention orders, which can help protect you from threats and violence Family & A Guide to Family Law in Queensland. De-Facto Law Family & A Guide to Family Law in Queensland De-Facto Law GLOSSARY When dealing with family law it is important to have a clear understanding of legal jargon. When it comes to legal documentation semantics Acknowledgements. The 10th edition of Women and Family Law was updated by the solicitors at Women s Legal Services NSW. Women and Family Law - 10th edition Acknowledgements The 10th edition of Women and Family Law was updated by the solicitors at Women s Legal Services NSW. Cover designed by Miska Graphics Layout and design Marriage, families & separation FAMILY COURT OF AUSTRALIA FEDERAL CIRCUIT COURT OF AUSTRALIA Marriage, families & separation Separation This brochure provides information for people considering, or affected by separation or divorce. Disclaimer Acknowledgements 1 Disclaimer The guidance provided in this workbook is not legal advice, it is information only. This workbook has been designed for you to use with legal help from a lawyer. The authors of this resource Family Law and You May 2016 Legal Services Commission Family Law and You Family Law and You May 2016 Legal Services Commission This booklet is for men and women who are separating from their partners. This is a simple guide to Family Law - it is not a substitute A GUIDE TO FAMILY LAW LEGAL AID A GUIDE TO FAMILY LAW LEGAL AID Important new rules in relation to legal aid were introduced on 1 April 2013 by the Legal Aid, Sentencing and Punishment of Offenders Act 2012 (LASPO). This legal guide The Family Law Guide for Australia The Family Law Guide for Australia CONTENTS 2... Contents 4... Family Law Courts 5...De Facto Relationships 7... Working it Out on Your Own 7... Private Negotiations 7...Lawyer led Negotiations and/or What you should know about IN ONTARIO What you should know about IN ONTARIO This booklet contains information about the law as it was at the time it was written. The law can change. Check the Ministry of the Attorney General website at Seeking Protection from Domestic Violence in New York s. Information for Immigrant Victims with Limited English Proficiency Seeking Protection from Domestic Violence in New York s Family Court: Information for Immigrant Victims with Limited English Proficiency What is domestic violence? If your current or former intimate partner DOMESTIC VIOLENCE. Do the right thing see your lawyer first DOMESTIC VIOLENCE Do the right thing see your lawyer first Contents 1. What is domestic violence? 2. What protection does the law offer? 3. Who can apply for protection? 4. What is a protection order? Superannuation & Disability Claims Securing your future Superannuation & Disability Claims Securing your future Great people Great results Great value Established 1952 Superannuation & Disability Claims When you are unable to work because of injury or illness, FROM CHARGE TO TRIAL: A GUIDE TO CRIMINAL PROCEEDINGS FROM CHARGE TO TRIAL: A GUIDE TO CRIMINAL PROCEEDINGS If you are experiencing, or have experienced, domestic violence and/or sexual violence there are a number of ways the law can protect you. This includes Resource pack DOMESTIC AND FAMILY VIOLENCE REFERRAL REFERENCES Resource pack DOMESTIC AND FAMILY VIOLENCE REFERRAL REFERENCES September 2015 2 Queensland Government Resource Pack Contents Domestic and family violence support services contact list... 4 Situation 1 Marriage, Families & Separation FAMILY COURT OF WESTERN AUSTRALIA Marriage, Families & Separation FAMILY COURT OF WESTERN AUSTRALIA This brochure provides information for couples considering separation or divorce. It also includes information for people affected, or Slater & Gordon Family Law Solicitors Slater & Gordon Family Law Solicitors Contents About Us 3 Divorce, Separation & Civil Partnership Dissolution 4 Children Matters 4 Finances 5 Cohabitation Issues 6 International Divorce 6 Domestic Abuse Family Law. What are your rights? Family Law What are your rights? Separation or divorce is a major crisis in anyone's life. You may find that it takes some time to come to terms with the separation and adjust to your new circumstances. Tool kit Domestic Violence Tool kit Domestic Violence A self-help resource to help people living with domestic violence Lifeline s domestic violence tool kit provides information about: Understanding what domestic violence is Developing Civil legal aid information for applicants Civil legal aid information for applicants This leaflet covers both civil legal aid and advice and assistance Solicitors you must give this leaflet to clients before they complete a financial eligibility Law Information: The basics Family Law Information: The basics 1 Family Law The basics Legal advice is always dependent upon your particular circumstances, and this is particularly the case in family law The information in this brief FIXED FEE DIVORCE AND FAMILY LAW SERVICES 01226 210000 info@mkbsolicitors.co.uk Please feel free to telephone the office and request to speak to a member of the family team Page 1 of 12 If your relationship has broken down AN OVERVIEW OF AUSTRALIAN FAMILY LAW AN OVERVIEW OF AUSTRALIAN FAMILY LAW For the information of clients and prospective clients of Kennedy Partners The breakdown of a marriage or de facto (including same sex) relationship can give rise to Department of Communities, Child Safety and Disability Services Legislation explained Department of Communities, Child Safety and Disability Services Legislation explained The Domestic and Family Violence Protection Act 2012 About this booklet Domestic and family violence affects individuals, What You Need to Know About Divorce What You Need to Know About Divorce There are four main steps in a divorce: 1. 2. 3. 4. Your lawyer writes the divorce papers and files them with the court. The sheriff s department gives (serves) your REPORTING AN OFFENCE TO THE POLICE: A GUIDE TO CRIMINAL INVESTIGATIONS REPORTING AN OFFENCE TO THE POLICE: A GUIDE TO CRIMINAL INVESTIGATIONS If you are experiencing or have experienced domestic volence and/or sexual violence there are a number of ways the law can protect A death in the workplace Office of Fair and Safe Work Queensland A death in the workplace A guide for family and friends A death in the workplace a guide for families and friends Page 1 of 13 The State of Queensland Department Property Settlement - Caveats in Family Law in Queensland Application and Purpose Property Settlement - Caveats in Family Law in Queensland Application and Purpose It is becoming more frequent in family law disputes for property to be registered in one party s name only. This may, A guide for beneficiaries A guide for beneficiaries March 2013 who? why? what? why? 20 frequently asked questions about being an beneficiary. what? what? This booklet provides a guide, in question and answer format, for beneficiaries POWERS OF ATTORNEY WHAT IS A GENERAL POWER OF ATTORNEY? What do you do if you want someone to help look after your affairs? What if you become unable to look after yourself or make decisions about your own affairs? Who can make decisions about your welfare Going to a Mental Health Tribunal hearing June 2015 Going to a Mental Health Tribunal hearing Includes: information about compulsory treatment and treatment orders information about Mental Health Tribunal hearings worksheets to help you represent Housing options for single parents Formed from the merger of the National Council for One Parent Families and Gingerbread Factsheet For single parents in England and Wales February 2012 Freephone 0808 802 0925 Gingerbread Single Parent FACT SHEET RELOCATION women s legal service FACT SHEET RELOCATION Can I move with my child(ren) without the other parent s permission? If you want to move with your child(ren), the other parent's permission will be required Toolkit for Immigrant Women Working with a Lawyer Toolkit Working with a Lawyer NOVEMBER 2010 Toolkit Working with a Lawyer NOVEMBER - 2010 This resource is part of Battered Claim of. family. These Provisions may be relied upon by persons who have applied for a visa as either: Family Violence & Immigration This fact sheet provides information about the criteria for making claims of family violence under certain visa classes. This fact sheet applies to claims for family violence WHAT IS AN INTERVENTION ORDER? This information is general and not a substitute for legal advice. The Legal Services Commission provides free advice for most legal problems. Contact the Legal Helpline on 1300 366 424 4 Criminal and Family Law 4 Criminal and Family Law ENG 004/2010 FAMILY LAW FOR WOMEN IN ONTARIO All Women. One Family Law. Know your Rights. Criminal and Family Law This booklet is meant to give you a basic understanding of legal All Women. One Family Law. 7 Family Law Arbitration ENG 007 FAMILY LAW FOR WOMEN IN ONTARIO All Women. One Family Law. Know your Rights. Family Law Arbitration This booklet is meant to give you a basic understanding of legal issues. Coping with separation and divorce LifeGuides Coping with the emotional pain Establishing your independence The legal process Finding legal and financial planners Financial advice Difficulty managing your debts? Getting help Coping with Understanding Nebraska's Protection Orders Understanding Nebraska's Protection Orders A guide for victims, law enforcement and service providers. What is a Protection Order? A protection order is a special type of order issued by a Judge which Application for Bond Loan and Rental Grant assistance Office use only (application number) Bond Loan Rental Grant Application for Bond Loan and Rental Grant assistance The Department of Housing and Public Works provides Bond Loans and Rental Grants to people [5] Civil legal aid what you may have to pay [5] Civil legal aid what you may have to pay It s important that you understand, before your solicitor starts working for you, what you might have to pay. This leaflet explains: what you might have to FAMILY LAW INFORMATION SESSIONS - 2011 FAMILY LAW INFORMATION SESSIONS - 2011 FAMILY LAW COURTS JOINT REGISTRY COMPLEX MATTERS - Family Court: applications about validity/nullity of marriage Hague Convention (removal of children overseas) Special Self-represented litigants kit Children Evidence & procedure Property Self-represented litigants kit A do-it-yourself kit to help you prepare a family law case and represent yourself in court Children Evidence & procedure Property Service Kit.. documents on another person in a case Service Kit Use this Use kit this when kit when asking you for need Court to orders serve to end a marriage documents on another person in a case This kit DOMESTIC VIOLENCE AND THE NEW MEXICO FAMILY VIOLENCE PROTECTION ACT DOMESTIC VIOLENCE AND THE NEW MEXICO FAMILY VIOLENCE PROTECTION ACT This information guide is general in nature and is not designed to give legal advice. The court does not guarantee the legal sufficiency Training Materials Day Two. Settled & Safe TRAINING MATERIALS DAY TWO Settled & Safe TRAINING MATERIALS DAY TWO 1 CONTENTS SETTLEMENT WORKER TRAINING TRAINING MATERIALS DAY TWO 2 About this training 2 Information not advice 2 Victoria Legal Aid services 2 Activity: Reflections Guide For Advocates Working With Immigrant Victims of Domestic Violence Guide For Advocates Working With Immigrant Victims of Domestic Violence Created by the Domestic Violence Coordinating Council October 2009 This guide is intended to provide information to advocates working Protective Orders Including: Order of Protection and Injunction Against Harassment Things You Should Know About Protective Orders Including: Order of Protection and Injunction Against Harassment This booklet is designed to provide general information about protective orders for domestic Divorce in Florida CAN YOUR MARRIAGE BE SAVED? Before you take any legal steps to end your marriage, you should make sure that you have tried all possible ways to save it. Do you want professional help Information for parents considering adoption of their child Information for parents considering adoption of their child Published by the Victorian Government Department of Human Services Melbourne, Victoria Copyright State of Victoria 2008 This publication is copyright, Relationships & Centrelink Relationships & Centrelink Frequently Asked Questions This booklet aims to assist people who are receiving income support payments from Centrelink. It provides information regarding a persons rights and Information Session Property Proceedings Information Session What will be covered Settling outside of court Pre-action procedures The Court process, structure and events The Law What will be covered (Notes) This presentation serves as a guide, The Family Law Act in PEI Community Legal Information Association of Prince Edward Island, Inc. The Family Law Act in PEI This pamphlet provides an overview of the Family Law Act. This Act defines the term spouse and covers Legal Information for Same Sex Couples Community Legal Information Association of Prince Edward Island, Inc. Legal Information for Same Sex Couples People in same sex relationships often have questions about their rights and the rights of their A guide for executors A guide for executors MARCH 2013 who? why? what? why? what? 18 frequently asked questions about being an executor. This booklet provides a guide, in question and answer format, for executors about their Alternatives to court Chapter 7 Do not use this guide for legal advice. It provides information only, and that information only applies to British Columbian law, services, and benefits. Consult with a lawyer for advice related WHAT BANKRUPTCY CAN T DO A decision to file for bankruptcy should only be made after determining that bankruptcy is the best way to deal with your financial problems. This brochure cannot explain every aspect of the bankruptcy Help with housing for Queenslanders affected by a disaster event Help with housing Queensland Disaster Response Housing and Homelessness Services Help with housing for Queenslanders affected by a disaster event The following is a list of programs and products available Domestic Violence: Can the Legal System Help Protect Me? Domestic Violence: Can the Legal System Help Protect Me? What is domestic violence? Domestic violence is a pattern of physically and/or emotionally abusive behavior used to control another person with Compensation and its effect on social security. What is not treated as compensation? factsheet Compensation and its effect on social security I This factsheet explains how receiving compensation may prevent you from receiving a social security payment, or you may have your payment reduced. What is DOMESTIC VIOLENCE? What is DOMESTIC VIOLENCE? Domestic violence is a pattern of control used by one person to exert power over another. Verbal abuse, threats, physical, and sexual abuse are the methods used to maintain power A GUIDE TO DIVORCE. The law A GUIDE TO DIVORCE Deciding that your marriage has ended can be very difficult. If you are not sure whether your marriage is at an end, there are relationship counselling services which may be useful in Insurance. Insurance. My home is insured. What should I do first? Insurance This chapter has information for people with insurance queries who experienced loss because of the February 2009 Victorian bushfires. It also has information on financial and other help. My BANKRUPTCY SOME FREQUENTLY ASKED QUESTIONS AND ANSWERS BANKRUPTCY SOME FREQUENTLY ASKED QUESTIONS AND ANSWERS 1 You should file for bankruptcy only after carefully deciding that bankruptcy is the best way to deal with your financial problems. This pamphlet Why use ADR? Pros & cons Why use ADR? Pros & cons Thinking about ADR? This leaflet is for you if you ve heard about alternative dispute resolution (ADR) and are wondering whether to use it to try and resolve a dispute. It will ORDER OF PROTECTION FREQUENTLY ASKED QUESTIONS BY PLAINTIFFS ORDER OF PROTECTION FREQUENTLY ASKED QUESTIONS BY PLAINTIFFS Q. Who can get an order of protection? A. An order of protection (OP) may be issued against a spouse, an ex spouse, a person with whom you have Family Mediation Information and Assessment (MIAM) form FM1 Family Mediation Information and Assessment (MIAM) form FM1 To be completed by the court Name of court Case reference Before completing this form please read the information notes at the end of the form. Dealing with debt: Your rights and responsibilities Dealing with debt: Your rights and responsibilities Key tips 1. Manage your finances and plan your budget, so that debts don t build up and take you by surprise. 2. A free and independent financial counselling Application for Compensation Application for Compensation This Application for Compensation form for injured workers is an approved form under the Workers Compensation and Rehabilitation Act 2003 (the Act). The general information
http://docplayer.net/1186097-You-and-family-law-a-short-guide.html
CC-MAIN-2017-51
refinedweb
8,224
53.41
Base class to be used by plugins to define custom pages in Create Server dialog. More... #include <createserverdialogpage.h> Base class to be used by plugins to define custom pages in Create Server dialog. Definition at line 38 of file createserverdialogpage.h. Generates game run parameters basing on the page's contents. These parameters are passed as arguments to the executable when the game process is started. Loads variables that are stored in the config into the GUI. This config is saved by Doomseeker when it calls saveConfig() method. Saves variables defined by this page to a config. This config is loaded by Doomseeker when it calls loadConfig() method. Validates contents of the page before the saveConfig(). Should return true on validation success or false otherwise. This may be used to modify the page contents, appearance or behavior. Validation is run before the game is run. No validation is performed before saveConfig() or after loadConfig(). Pages must take care of displaying their own error messages. Default behavior assumes that no validation is needed and always returns true. Definition at line 59 of file createserverdialogpage.cpp.
https://doomseeker.drdteam.org/docs/doomseeker_1.0/classCreateServerDialogPage.php
CC-MAIN-2021-25
refinedweb
185
60.72
Commenting Objective-C Code There is an old saying amongst veteran programmers that goes something like "Don't comment bad code, re-write it!". Before exploring what these seasoned programmers are really saying, it is important to understand what comments are and why we should use them. Why Comment your Code? <google>IOSBOX</google> Comments in both programming and scripting languages provide a mechanism for the developer to write notes that are ignored by the compiler or interpreter. These notes are intended solely for either the developer or anyone else who may later need to modify the code. The main purpose of comments, therefore, is to allow the developer to make notes that help anyone who may read the code later to understand issues such as how a particular section of a program works, what a particular method does or what a variable is used to store. Commenting code is considered to be good practice. Rest assured that a section of Objective-C code that seems obvious when you write it will often be confusing when you return to it months, or even years later to modify it. By including explanatory comments alongside the code Objective-C program does then you must have written it badly. Whilst one should always strive to write good code there is absolutely nothing wrong with including comments to explain what the code does. Even a well written program can be difficult to understand if it is solving a difficult problem so, ignore the old programmer's adage and never hesitate to comment your Objective-C code. Another useful application of comments in Objective-C is to comment out sections of a program. Putting comment markers around sections of code ensures that they are ignored by the compiler during compilation. This can be especially useful when you are debugging a program and want to try out something different, but do not want to have to delete the old code until you have tested that the new code actually works. Single Line Comments The mechanism for a single line comment is marked by prefixing the line with // (this will familiar to C++ or Java programmers). For example: // This is a comment line. It is for human use only and is ignored by the Objective-C compiler. NSString *myString; int i = 0; // This is another comment The // syntax tells the compiler that everything on the same line following on from the // is a comment and should be ignored. This means that anything on the line before the // comment marker is not ignored. The advantage of this is that it enables comments to be placed at the end of a line of code. For example: NSString *myString = @"Welcome to Techotopia"; // Variable containing pointer to welcome string object In the above example everything after the // marker is considered a comment and, therefore, ignored by the Objective-C compiler. This provides an ideal method for placing comments on the same line of code that describe what that particular line of code does. Multi-line Comments For the purposes of supporting comments that extend over multiple lines Objective-C */ (int) addNums (num1, num2) { return (num1 + num2) } Multi-line comments are particularly useful for commenting out sections of a program you no longer wish to run but do not yet wish to delete, together with an explanation of when and why you have commented it out: /* Commented out December 23 while testing improved version int myValue = 1; NSString *myString = @"My lucky number is "; NSLog ( @"%@ %@", myString, myValue ); */ Summary Comments in Objective-C enable the developer to add notes about the code or comment out sections of code that should not be compiled. Comments can be single line comments (using the // marker) or multi-line (beginning with /* and ending with */). Commenting is considered to be good practice. Regardless of how well you understand the logic of some Objective-C, there is a good chance you may one day have to return to that code and modify it. Often this can be months, or even years later and what seemed obvious to you at the time you wrote it may seem less obvious in the future. Also, it is often likely that some other person will have to work on your code in the future. For both these reasons it is a good idea to provide at least some basic amount of commenting in your code.
https://www.techotopia.com/index.php/Commenting_Objective-C_Code
CC-MAIN-2018-39
refinedweb
731
54.97
If you are an ASP.NET Web Forms programmer making the switch to ASP.NET MVC – what’s the first thing you should learn? There are lots of candidates for the number one spot. Some people will say the first thing to do is learn and embrace the spirit of the MVC design pattern. Others might say you should learn how to unit test a controller, or learn how to use a view model. Learn how to use an HTML <form>. Please excuse the ASP.NET web forms programmer who forgets about the <form> tag. Although every .aspx file has one, they never need to touch it, or even look at it. The form tag is not only well hidden, but also constrained. It only take a few years to start thinking the web revolves around pages that only submit information back to themselves. The most important things to lean (or relearn) are: Let’s look at each case. There are two types of requests a web browser will use when communicating with a web server – POST requests and GET requests. Both are designed to do what they sound like – GET a response, or POST some information and receive a response. Web forms always use POST methods. HTTP POST is the best method to use when you are submitting information to a web server and changing state in your application. For example, if a user fills out a <form> with textbox and radio button controls full of patient information you want to save in a database, then POST is the HTTP method you should use. The browser will POST the user’s values to the server where you can save them in the database, and then you can respond and tell the user everything worked (or tell them something blew up). On the other hand, an HTTP GET operation operation is the best way to submit information to a server when you are not changing state inside the application. The best example is a form used to search for information. You need to send search parameters to the server, but the search parameters aren’t creating new records in a database – they are only used as to query information. <form action="/search" method="get"> <input type="text" name="searchTerm" /> <input type="submit" value="Search" /> </form><form action="/search" method="get"> <input type="text" name="searchTerm" /> <input type="submit" value="Search" /> </form> If the user enters “baby blue bathysphere” into the textbox and clicks the button, the browser will send off a GET request with the following URL: /search?searchTerm=baby+blue+bathysphere Notice how the submitted form values are placed in the URL itself. Not only is a GET operation cacheable, but users can also bookmark the response to a GET submission because all the information needed to produce the page is in the URL. GET is the default value for the method attribute of a <form>, so if you don’t specify the method you’ll have a GET by default. ASP.NET web forms always POST to themselves, which can be limiting. As the previous example demonstrates, you can set the action attribute to submit a form to any URL, even a URL pointing to another application on a different server. For example, the following HTML would send the user to Google (both Google and Bing both expect the search parameter to have the name “q”). <form action="" method="get"> <input type="text" name="q" /> <input type="submit" value="Search" /> </form> You’ll usually be setting the action attribute to submit information to some controller action in your MVC application. The Html.BeginForm helpers will help build the correct <form> tag to reach the desired action for you. If we were using the first code-snippet in this post (the one with an action of “/search”), we could respond to the search request with the default action of a SearchController. The MVC framework can automatically pass the searchTerm form parameter as a parameter to the action. public class SearchController : Controller { public ActionResult Index(string searchTerm) { // .... return View(); } } Well … not always. There are times when having multiple <form> tags on a page is a good idea. You can have two distinct pieces of a page submit information to two different URLs. Multiple <form> tags regularly make sense on portal type pages that contain multiple sections with disparate functionality. Like an area that lets a user get a stock quote, and an area that lets a user search for a movie. These are two different tasks that will probably best be handled by two different controllers, two different URLs, two different forms, and two different sets of input controls. <form action="/stock/quote"> <input type="text" name="symbol" /> <input type="submit" value="Quote It!" /> </form> <!-- ... ---> <form action="/movie/search"> <input type="text" name="q" /> <input type="submit" value="Search" /> </form> Not every scenario requires multiple forms, however. Sometimes you want a single form to provoke different behaviors from the server. For example, imagine a shopping page where a user selects some check boxes for products they are interested in. You might need a button allowing the user to submit this information to “compare products” and another button allowing the user to save the selected items in a “wish list”. Both buttons need to submit the same information to the server, so they’ll probably live inside the same form <form action="products/shop" method="post"> <!-- --> <input type="submit" name="task" value="Compare" /> <input type="submit" name="task" value="Save to wish list" /> </form> Both buttons in the above form will force the browser to POST to products/shop. Notice how both buttons have the same value for the name attribute, but their values are different. In an MVC application you can create a controller to accept this form submission: public class ProductsController : Controller { [AcceptVerbs(HttpVerbs.Post)] public ActionResult Shop(string task) { // ... return View(); } } The value of the task parameter in the Shop action will contain the value of the button – either “Compare” or “Save to wish list”. You can inspect this value and decide what to do next. Having <form> tags available to due your bidding in an MVC application allows you a great deal of flexibility and control. Every bit you learn about using forms will give you an edge in building your application. Experiment with them, read about them, and learn to love them!
https://odetocode.com/blogs/scott/archive/2009/11/30/whatrsquos-the-first-thing-to-learn-about-asp-net-mvc.aspx
CC-MAIN-2021-21
refinedweb
1,066
61.36
New in Mono 3.2.3 Highlights This release features over 2 months of fixes a few nice features. We’re now back to do simultaneous releases to Windows, Linux and Mac. The C# compiler has a lot of fixes for async related issues. New static and dynamic hardware capabilities probing, mono can now exploit hardware caps in many more cases than before. Blended v5/v7 mode for arm. Some ARM targets require binaries that support all the way from very old CPUs to the most modern ones. Previously we would fail to work on SMP machines when built for UP targets. Added skeletons for both System.DirectoryServices and System.Windows.Forms.DataVisualization.Charting. New server focused flag. Run mono with –server to tell the runtime to target performance. With this release, this means an aggressive threadpool scheduler that creates additional threads faster. We put a lot of effort on windows for this release. Builds are now based on a recent mingw toolchain. We fixes a good number of build issues and bugs in the windows backed. We have finally switched to use vectored exception handling on windows, which makes it possible, for those of us that like Inception, to debug mono’s debugger. And, finally, PCL has arrived. This means a few fixes in the runtime, class libraries and build tools. And, on Mac, we now ship PCL reference assemblies. Bugs - 1782 - Check generic constraints for duplicates. - 4141 - XmlSchemaImporter needs to consider attributeGroupRef in some case. - 4344 - xsl:stylesheet always ignored xsl template contents. - 4668 - C# compiler doesn’t like decimal in custom attribute values, so use string. - 6327 - Correctly install xbuild - 7126 - Don’t allow execution of dynamic assemblies without run access. - 8637 - omit xml declaration for ToString(). - 8719 - Implements parsing of multi value User-Agent string. - 8934 - Add more implicit generic array interfaces. - 10001 - Do not use chunked encoding with CGI/FastCGI. - 10194 - SetElementValue(nonExistentElementName, null) caused NRE. - 11294 - Add more system assemblies remapping. - 11778 - Fix Syscall.readlink() for non-ascii targets. - 11910 - Implement character validation methods in XmlConvert. - 12035 - xsi:nil=’true’ was ignored in some scenario. - 12469 - Add more conversion methods to XmlAtomicValue. - 12995 - Avoid an assert in mono_save_seq_point_info () if no seq points are generated for a method. - 13050 - Properly null terminate strings in mono_dwarf_escape_path (). - 13065 - Continue single stepping if the same line reached in all cases. Factor out some code code. - 13191 - Avoid passing partially shared instances to the JIT. - 13233 - Fix an overflow if MONO_ZERO_LEN_ARRAY is not 0. - 13289 - Nested partial type inside generic class can have base type defined later than current type inflation happens. - 13316 - Add nested partial types inside nested partial types to AST. - 13318 - Schedule internal delay task on default scheduler only. - 13324 - Lazy initialization of type parameters expanded interfaces. - 13336 - Handle property with default values. - 13340 - Another attempt at fixing mono_atomic_load_acquire() on MSVC. - 13343 - Support FTP download where PWD starts with ‘\’. - 13362 - Adds async handling to binary:emitbranchable. - 13435 - Add some error checking to custom attr parsing and plug a memory leak. - 13443 - Add clone for error expression. - 13454 - Lift result of enum substraction when operation is lifted due to non-nullable enum type. - 13466 - Add *CachePolicy to mobile profile. - 13476 - Ignore space separators in nowarn arguments. - 13488 - Add AssemblyAction.Save to the linker. - 13497 - Check promoted value type binary equality operations against null too. - 13501 - Correctly parse pragma headers. - 13509 - Remove CultureInfo.CurrentCulture dependency from ordinal based string::EndsWith. - 13523 - Write only import section from global namespaces before global attribute sections. - 13544 - Fix overflow checking in newarray with 64 bit array lengths. - 13549 - Correctly import nested non-generic types inside generic containers used within same generic container. - 13552 - Grow underlying buffer only when necessary. - 13603 - Quote path arguments to opt/llc. - 13604 - STW handshake/thread shutdown race condition. - 13626 - Rewrites RuntimeReflectionExtensions to actually do something. - 13682 - Don’t show internal error when default paramater expression cannot be converted to paramter type. - 13708 - ASP.NET routing constraints should be treated as ‘convertible to string’ - 13716 - use XmlSchemaSettings.XmlResolver to resolve schemas. - 13729 - Fix cross compilation to windows. “Windows.h” should be “windows.h”. - 13731 - Handle partial class case when nested type of partial container depends on parent base type from another partial container. - 13734 - Disable LLVM for async methods. - 13736 - Create correct flow branching for single non-default switch section. - 13742 - Always release DeflateStream unmanaged resources. - 13767 - Handle custom attributes with nested array of enums. - 13786 - Update named params parameter converted result expression. - 13793 - Inflate default parameter expression without type checks - 13813 - Thread teardown race condition. - 13817 - Basic optional parameters support in binder. - 13879 - Verifier support for IReadOnlyList<T> and IReadOnlyCollection<T>. - 13890 - Relax the restriction on global methods visibility. - 13892 - Add argument modifiers to generated base proxy when needed. - 13951 - Avoid lookups in the AOT images during STW. - 13952 - Don’t crash when reporting invalid case label value. - 13953 - Support OID names in RSACryptoServiceProvider.SignData(). - 13969 - Fix recursive check for non dependent return types during type inference. - 13970 - Correct parsing of invalid 00000000-0000-0000-0000-000000000000 guid format. - 13977 - Use the invariant culture calendar if the requested one is not available. - 13996 - Type parameter inflated interfaces needs to be marked too. - 14032 - Fixes GZipStream dispose order. - 14053 - Report error for name collision between property and generic method. - 14069 - Avoid the managed->copy for ref vtypes with an [In] attribute in n2m wrappers. - 14077 - HashSet no longer grows in capacity on deserialize - 14126 - Bad compiler interaction between anonymous method and async - 14143 - xsl:import in included stylesheet caused compilation error. - 14168 - Use IReflectType interface instead of TypeDelegator. - 14185 - Fixes negative symbol definition for few locales to be simple -. - 14194 - Fix yet another DISABLE_JIT bug in wrapper generation. - 14217 - Fix an LLVM assertion on structs with unaligned size. - 14245 - Invalid syntax during attribute target parsing can crash parser. - 14289 - Probing of generic parameter needs to check both operands. - 14339 - Clear out the ref fields from MonoDomain before calling mono_gc_clear_domain. - 14347 - More thorough check for managed type parameters. - 14351 - Bad compiler interaction between captured this, lambdas and async. - 14384 - Don’t resolve extension method expression when in probing mode. - 14426 - Perform alignment checks for CAS on 32bits systems. - 14503 - Add support for invoking interface methods. - 14505 - Set empty string to TraceListeners for empty assert message. - 14515 - Fixes parallel enumerable index counter. - 14544 - Add System.ServiceModel.Activation assembly. - 14555 - Make suspend work during thread cleanup.
https://www.mono-project.com/docs/about-mono/releases/3.2.3/
CC-MAIN-2020-50
refinedweb
1,065
53.68
Using roundabout process of finding the simple solution. Here is my setup/test code. I am running Python 2.7.3 on Ubuntu 12.04. import cStringIO import gzip STUFF_TO_G?""" FILENAME = 'myfile.json.gz' def pycurl_simulator(fileobj): # Get the file size fileobj.seek(0, 2) filesize = fileobj.tell() fileobj.seek(0, 0) # Read the file data fout = open(FILENAME, 'wb') fout.write(fileobj.read()) fout.close() return filesize Try 1: seek from the end fails¶ Here is my first attempt using cStringIO with the gzip module. def try1_seek_from_end_fails(): ftemp = cStringIO.StringIO() fgzipped = gzip.GzipFile( filename=FILENAME, mode='wb', fileobj=ftemp) fgzipped.write(STUFF_TO_GZIP) filesize = pycurl_simulator(fgzipped) print filesize I got this exception: Traceback (most recent call last): File "tmp.py", line 232, in <module> try1_seek_from_end_fails() File "tmp.py", line 83, in try1_seek_from_end_fails filesize = pycurl_simulator(fgzipped) File "tmp.py", line 25, in pycurl_simulator fileobj.seek(0, 2) File "/usr/lib/python2.7/gzip.py", line 415, in seek raise ValueError('Seek from end not supported') ValueError: Seek from end not supported It turns out the gzip object doesn't support seeking from the end. See this thread on the Python mailing list: Try 2: data is not compressed¶ What if we don't seek() from the end and just tell() where we are? (It should be at the end after doing a write(), right?) Unfortunately, this gave me the uncompressed size. Reading from the GzipFile object also gave me an error saying that I couldn't read from a writable object. def try2_data_is_not_compressed(): ftemp = cStringIO.StringIO() fgzipped = gzip.GzipFile( filename=FILENAME, mode='wb', fileobj=ftemp) fgzipped.write(STUFF_TO_GZIP) filesize = fgzipped.tell() print filesize Try 5: file much too small¶ I googled, then looked at the source code for gzip.py. I found that the compressed data was in the StringIO object. So I performed my file operations on it instead of the GzipFile object. Now I was able to write the data out to a file. However, the size of the file was much too small. def try5_file_much_too_small(): fgz = cStringIO.StringIO() gzip_obj = gzip.GzipFile( filename=FILENAME, mode='wb', fileobj=fgz) gzip_obj.write(STUFF_TO_GZIP) filesize = pycurl_simulator(fgz) print filesize Try 6: unexpected end of file¶ I saw there was a flush() method in the source code. I added a call to flush(). This time, I got a reasonable file size, however, when trying to gunzip it from the command line, I got the following error: gzip: myfile.json.gz: unexpected end of file def try6_unexpected_end_of_file(): fgz = cStringIO.StringIO() gzip_obj = gzip.GzipFile( filename=FILENAME, mode='wb', fileobj=fgz) gzip_obj.write(STUFF_TO_GZIP) gzip_obj.flush() filesize = pycurl_simulator(fgz) print filesize Try 7: got it working¶ I knew that GzipFile worked properly when writing files directly as opposed to reading from the StringIO object. It turns out the difference was that there was code in the close() method of GzipFile which wrote some extra required data. Now stuff was working. def try7_got_it_working(): fgz = cStringIO.StringIO() gzip_obj = gzip.GzipFile( filename=FILENAME, mode='wb', fileobj=fgz) gzip_obj.write(STUFF_TO_GZIP) gzip_obj.flush() # Do stuff that GzipFile.close() does gzip_obj.fileobj.write(gzip_obj.compress.flush()) gzip.write32u(gzip_obj.fileobj, gzip_obj.crc) gzip.write32u(gzip_obj.fileobj, gzip_obj.size & 0xffffffffL) filesize = pycurl_simulator(fgz) print filesize Try 8: (not really) final version¶ Here's the (not really) final version using a subclass of GzipFile that adds a method to write the extra data at the end. If also overrides close() so that stuff isn't written twice in case you need to use close(). Also, the separate flush() call is not needed. def try8_not_really_final_version(): class MemoryGzipFile(gzip.GzipFile): """ A GzipFile subclass designed to be used with in memory file like objects, i.e. StringIO objects. """ def write_crc_and_filesize(self): """ Flush and write the CRC and filesize. Normally this is done in the close() method. However, for in memory file objects, doing this in close() is too late. """ self.fileobj.write(self.compress.flush()) gzip.write32u(self.fileobj, self.crc) # self.size may exceed 2GB, or even 4GB gzip.write32u(self.fileobj, self.size & 0xffffffffL) def close(self): if self.fileobj is None: return self.fileobj = None if self.myfileobj: self.myfileobj.close() self.myfileobj = None fgz = cStringIO.StringIO() gzip_obj = MemoryGzipFile( filename=FILENAME, mode='wb', fileobj=fgz) gzip_obj.write(STUFF_TO_GZIP) gzip_obj.write_crc_and_filesize() filesize = pycurl_simulator(fgz) print filesize Try 9: didn't need to do that (final version)¶ It turns out I can close the GzipFile object and the StringIO object remains available. So that MemoryGzipFile class above is completely unnecessary. I am dumb. Here is the final iteration: def try9_didnt_need_to_do_that(): fgz = cStringIO.StringIO() gzip_obj = gzip.GzipFile( filename=FILENAME, mode='wb', fileobj=fgz) gzip_obj.write(STUFF_TO_GZIP) gzip_obj.close() filesize = pycurl_simulator(fgz) print filesize References¶ Here is some googling I did: - - - - - - Good article. I appreciate and it is nice to see your exploration / thought process. fgz = cStringIO.StringIO() with gzip.GzipFile(filename=FILENAME, mode='wb', fileobj=fgz) as gzip_obj: gzip_obj.write(STUFF_TO_GZIP) filesize = pycurl_simulator(fgz) print filesize works as expected pablo: Using a context manager makes it even simpler-- thanks!
http://www.saltycrane.com/blog/2012/11/using-pythons-gzip-and-stringio-compress-data-memory/
CC-MAIN-2015-18
refinedweb
833
61.93
After. Who has not seen hours of nitpicking on code reviews, a heated debate around the coffee machine or nerf guns battles to decide where the semicolon should be? When I start a new project, the first thing I do is set up an automated style check. With that in place, there's no time wasted during code reviews about manually checking what's a program's good at: coding style consistency. Since coding style is a touchy subject, it's a good reason to tackle it at the beginning of the project. Python has an amazing quality that few other languages have: it uses indentation to define blocks. While it offers a solution to the age-old question of "where should I put my curly braces?", it introduces a new question in the process: "how should I indent?". I imagine that it was one of the first question that was raised in the community, so the Python folks, in their vast wisdom, came up with the PEP 8: Style Guide for Python Code. This document defines the standard style for writing Python code. The list of guidelines boils down to: - Use 4 spaces per indentation level. - Limit all lines to a maximum of 79 characters. - Separate top-level function and class definitions with two blank lines. - Encode files using ASCII or UTF-8. - One module import per importstatement and per line, at the top of the file, after comments and docstrings, grouped first by standard, then third-party, and finally local library imports. - No extraneous whitespaces between parentheses, brackets, or braces, or before commas. - Name classes in CamelCase; suffix exceptions with Error(if applicable); name functions in lowercase with words separated_by_underscores; and. That's what the pycodestyle tool (formerly called pep8) is there for: it can automatically check any Python file you send its way. $ pycodestyle hello.py hello.py:4:1: E302 expected 2 blank lines, found 1 $ echo $? 1 pycodestyle indicates which lines and columns do not conform to PEP 8 and reports each issue with a code. Violations of MUST statements in the specification are reported as errors — their error codes start with an E. Minor issues are reported as warnings — their error codes start with a W. The three-digit code following the first letter indicates the exact kind of error or warning. You can tell the general category of an error code at a glance by looking at the hundreds digit: for example, errors starting with E2 indicate issues with whitespace; errors starting with E3 indicate issues with blank lines; and warnings starting with W6 indicate deprecated features being used. I advise you to consider it and run a PEP 8 validation tool against your source code on a regular basis. An easy way to do this is to integrate it into your continuous integration system: it's a good way to ensure that you continue to respect the PEP 8 guidelines in the long term. Most open source project enforce PEP 8 conformance through automatic checks. Doing so since the beginning of the project might frustrate newcomers, but it also ensures that the codebase always looks the same in every part of the project. This is very important for a project of any size where there are multiple developers with differing opinions on whitespace ordering. You know what I mean. It's also possible to ignore certain kinds of errors and warnings by using the --ignore option: $ pycodestyle --ignore=E3 hello.py $ echo $? 0 This allows you to effectively ignore parts of the PEP 8 specification that you don't want to follow. If you're running pycodestyle on a existing code base, it also allows you to ignore certain kinds of problems so you can focus on fixing issues one category at a time. If you write C code for Python (e.g. modules), the PEP 7 standard describes the coding style that you should follow. Other tools also exist that check for actual coding errors rather than style errors. Some notable examples include: - pyflakes, which is also extendable via plugins. - pylint, which also checks PEP 8 conformance while performing more checks by default. It also can be extended via plugins. These tools all make use of static analysis — that is, they parse the code and analyze it rather than running it outright. If you choose to use pyflakes — which I recommend — note that it doesn't check PEP 8 conformance on its own — you would still pycodestyle to do that. That means you need 2 different tools to have a proper coverage. In order to simplify things, a project named flake8 exists and combines pyflakes and pycodestyle into a single command. It also adds some new fancy features: for example, it can skip checks on lines containing # noqa and is extensible via plugins. There are a large number of plugins available for flake8 that you can just use. For example, installing flake8-import-order (with pip install flake8-import-order) will extend flake8 so it also checks that your import statements are sorted alphabetically in your source code. flake8 is now heavily used in most open source projects for code style verification. Some large open source projects even wrote their own plugins, adding checks checks for errors such as odd usage of except, Python 2/3 portability issues, import style, dangerous string formatting, possible localization issues, etc. If you're starting a new project, I strongly recommend you use one of these tools and rely on it for automatic checking of your code quality and style. If you already have a codebase, a good approach is to run them with most of the warnings disabled and fix issues one category at a time. While none of these tools may be a perfect fit for your project or your preferences, using flake8 together is a good way to improve the quality of your code and make it more durable. If nothing else, it's a good start toward that goal. Many text editors, including the famous GNU Emacs and vim, have plugins available (such as Flycheck) that can run tools such as pep8 or flake8 directly in your code buffer, interactively highlighting any part of your code that isn't PEP 8-compliant. This is a handy way to fix most style errors as you write your code.
https://julien.danjou.info/code-style-checks-in-python/
CC-MAIN-2019-51
refinedweb
1,056
60.35
Details - Type: Bug - Status: Closed - Priority: Major - Resolution: Fixed - Component/s: findbugs-plugin - Labels:None - Environment:Hudson, Findbugs, PMD - Similar Issues: Description I think the 'contextHashCode' depends on the seven lines around the warning line (up 3, down 3, warning in the centre). But if I add one/several lines in the java code, the same number of new and fixed warnings appear, meaning that the same warnings in the current and old build can not be identified. In a simple case,the source is, package foo; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!!!" ); } public boolean equals(Object o){ return true; } } Then I add one line in the top of the file, which does not affect the code; But the build result tells that there are two new warnings and fixed warnings;(see pic1) And I find that the contextHashCode of the warnings in the current build and old builds are not the same.(see findbugs-warnings (1).xml and findbugs-warnings .xml) Attachments Issue Links - is duplicated by JENKINS-2968 Findbugs reports some warnings as resolved even if this is not true - Closed
https://issues.jenkins-ci.org/browse/JENKINS-6669
CC-MAIN-2017-39
refinedweb
193
59.84
Feature #17312closed New methods in Enumerable and Enumerator::Lazy: flatten, product, compact Description (The offspring of #16987, which was too vague/philosophical) I propose to add to Enumerable and Enumerator::Lazy the following methods: compact product flatten All of them can be performed with a one-way enumerator. All of them make sense for situations other than "just an array". All of them can be used for processing large sequences, and therefore meaningful to add to Lazy. Related issues Updated by Dan0042 (Daniel DeLorme) 10 months ago What would be the interaction between Array#flatten and Enumerable#flatten ? It's a big compatibility problem if flatten recursively applies to any Enumerable object within an array. x = Struct.new(:a).new(1) #=> #<struct a=1> [[[x]]].flatten #=> [x] currently Enumerable === x #=> true x.to_a #=> [1] [[[x]]].flatten #=> [1] would be a problem Updated by mame (Yusuke Endoh) 10 months ago I think Enumerable#compact is trivial and maybe useful. In regard to Enumrable#flatten, I agree with Dan0042 (Daniel DeLorme)'s concern. I think that it should flatten only Array elements, but it might look unnatural. I'm unsure if Enumerable#product is useful. Its arguments are repeatedly iterated, so the arguments should be Arrays? It would be good to separate tickets for each method, and a draft patch would be helpful for discussion. Updated by zverok (Victor Shepelev) 10 months ago mame (Yusuke Endoh) Dan0042 (Daniel DeLorme) Oh, you are right, starting to think from Enumerable::Lazy perspective I've missed a huge incompatibility introduced by flatten. mame (Yusuke Endoh) I'll split into several proposals+patches: Enumerable#compact, and, I am starting to think now, maybe Enumerator#flatten would make some sense. As for #product, I just added it for completeness (as a method which also can work with unidirectional enumeration), I can't from the top of my head remember if I needed it some time in the past. Updated by Dan0042 (Daniel DeLorme) 10 months ago I understand the thinking behind #flatten; if ary.flatten is possible then why not ary.to_enum.flatten? It should be isomorphic. But even with Enumerator the recursive aspect still represents a compatibility problem. So as long as the behavior of Array#flatten is not modified I think all this is trivial to implement: module Enumerable def compact(...); to_a.compact(...); end def product(...); to_a.product(...); end def flatten(...); to_a.flatten(...); end end edit: oops sorry, forgot the point was that Enumerator::Lazy#flatten should return a Enumerator::Lazy Updated by zverok (Victor Shepelev) 10 months ago But even with Enumerator the recursive aspect still represents a compatibility problem. I am not sure about its severity, though. I mean, Universe is big and sure somewhere in it there should be a code which has an array of enumerators and then does flatten on them... But I am not sure there is much of this code in the wild. I believe that this situation has the similar rarity class as the situation with code which does unless obj.respond_to?(:except) and will be broken by newly introduced Hash#except method... Like, every change is incompatibility for somebody, as points, but Enumerator#flatten seems quite innocent. So as long as the behavior of Array#flatten is not modified I think all this is trivial to implement: def flatten(...); to_a.flatten(...); end Note that this ticket is a follow-up of #16987. What I interested in, is more usages for .lazy, and eager implementation of Enumerator::Lazy#flatten is definitely a no-go. So, I actually could propose just Enumerator::Lazy#flatten, but it seems quite weird that lazy enumerator can be flattened, while regular one can't. Updated by p8 (Petrik de Heus) 10 months ago I was really suprised that #last isn't implemented in Enumerable while #first is. Updated by zverok (Victor Shepelev) 10 months ago I was really suprised that #lastisn't implemented in Enumerable while #firstis. It is natural. That's because Enumerable is "uni-directional" (it is not guaranteed that you can iterate through it more than once, and there is no way to go back). Imagine this: lines = File.each_line('foo.txt') lines.last # -- if it worked, ALL the file is already read here, and you can't do anything reasonable with it Also, last is "intuitively" cheap ("just give me last element, what's the problem?"), but as Enumerable relies on each, and each only, Enumerable#last would mean "go through entire each till it would be exhausted, and give the last value", which might be very pricey. All the methods I am trying to propose are compatible with uni-directional #each Updated by p8 (Petrik de Heus) 10 months ago zverok (Victor Shepelev) Thanks for the explanation. That makes a lot of sense! Updated by matz (Yukihiro Matsumoto) 10 months ago - Related to Feature #16987: Enumerator::Lazy vs Array methods added Updated by matz (Yukihiro Matsumoto) 10 months ago My opinion for each proposed method. compact- OK, I can imagine use-cases too product- Negative; I concern about arguments (array or enumerable) flatten- Negative; I concern about types of elements (array of enumerable) If you want product and flatten in Enumerable, submit separate issues to persuade me. Matz. Updated by zverok (Victor Shepelev) 10 months ago PR for #compact: Updated by nobu (Nobuyoshi Nakada) 9 months ago - Status changed from Open to Closed Applied in changeset git|68ea7720b367fe84da601cdbc61cb0d651c3221b. NEWS: [Feature #17312] [ci skip] Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/17312
CC-MAIN-2021-39
refinedweb
911
53.92
You define a struct as follows: struct name { //variables go here }; //don't forget this semicolon! When you define a struct, you are defining your own variable type. You can declare variables with the the struct type as follows: struct name variable; It's just like you would declare an int, or any other type of variable. The variables in a struct are called members, look at this struct definition: struct intfloat { int a; float b; }; This is a very simple struct with an integer, a, and a floating point number, b. Let's say you declare the struct like this: struct intfloat test; To access a member from the test variable, you must use the dot operator: test.a=6; This sets the member a as the number 6. You can do the same thing with member b: test.b=1.5; This sets b as 1.5 because b is a floating point number. Typedef is a good way to save a lot of typing. It gives a data type a new name. You can do this with the struct definition: typedef struct { int a; float b; } intfloat; When using a typedef, you don't need to use struct for every variable you declare, just do this: intfloat test; If you haven't used pointers before, please read this tutorial before moving on. When you declare structs as pointers, you have to use the arrow operator to access members. Let's assume we already defined intfloat with a typedef, just like above: intfloat test; test.a=5; test.b=4.3; intfloat *pointer; pointer=&test; printf("%d, %f\n", pointer->a, pointer->b);This code will print out: 5, 4.300000 The arrow operator is what dereferences the pointer members. Here is an example in C that uses structs to show stock statistics: #include <stdio.h> typedef struct { char *name; float value; float change; } stock; stock setval(char *name, float value, float change) { stock temp; temp.name=name; temp.value=value; temp.change=change; return temp; } void printv(stock temp) { printf("%s stats:\nStock value is:%f, Stock change is:%f\n", temp.name, temp.value, temp.change); } int main() { stock google=setval("GOOG", 591.50, 2.48); printv(google); stock redhat=setval("RHT", 27.66, 0.53); printv(redhat); return 0; } When using structures, it is usually a good idea to have functions that make it easy to handle them. My setval function sets the statistics, my printv function prints out the stock statistics. As always, feel free to post suggestions, questions, and positive feedback. Remember, +rep is appreciated.
http://forum.codecall.net/topic/52370-using-structures/
CC-MAIN-2019-51
refinedweb
432
72.97
Multiple dispatch Project description A relatively sane approach to multiple dispatch in Python. This implementation of multiple dispatch is efficient, mostly complete, performs static analysis to avoid conflicts, and provides optional namespace support. It looks good too. See the documentation at - Supports namespaces with optional keyword arguments - Supports variadic dispatch What this doesn’t do - Diagonal dispatch a = arbitrary_type() @dispatch(a, a) def are_same_type(x, y): return True - Efficient update: The addition of a new signature requires a full resolve of the whole function. This becomes troublesome after you get to a few hundred type signatures. only the small six library as a dependency. It is, in short, a light weight dependency. License New BSD. See License file.* 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/multipledispatch/
CC-MAIN-2019-18
refinedweb
145
50.02
Hello sir.. i am a beginner in C++.. how to determine if the input is not an integer.. thnx in advance.. Printable View Hello sir.. i am a beginner in C++.. how to determine if the input is not an integer.. thnx in advance.. What have you tried? #include <cctype> has a function for that called isdigit(). Here's an example of it. More information about this header can be further read here:More information about this header can be further read here:Code: if(isdigit(a)) cout << "digit" << endl; else cout << "character" << endl; cctype (ctype.h) - C++ Reference You can also just attempt to input a number and test whether this returns true. Like if(cin>>a) note: It doesn't really return true. It will just evaluate to true. Code: cin>>input; for(int x=0; x<strlen(input); x++) { if( (int) input[x] < (int) '0' || (int) input[x] > (int) '9' ) ) { cout<<"Not a numerical input"; break; } } like_no_other, you should indent your code properly. It would help if you actually showed the declaration of input (and it looks like your code will be vulnerable to buffer overflow). Chances are, all that casting is unnecessary and the check is more descriptively done with isdigit() anyway. Yes, you're right, it is faulty.He should definately use isdigit() , but I think he could learn more by giving him an explicit way to check his input other than "i_do_all_the_work_for_you" function. Code: char input[20]; cin.getline(input, 19, '\n'); bool IsInt=1; for(int x=0; x<strlen(input); x++) { if( (int) input[x] < (int) '0' || (int) input[x] > (int) '9' ) ) { IsInt=0; break; } } That would be better written as: EDIT:EDIT:Code: char input[20]; cin.getline(input, sizeof(input), '\n'); bool IsInt = true; for (size_t x = 0, n = strlen(input); x < n; ++x) { if (input[x] < '0' || input[x] > '9') { IsInt = false; break; } } Ah, but I notice that this algorithm does not correctly handle the input of an empty string. >> He should definately use isdigit() I disagree. The operator>> used with cin automatically determines if input is an integer or not. There's no need for you to re-implement what was already done. Won't just cin.fail() work if the variable is defined as an integer? It seems to me that we now have x == 1 iff the user didn't enter a valid integer. And you need no additional library or anything.It seems to me that we now have x == 1 iff the user didn't enter a valid integer. And you need no additional library or anything.Code: int Var; bool x; cin << Var; x = cin.fail(); Yes, that's what we're talking about when we say to use if(cin>>a). The return value of cin >> a evaluates to false if an integer was not read in (and the failbit is set). @laserlight:i don't follow, what was wrong with my code? Quote: Originally Posted by like_no_other - If the input is an empty string, your code would treat it as a valid integer. - getline() should have been called with 20 instead of 19 as the second argument (but then 20 was arbitrary in the first place, so this is a minor point). - strlen() should only be called once rather than on each iteration. - The casts to int are unnecessary. - The code needs to be properly and consistently indented. >> what was wrong with my code? Beyond what laserlight stated, your code sets IsInt to false on valid integers and true on invalid integers. True, those cases (negative numbers or overflow) might be rare depending on what you're using it for, but you don't know what the OP is using this for so I'd recommend the built-in capabilities that handle end cases better. thnx to all of u guys.. and sori for the late reply... i used "if (cin>>a)" and it works but when i enter any number that has a decimal like 2.35 or 13.43 etc.. it treats as an integer too why? AFAIK ther is no decimal in integer value.. thnx in advance and sori for my english..
http://cboard.cprogramming.com/cplusplus-programming/115677-determine-users-input-printable-thread.html
CC-MAIN-2014-41
refinedweb
694
75.5
This site uses strictly necessary cookies. More Information So i am creating my second game and I want this game to be finished. I am creating a 3d Game. My player is a stationary object and he is looking at a cube. So the cube is on the ground and the cube is changing colors from red to green. I want to make my player lose if he clicks on the cube while the color of the cube is red. I Have been trying for ages and I can't find a fix to this problem. I'm using raycasts because i think this will be the easiest way but i just can't get the script to work. I hope that is all the information i needed to give. Im open to all suggestions on how to do this without raycasts and with something else. Thanks. in the "changing colors" , is a simple swap of red to green or is there a blending? If simple swap, ins$$anonymous$$d of swapping colors maybe swap identical cubes? The green cube and red cube alternating ins$$anonymous$$d of colors. Then raycast can get the name of the object and if gets the red cube name he loses Answer by silvematt · May 22, 2020 at 09:06 PM Hello. You can do a simple thing like this: public class CubeStatus : MonoBehaviour { public bool isGreen = false; void SwapColor(bool green) { // Change color material isGreen = green; } } In this way you've saved the state of the cube. Where you do the Raycast, add a reference for the CubeStatus component: public class RaycastShooter : MonoBehaviour { [SerializeField] CubeStatus status; // Assign it in the inspector public void Shoot() { RaycastHit hit; if (Physics.Raycast(rayOrigin, forwardVect, out hit, range)) { if (hit.transform.CompareTag("TheCube")) { if (status.isGreen) // we've hit good else // game over } } } } Look that in this case the Cube must have the tag "TheCube", otherwise it will not pass the if condition. Answer by dahiyabunty1 · May 23, 2020 at 11:22 AM maybe you try if(hit.gameobject.meshrender.sharedmaterial.color == color.green) { //do stuff } Script doesn't work. It gives me an error. Error CS1061 'GameObject' does not contain a definition for 'meshrender' and no accessible extension method 'meshrender' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?) Answer by C4p3erx · May 23, 2020 at 11:48 AM Thank you both for your answers here :). @silvematt @dahiyabunty1 Setting booleans is such a obvious thing to do idk why I didn't do it tho:/. I will try both solutions today and I will let you know what works for me. I have a problem with the first script tho. So on the first script when I change the color of the cube won't it stay the same color all the time? Right now Im using coroutines for the color changing on the cube beacuse I want it constantly to be changed not only one time. The second script is 318 People are following this question. How to shoot with a raycast? 2 Answers Camera switch between child back to main camera issue 2 Answers Unity 3D: How to make the gameobject speed increase continuously on tapping quickly? 1 Answer setting a bool on another object's animator by player's raycast 2 Answers i am making an increment of one when user clicks a game object, trying to decrement the counter if the same game object is clicked again 1 Answer EnterpriseSocial Q&A
https://answers.unity.com/questions/1733671/i-need-help-with-raycasts-and-with-color-of-gameob.html
CC-MAIN-2021-43
refinedweb
591
71.14
PHP Programming/Nuts and Bolts Contents The Examples[edit] Example 1 - Basic arithmetic operators[edit] This example makes use of the five basic operators used in mathematical expressions. These are the foundation of all mathematical and string operations performed in PHP. The five mathematical operators all function identically to those found in C++ and Java <?php $x = 25; $y = 10; $z = $x + $y; echo $z; echo "<br />"; $z = $x/$y; echo $z; echo "<br />"; $z = $y*$y*$x; echo $z - 1250; echo "<br />"; ?> 35<br />2.5<br />1250<br /> 35 2.5 1250 echo "<br />"; 352.51250 This is of course not the desired result. There are two code options that perform the opposite of the assign (=) operator. The keyword null should be used for variable nullification, which is actually used with the assign (=) operator in place of a value. If you want to destroy a variable, the unset() language construct is available. $variable = null; or unset($variable); Example 2 - String concatenation[edit] This example demonstrates the concatenation operator ( .), which joins together two strings, producing one string consisting of both parts. It is analogous to the plus ( +) operator commonly found in C++ string class (see STL), Python, Java, JavaScript implementations. $string = $string . " " . "All the cool kids are doing it."; $string(that is "PHP is wonderful and great.") to the literal string " All the cool kids are doing it." and assigns this new string to $string. <?php $string = "PHP is wonderful and great."; $string = $string . " " . "All the cool kids are doing it."; echo $string; ?> PHP is wonderful and great. All the cool kids are doing it. As we all know, or for those new to programming will soon find it, programmers are always searching for "tighter code". Simply put, we pride ourselves in doing the most work with the fewest keystrokes. With that in mind, here's a trick that can save those precious keystrokes: concatenate and assign at the same time. It's easy. Let's take the same example as above. <?php $string = "PHP is wonderful and great."; $string .= " " . "All the cool kids are doing it."; echo $string; ?> PHP is wonderful and great. All the cool kids are doing it. You just saved 8 keystrokes with the exact same output. Big deal? Imagine having to do that with 100 lines of template code like I did recently. Yes, it's a big deal. By the way, if you change the implementation without changing the output, that's known as refactoring. Get comfy with that term. You'll be using it a lot. See more examples of compound assignments below. Example 3 - Shortcut operators[edit] This snippet demonstrates self-referential shortcut operators. The first such operator is the ++ operator, which increments $x (using the postfix form) by 1 giving it the value 2. After incrementing $x, $y is defined and assigned the value 5. The second shortcut operator is *=, which takes $y and assigns it the value $y*$x, or 10. After initializing $z to 180, the subsequent line performs two shortcut operations. Going by order of operations (see manual page below), $y is decremented (using the prefix form) and divided into $z. $z is assigned to the resulting value, 20. <?php $x = 1; $x++; echo $x . " "; $y = 5; $y *= $x; echo $y . " "; $z = 180; $z /= --$y; echo $z; ?> 2 10 20 <?php $x = 1; $x = $x + 1; echo $x . " "; $y = 5; $y = $y*$x; echo $y . " "; $z = 180; $y = $y - 1; $z = $z/$y; echo $z; ?> New Concepts[edit] Operators[edit] An operator is any symbol used in an expression used to manipulate data. The seven basic PHP operators are: =(assignment) +(addition) -(subtraction) *(multiplication) /(division) %(modulus) .(concatenation) In addition, each of the above operators can be combined with an assignment operation, creating the operators below: +=(addition assignment) -=(subtraction assignment) *=(multiplication assignment) /=(division assignment) %=(modulus assignment) .=(concatenation assignment) These operators are used when a variable is added, subtracted, multiplied or divided by a second value and subsequently assigned to itself. $var = $var + 5; and $var += 5; There are also increment and decrement operators in PHP. ++(increment) --(decrement) These are a special case of the addition and subtraction assignment operators. $var = 0; $var += 1; echo "The incremented value is $var.\n"; $var -= 1; echo "The decremented value is $var.\n"; The incremented value is 1. The decremented value is 0. While this is perfectly legal in PHP, it is somewhat lengthy for an operation as common as this. It can easily be replaced by the increment operator, shortening the statement. $var = 3; $var++; echo "The incremented value is $var.\n"; $var--; echo "The decremented value is $var.\n"; The incremented value is 4. The decremented value is 3. For a more in-depth overview of PHP's operators, including an explanation of bitwise operators, refer to the manual link below. Precedence[edit] Precedence determines the priority given to certain operators to be performed earlier in a statement. If an operator has higher precedence, it doesn't mean that it is of greater importance; the opposite can often be true. - Associativity When multiple operators occur that have the same precedence (whether multiple instances of the same operator or just different operators with the same precedence), it becomes important to consider the associativity: whether right (to left), left (to right), or non-associative. - Examples where associativity is irrelevant In certain cases (as in the example below), especially where the same operator is present, the associativity may make no difference to the result. The following... $a = 5*2*3*4; // Equals 120 ...with its left associativity is equivalent to: $a = (((5*2)*3)*4); // Equals 120 However, in this case, right associativity would have produced the same result: $a = (5*(2*(3*4))); // Would also equal 120 - Examples where associativity is relevant in PHP (but not mathematically) In mathematics, it may be considered irrelevant in which direction a calculation is performed for operators with the same precedence. For example, the following... $a = 5+3-2+8; // Equals 14 ...is equivalent to this (left associative) statement: $a = (((5+3)-2)+8); // Equals 14 And, if this were considered according to human conventions in mathematical calculations, the following equivalent right associative expression would produce the same result: $a = (5+(3+(-2+8))); // Would also equal 14 However, since we are dealing with a linear computer language that doesn't know to convert the "2" into a negative number and group it with the "8" before adding it to the "3" (and then the "5"), if PHP were to perform the following expression in a strict right associative manner, the following (mistaken) outcome would occur: $a = (5+(3-(2+8))); // Would equal -2 Thus, the associativity is relevant and should be memorized (though it is generally good practice to make one's groupings explicit anyhow—both to avoid mistakes and to improve readability for others looking at the code). Similar problems occur with multiplication and division. Although with human convention, all adjacent multiplication and division groups would have the multiplication performed at the numerator level and the division at the denominator level, the PHP interpreter does not know to do this, so it is bound to set the left(-to-right) convention when explicit groupings (via parentheses—that have highest precedence) have not been made: $a = 5*4/2*3; // Equals 30 This is equivalent to the left associative: $a = (((5*4)/2)*3); // Also equals 30 However, as with the addition/subtraction example above, performing this by right associativity (in a strictly reverse linear fashion) does not produce the same (intended) result: $a = (5*(4/(2*3))); // Equals 3.33333 Newline and Other Special Characters[edit] Both of the below examples make use of the newline character (\n, \r\n or \r, basing on the OS) to signify the end of the current line and the beginning of a new one. echo "PHP is cool,\nawesome,\nand great."; PHP is cool, awesome, and great. Notice: the line break occurs in the output wherever the \n occurs in the string in the echo statement. However, a \n does not produce a newline when the HTML document is displayed in a web browser. This is because the PHP engine does not render the script. Instead, the PHP engine outputs HTML code, which is subsequently rendered by the web browser. The linebreak \n in the PHP script becomes HTML whitespace, which is skipped when the web browser renders it (much like the whitespace in a PHP script is skipped when the PHP engine generates HTML). This does not mean that the \n operator is useless; it can be used to add whitespace to your HTML, so if someone views the HTML generated by your PHP script they'll have an easier time reading it. In order to insert a line-break that will be rendered by a web browser, you must instead use the <br /> tag to break a line. Notice: The newline is \n for Linux/Unix-based systems, \r\n for Windows and \r for Mac's. echo 'PHP is cool,<br />awesome<br />and great.'; The function nl2br() is available to automatically convert newlines in a string to <br /> tags. $string = "This\ntext\nbreaks\nlines."; $string = nl2br($string); print $string; This<br /> text<br /> breaks<br /> lines. This text breaks lines. Other special characters include the ASCII NUL (\0) - used for padding binary files, tab (\t) - used to display a standard tab, and return (\r) - signifying a carriage return. Again, these characters do not change the rendering of your HTML since they add whitespace to the HTML source. In order to have tabs and carriage returns rendered in the final web page, &tab; should be used for tabs and <br /> should be used for a carriage return. Input to PHP[edit] PHP has a set of functions that retrieve input. If you are using standard input (such as that from a command-line), it is retrieved using the basic input functions: $mystring = fgets($stdin); Or: $stdin = fopen('php://stdin', 'r'); // opens standard input $line = fgets($stdin); // reads until user presses ENTER Web servers[edit] On Web servers, information sent to a PHP app may either be a GET operation or a POST operation. For a GET operation, the parameters are sent through the address bar. Parameters within the bar may be retrieved by using accessing $_GET['parameter']. On a POST operation, submitted input is accessed by $_POST['parameter']. A more generic array, $_REQUEST['parameter'] contains the contents of $_GET, $_COOKIE.
http://en.wikibooks.org/wiki/PHP_Programming/basics
CC-MAIN-2015-22
refinedweb
1,745
55.13
» Publishers, Monetize your RSS feeds with FeedShow: More infos (Show/Hide Ads) With the lack of posts and everything, people have been asking me what I have been up to. Among other things, I am updating my SharePoint development book for the 2010 release. The new title will be Pro SharePoint 2010 Solution Development. Just like the last book, you can expect lots of examples that incorporate Microsoft Office 2010, Visual Studio Tools for Office, Open XML, and of course SharePoint 2010. This is still a developer book meant to show patterns that devs can use in projects - not an introduction to SharePoint development. I've wrangled Chad Wach (another Microsoft SharePoint resource) to helping me with a few chapters. We are nearly done with the first drafts of the chapters, but plan to update them as we get RTM bits. The book should be out by TechEd - sometime early summer. It is already posted on amazon.com for pre-order. You will notice a lot of the chapters have the same title as some of the solutions in the last book. I can guarentee you that there is a lot new here. Even in cases where the goal of the solution is the same, we were able to take it much father with less code given the improvements in the platform. Below is where the table of contents stands currently. The chapters in brackets are still being written and may change. I hope to have some webcasts for you soon of some of the solutions. 1 - Office Business Applications 2 - SharePoint 2010: Overview and New Features 3 - SharePoint Development with Visual Studio 2010 4 - Microsoft Office Overview for Developers 5 - [An Excel Services focused chapter] 6 - Merging SharePoint List Data into Word Documents 7 - Automating Document Assembly 8 - Extending PowerPoint to Build a Presentation Based on Site Content 9 - Building a Presentation Server-Side with a Web Part 10 - Surfacing Line-of-Business Data into Outlook 11 - [Site Provisioning Forms and Workflows] 12 - Rapid SharePoint Application Development using Access 13 - Using Visio Services to Visualize Data 14 - [Building Mashups] 15 - Realizing the Vision Most of day 1 was the keynotes. Got to love that the first demo was for the developers in the room. Really like that the definition of SharePoint has become more broad then simply a collaboration platform. The new pie slide simply stated Next Generation Platform. I sat in all the keynotes and then mostly IT Pro sessions. This is because I am already pretty deep in the dev stuff. I went to IT Pro Overview, and the 2 part sessions on Architecture done wy the SharePoint 911 guys which were very entertaining. Some favorite lines: Co-authoring is the feature that lets you watch other people do your work... If you write a bad web part, my sharepoint server will hunt you down and shoot you... I really like all the powershell stuff done by Shane and Todd. The biggest thing to take out of this is make get-help your friend and don't forget tabbing can auto complete not only commands, but also parameters. I'll be doing more blogging once I get back with a lot of details as well as the dev work I have been doing... finally nice that the NDA has been lifted. Was working on a proof of concept today and ran across an interesting error when trying to get the MOSS server to talk to RMS. Since this is just in a lab, the MOSS central administration web app pool was running as Network Service. When I chose to specify the RMS server, the error was that it was found, but that the local machine account did not have access. Turns out, you need to set a few permissions on one of the asmx web service files on the RMS server. In my case the RMS Server was on a domain controller- installed with the default options. To solve the problem, I simply went to c:\inetpub\wwwroot\_wmcs\certification and modified the permissions of ServerCertification.asmx. I added the computer account of the MOSS server, and the app pool identity of my other web applications, as well as the AD RMS Service Group. That fixed it. Here is another post that has some pretty pictures and more explanation: made it onto this blog. So I'll just post the deck. Enjoy! I’ve been updating some of my demos for the upcoming DC SharePoint Best Practices Conference (). Basically, I have a session that shows different approaches to common document generation scenarios that customers have expressed an interest in. I will show why you want to be building these out with SharePoint and why you want to use some of the latest tools to help. These tools are things like the new Visual Studio Extensions for WSS, the new Open XML SDK, and the Word Content Control toolkit. Some of the demos in my session (on the first day of the conference) were solutions that I first proposed in my book: Pro SharePoint Solution Development. Those solutions were built on (gasp) VS.NET 2005 and the Packaging API which was brand new back then. For those of you who have been looking for an update, here you go. Here are some download links to updated projects: A web part for building a PowerPoint presentation server-side: A new feature that merges SharePoint list data into a Word document template: A new feature that supports the splitting of a document into discrete sections and then merged back: Just a reminder that all of these solutions are really just demo code and should have a lot more error handling and testing. But it gives you a really good starting point for your own solutions. The biggest difference with these new projects is the use of the Open XML SDK which gives you an object model to work with instead of coding nasty XML. Here is an example of an old code snippet that opened up a PowerPoint template and located the slide parts: Using pptPackage As Package = Package.Open(fileStream, FileMode.Open, FileAccess.ReadWrite) ' Get the main document part (presentation.xml). For Each relationship As PackageRelationship In pptPackage.GetRelationshipsByType(documentRelationshipType) documentUri = PackUriHelper.ResolvePartUri(New Uri("/", UriKind.Relative), relationship.TargetUri) documentPart = pptPackage.GetPart(documentUri) ' There is only one document part. Get out now. Exit For ' Manage namespaces to perform Xml XPath queries. Dim nt As New NameTable() nsManager = New XmlNamespaceManager(nt) nsManager.AddNamespace("p", presentationmlNamespace) nsManager.AddNamespace("a", drawingmlNamespace) ' Iterate through the slides and extract the title string from each. Dim xDoc As New XmlDocument(nt) xDoc.Load(documentPart.GetStream()) Dim sheetNodes As XmlNodeList = xDoc.SelectNodes("//p:sldIdLst/p:sldId", nsManager) And see how this changes with the new SDK: Dim presDoc As PresentationDocument = PresentationDocument.Open(fileStream, True) Dim presPart As PresentationPart = presDoc.PresentationPart Dim presentation As DocumentFormat.OpenXml.Presentation.Presentation = presPart.Presentation If (Not (presentation.SlideIdList) Is Nothing) Then ' Get the title of each slide in the slide order. For Each slideId As SlideId In presentation.SlideIdList.Elements(Of SlideId)() Just a reminder that you need these add-ons to VS.NET 2008 to work with these projects: Visual Studio Extensions 1.3 March Preview: Open XML Format 2.0 SDK April Preview: As promised in my earlier video demo, here is a web part that I quickly wrote to view the claims of a user when they are authenticating to the SharePoint site using a Security Token Service such as Geneva Server. There are some important sections in the code. First is the check to see if a user is actually has a claims principal: IClaimsPrincipal icp = null; IClaimsIdentity claimsIdentity = null; public ViewClaimsWebPart() { try { icp = this.Context.User as IClaimsPrincipal; claimsIdentity = (IClaimsIdentity)icp.Identity; } catch { } } protected override void CreateChildControls() { try { if (claimsIdentity != null) And then just collecting the claims into a dataset: ClaimsInfo oData = new ClaimsInfo(); foreach (Claim claim in claimsIdentity.Claims) { oData.Claims.AddClaimsRow(claim.ClaimType, claim.Value); } Here is a link where you can download the sample. Just be mindful it is a sample. Just one note that this project was built using the new Visual Studio Extensions for WSS 1.3 March CTP. You can get that here if you haven’t tried it out. Much better than previous releases – so give it a try. No this is not a post on anything SharePoint 2010 related. I get asked this question, quite a bit… It usually goes something like: I have a SharePoint site and when the user clicks on a Word document, the file is shown in the Internet Explorer viewer and not in MS Word. I had to track this down once upon a time with good old SharePoint 2003 so I can usually answer that it is a setting on the desktop that determines whether or not the rich client app will launch. At a recent conference, an attendee pushed for a little more detail and it took me a while to find the KB article. Here it is: As you can see there is an interactive way to set it through some very hidden settings screens as well as through the registry. The registry approach published via a group policy would be the way to go if a massive amount of users need to have the change made. I put together a little video demo of using Geneva Beta 2 stuff with MOSS 2007. You can get these VMs using the links from the previous post, but it is an awful lot to download and setup. So I thought a video might be appealing.: There is only 1 error that I found going through the docs. On page 87, the Url should be. And I would change the demo a bit and only add the RMS protection to the confidential documents.!:: As usual, the code is for learning purposes only! All the usual caveats about not supporting it, etc all apply.: <add assembly="System.Web.Silverlight, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> I still haven't gotten to my previous projects, but at least Hello World works now :) You do. Mike Gannotti has invited you to attend an online meeting using Live Meeting. Join the meeting. Audio Information Computer Audio To use computer audio, you need speakers and microphone, or a headset.) 500-6738 Participant code: 121607: 2KN7GD Entry Code: t}k9d,(>N Location: If you still cannot enter the meeting, contact supportNotice Microsoft Office Live Meeting can be used to record meetings. By participating in this meeting, you agree that your communications may be monitored or recorded at any time during the meeting.: By the way, they caked make up on me for the video... I was preparing for the upcoming conference and wanted to demo some of the new tools coming for SharePoint. Often I have heard the customer's IT department talk about finding rogue SharePoint installations and getting better metrics on how these servers were being used, so I thought I would spend some time with the SharePoint Asset Inventory Tool. This tool is currently in Beta, but is publicly available through Microsoft's Connect site. It is basically a scanning solution that looks for SharePoint servers and dumps metrics about them into a SQL store with some nice SQL Reports. I installed the tool, only to get an error half-way through the scan. The error was something about a malformed SQL statement near a ';' and an ELSE statement. Unfortunately, I had nothing in the repository to even show as part of the demo. So the hunt began... Looking through log files, I found the offending stored procedure to be dbo.SP_INSUPD_DEVICES_PORT_NUMBER. This proc was in the SATAssets database on my SQL server. If you modify this proc, you will notice that it builds a dynamic SQL string. In this string, one of the variables is not covered by two single quptes ''. So ... IF('' + PORT_NUMBER + '' IS NOT NULL) notice that I added the 2 ''. This proc and the SATAssets DB seem to be recreated each time you run a new scan after the initialization screen. Start the wizard, wait for the initialize prompt to go away, modify the proc, and then it works. I also am a big fan of host headers in my dev environments. I noticed I also had to make sure that I had a web application that resolved the the server name on port 80 (or one of the ports it was looking for) to get my results. I've also posted this workaround in the forums so hopefully you'll have some luck before the next drop happens on the Connect beta site. how a Visual Studio Tools for Office add-in for PowerPoint can call SharePoint's web services to retrieve content and build slides. The second approach shows how this can be done completely server side by manipulating the new Open XML formatted files. Both demos usually get people excited; I hope you enjoy them. The code for these is available on Apress' web site since they are from my book: Pro SharePoint Solution Development. This book is mentioned a lot in the blog so it should be easy to find more info if you are interested. Sorry for the background noise in the video. The HVAC system here is running full strength on this cold day. Also, I will be presenting at the upcoming SharePoint conference in Seattle in March. My topic will be "Enforce Governance by Provisioning Sites through Workflows" or something like that. Stop by and say hi. I may have a few books to hand out. Just an update: Ian at wssdemo.com has hosted this video on a streaming server which has much better quality: Video: Building Presentations from SharePoint Content
http://reader.feedshow.com/show_items-feed=f7026661b52fbbd7e5a6ceab8e52229e
CC-MAIN-2014-42
refinedweb
2,300
63.59
Created on 2011-05-08 08:53 by acooke, last changed 2016-08-24 13:46 by ppperry. Hi, In general, registering a class with an ABC is equivalent to making it a subclass (isinstance and issubclass are patched through ABCMeta). However, this does not work for exceptions (see example below, where exception is not caught). This doesn't seem terribly surprising to me - I imagine that checking would slow down exception handling - but I couldn't find any documentation (and posting on c.l.p didn't turn up anything either). So I thought I would raise it here - perhaps there is a possible fix (my obscure use case is that I have a backtracking search; backtracking occurs when a certain exception is encountered; making that exception an ABC and allowing existing exceptions to be registered with it allows the search to work with existing code without a wrapper that catches and translates exceptions that should trigger a backtrack). Or perhaps the docs could be extended. Or perhaps I've misunderstood something... Cheers, Andrew Python 3.2 (r32:88445, Feb 27 2011, 13:00:05) [GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from abc import ABCMeta >>> class RootException(Exception,metaclass=ABCMeta): pass ... >>> class MyException(Exception): pass ... >>> RootException.register(MyException) >>> try: ... raise MyException ... except RootException: ... print('caught') ... Traceback (most recent call last): File "<stdin>", line 2, in <module> __main__.MyException Scouting around the CPython codebase a bit, I speculate that the cause of this behavior is that PyErr_GivenExceptionMatches() in errors.c uses PyType_IsSubtype() [which simply walks a class's __mro__ checking for pointer equality] rather than PyObject_IsSubclass()/PyObject_IsInstance() [which are smart enough to consult __subclasscheck__()/__instancecheck__() if they exist]. Of course, the more important issue here is whether this behavior is intended or not. I surmise python-dev needs to have a discussion about it? Surveying the docs, the current behavior *is* /technically/ correct (in a suspiciously precise way) according to the Language Reference: : "For an except clause with an expression [...] the clause matches the exception if the resulting object is 'compatible' with the exception. An object is compatible with an exception if it is the class or a base class of the exception object" (which exactly describes what PyType_IsSubtype() checks for) The Tutorial is by contrast much more vague: : "if [the raised exception's] type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement." No definition of what it means for the types to "match" seems to be given. The documentation for ABCMeta.register() says that it makes the other class a "virtual subclass". That would make the ABC a "virtual base class". So whether the current behaviour is correct depends on whether you consider a "virtual base" to count as a base. From the reasoning behind the introduction of ABCs, it certainly sounds like it should count. Also, this is a feature that works correctly in Pyton 2.7, so could trip people up who are trying to move to Python 3. I agree it's a bug and should be fixed. It's too confusing that there would be two slightly different interpretations of isinstance/issubclass where the isinstance() and issubclass() would be using the extended interpretation but the except clause would use the narrow interpretation. The exception matching done by the except clause ought to be explainable in terms of issubclass/isinstance. I think being able to catch exception with ABCs is esssentially useless. The originally stated "usecase" can be simply solved by putting classes into a tuple and putting that in the except clause. In general, the whole abc machinary causes lots of code which expects instance and subclass checks to be side-effect free to be able to execute arbitrary code, which creates messes. Perhaps ABCMeta could raise a UserWarning when creating an Exception subclass? perhaps it could just work in a simple, consistent way? in my original report i wondered whether there was a significant performance hit. but so far the objections against fixing this seem to be (1) a lawyer could be convinced the current behaviour is consistent with the docs (2) python 3 should remain compatible with python 2 (3) abcmeta is the sucksorz. those don't seem like great arguments against making it just work right, to me. >. Basically, someone needs to produce a patch and we can go from there. I posted on python dev that this would slow exception checking considerably so that is a concern. As for possible bugs, this has been working in the 2 branch for a while now, so I don't think that is the biggest issue. As for possible use cases, writing a wrapper around backend, each with its own exceptions and still being able to catch a 'base' exception in your code while still having the ability to catch specific exceptions, without doing awkward stuff like looking at __cause__ (let alone that you have to reraise that in 2 for code that has to run on both branches). Yes, you could patch the exceptions' bases but that is what Abc was created to avoid. Sorry for the mistakes and weird phrasing, posting this off my phone. I have a patch, with tests, but no Internet on my computer so going out, will post it when I get back/my Internet comes back Benjamin: if you are after a use case for this feature, see In Django, there are multiple database backends, each of which currently catch the adapter's DatabaseError and reraise it as Django's DatabaseError so that Django code can handle database errors in a standard way without having to care about which backend they came from. Unfortunately, this loses some information from the exception. My idea for solving that bug was to make Django's DatabaseError an ABC. By registering the various adapter's DatabaseErrors with the ABC, it would not be necessary to catch and reraise them in the backends while still preserving the ability to catch the generic errors in the core. This works fine in Python 2.x, but it was pointed out that it would cause compatibility problems when porting to Python 3.2. As promissed the patch. It doesn't break any tests, and it passes the ones I added. I have a pybench one as well, which even though trivial, does point to the fact that there is a degradation in performance, but not sure it's worth posting here. When does the performance hit occur? If it is only when an exception has been raised, and its own class is not listed by the except clause, then I personally wouldn't worry about it; tracing the MRO *could* get arbitrarily long already; it just doesn't in practice. The same should be true of virtual subclassing. On the other hand, if it adds another module or three to the required startup set, that might be a concern... The).. That just leaves the complexity argument associated with running arbitrary code at an unexpected place in the eval loop, and for that the tests in the patch would need to be strengthened with some pathological examples like: - __subclasscheck__ raising an exception - __subclasscheck__ raising and then suppressing an exception - __subclasscheck__ invoking the garbage collector - __subclasscheck__ hitting the recursion limit - __subclasscheck__ provoking MemoryError The games the current patch already has to play with the recursion limit also bother me. However, if an alternate approach could be found that avoids the adjustment of the recursion limit in the eval loop, that also sensibly survived the kinds of arbitrary code execution torture tests I mention above, then I'd be far more sanguine about the idea of actually resolving the discrepancy rather than formalising it as part of the general fact that the exception hierarchy isn't as flexible as most of the rest of the language. >. I think that the performance question can only really be answered by running (micro-)benchmarks here. Can someone please point out why do we have to do that dance with recursion limit? I've came upon this problem as well. I had some (bad) API I had to work with. It always raised the same exception with the only difference in the message. So I thought I could do something like this: def message_contains(msg): class _MyExc(object): def __instancecheck__(self, exc): return msg in exc.args[0] return _MyExc But after I tried it in number of different ways I found out that it's not possible. So here's another reason to change this behavior. Because context managers are closer to try/finally blocks than they are to exception handling, the class-based implementation for the contextlib.suppress API uses issubclass rather than emulating the CPython exception handling semantics: The exception checking in the unittest module is similarly based on issubclass: I'm planning to add the catch() and ExitLabel() context managers to contextlib2 this evening, and those too will be based on issubclass(). Perhaps as a near term thing, we should put an "implementation detail" notice somewhere in the language reference, pointing that it's the code using issubclass that is considered correct here, and CPython's exception handling that is considered out of line? A point on the safety/correctness front: I remembered we already run arbitrary code at roughly this point in the eval loop, as we have to invoke __iter__ to get the exceptions to check when an iterable is used in except clause. That means allowing the subclass check hooks to run here isn't as radical a change as I first thought. "I remembered we already run arbitrary code at roughly this point in the eval loop, as we have to invoke __iter__ to get the exceptions to check when an iterable is used in except clause." Are you sure? IIRC the except clause only accept exceptions and tuples of exceptions, not iterators. Ah, you're right - I found the example I was thinking of (Richard Jones's "Don't do this!" talk), and it was just demonstrating that the except clause accepts any expressions producing a tuple or BaseException instance, not that we call __iter__ at that point. And since we do identity checks for the exception type matching (rather than equality checks), it looks like all the avenues for arbitrary code execution while checking if an exception handler matches a thrown an exception are closed off. ) ISTM Nick meant that the exception that was raised can't cause arbitrary code execution. On Wednesday, October 1, 2014, Antony Lee <report@bugs.python.org> wrote: > > Antony Lee added the comment: > > ) > > ---------- > nosy: +Antony.Lee > > _______________________________________ > Python tracker <report@bugs.python.org <javascript:;>> > <> > _______________________________________ > Right, I had a specific concern related to the way the C level code works. On closer inspection, it turned out all the Python level code execution is complete by the time we reach the point I was worried about. I'm attaching a patch that works without changing the recursion limit, and adds some tests for pathological cases. Instead, PyErr_GivenExceptionMatches is changed so that if an exception was previously set, it is replaced by an exception that PyObject_IsSubclass raises. In that way recursion errors should be propagated properly. In exception matching, this means that exceptions (including recursion errors) from PyObject_IsSubclass are ignored. There is already an explicit test for this behavior in test_exceptions. This behavior *could* be changed if intended by introducing a variant of PyErr_GivenExceptionMatches that can set an exception even if none was set before, and calling that in cmp_outcome in ceval. New version including (I think) correct refcount handling. Clarifying some comments in this one. I'm worried about the runtime cost of this. Code like this is an extremely common idiom and should remain fast: try: x = d[key] except KeyError: # do something else Agreed. Since type has __subclasscheck__ (why I don't know) this might result in a slowdown since all checks have to go through calling it in PyObject_IsSubclass. Just noticed that given_exception_matches_inner can be simplified a bit since PyObject_IsSubclass already checks for tuples by itself. Quick microbenchmark: try: {}["a"] except KeyError: pass original tip: 1.35 usec with patch v3: 1.55 usec so it's about 15% slowdown for catching a simple exception on my machine. > Since type has __subclasscheck__ (why I don't know) Ouch, really? That means the PyType_IsSubtype path in PyObject_IsSubclass() is never taken? I think we should add a tp_subclasscheck slot to minimize the general cost of this. Also, try to see if there aren't redundant type / tuple checks along the way. OK, with these two patches (speedup and v4) I can't see a significant slowdown anymore. IsSubclass speedup patch now tracked in #22540. Can we move forward and land this patch? It seems to be working and for some reason it even makes that microbenchmark work faster. Does this introduce a slowdown when the type doesn't match? That is, clearly George's example: try: {}["a"] except KeyError: pass won't be slowed because the fast path will get an immediate hit. But what about: try: {}["a"] except TypeError: pass except ValueError: pass except KeyError: pass (or with the KeyError handler higher up the call stack). The fast path speeds up the handled case, but it doesn't seem like it would help the unhandled case (where it would need to check the slow path for each unhandled exception type one at a time). On rereading #22540, maybe that won't be an issue (in the common case where no custom metaclasses are used for the exceptions to be caught, it looks like maybe there is no slow path to traverse?). Still worth double checking. Note. In the current (v4) patch, it looks like there is an unneeded “allow_new_exception” parameter that is always set to zero. So maybe the patch needs more careful thought. Also I agree it needs documentation, what’s new, “changed in version 3.6”, etc. This question came up again recently over in #27814, in the context of a proposal to add an "unless" parameter to contextlib.suppress(). I declined the RFE mainly on the basis of API complexity, but I also noted you can get something comparable in the current API by using virtual subclassing to say "If a subclass of these, but not of these": So the status quo is currently giving us a slightly odd discrepancy between normal except clauses and code that emulates them via issubclass()
http://bugs.python.org/issue12029
CC-MAIN-2016-44
refinedweb
2,426
60.24
Import Statements in TypeScript: Which Syntax to Use Import Statements in TypeScript: Which Syntax to Use Importing packages, libraries, etc. is an important part of any developer's workflow. Read on to learn how to do this in TypeScript. Join the DZone community and get the full member experience.Join For Free TypeScript has multiple different syntaxes for imports. When should you use which? Most of the Time, the Module Exports Multiple Things There are two great ways to import from another module in TypeScript, when the module exports an object with properties. This is the common case. Import the whole module, giving it a name: import * as child_process from "child_process"; // then later... child_process.spawn(...); or pick the names you want to import: import { spawn } from "child_process"; // then later spawn(...); When the Module Exports Just One Thing This doesn't work when the module doesn't export an object with properties. Some modules export a function or a class instead. How can you know? Good question. You have to look at the module's code or look at examples. In this case, give the single exported thing a name: import boxen from "boxen"; // then later... // boxen happens to export a function boxen(...); How to Know What the JavaScript Module Exports The short answer. Use import boxen as "boxen"; In contrast, the npm page for chalk shows: const chalk = require('chalk'); console.log(chalk.blue('Hello world!')); Here, you can see that the thing it got from requiring boxen is being used as an object. Use import * as chalk from "chalk"; How to Know What * as myModule from "./myModule" or. This Other Weird Case I haven't hit this yet, but the docs say that sometimes from TS people do: export = Thing; to export just one thing instead of an object. In this case, you have to bring that in with: import thing = require("./Thing"); This seems to be for historical reasons for interop in ways you probably don't need, so let's not. Fall Back to JS You can always const thing = require("Anything"); just like in JS, but you won't get typing. You also won't get compile-time checking that the module is available. Sometimes that is what you want. Sometimes 'import' Means 'run' You can import a script for side effects only: import "./set_up_global_logging";. Published at DZone with permission of Jessica Kerr , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/import-statements-in-typescript-which-syntax-to-us?fromrel=true
CC-MAIN-2019-51
refinedweb
424
66.44
just follow the subversion installation instructions at the link above, you need lazy-pac-cli-devel too which follow the same steps as libpypac-devel, you'll get it by the same checkout, I'd be curious to see your implementation of this. There are a few different ways to do this if you are trying to do a "progress bar" type thing depending on what you are actually doing.]]> *xerxes hugs tmaynard very hard* that last stuff works beutifully, edit: if you feel lucky you can get the evidence on svn, more info here: Non curses version: import sys import time myStrings=["Pacman working ...","pAcman working ...","paCman working ...", "pacMan working ...","pacmAn working ...","pacmaN working ...", "pacman Working ...","pacman wOrking ...","pacman woRking ...", "pacman worKing ...","pacman workIng ...","pacman workiNg ...", "pacman workinG ..."] for eachString in myStrings: sys.stdout.write(eachString) sys.stdout.flush() sys.stdout.write("r") time.sleep(1) print("n") Enjoy!]]> sonix stuff doesn't seem to work, i will try tmaynards curses sollution also my function is beeing fed by another function so how do i deal with that? or should i have one curses function like tmaynards and use sleep()? Try this : import curses import time stdscr = curses.initscr() myStrings=["Pacman working ...","pAcman working ...","paCman working ...", "pacMan working ...","pacmAn working ...","pacmaN working ...", "pacman Working ...","pacman wOrking ...","pacman woRking ...", "pacman worKing ...","pacman workIng ...","pacman workiNg ...", "pacman workinG ..."] for eachString in myStrings: stdscr.addstr(0, 0, eachString,curses.A_REVERSE) time.sleep(1) stdscr.refresh() curses.endwin() Is this kinda what you are loooking for?]]> yes that is exactly what I'm saying. edit: Well atleast I didnt need anything to make it work in java... I dont know python so I cant really say if you need it or not.]]> are you saying that i don't have to use curses?]]> Sorry for writing it in java (dont really know python). anyway:: The curses part of pacmans "download printing" is printing the carriage return (ascii value 13) as a character to the end of each line until 100% download is reached.Then it prints linefeed (ascii 10) to change the line. In other words : you should be able to overwrite your prints if you supply a carriage return at the end (like in my java prog and pacman) if python doesnt do anything strange behind your back when you do a print. in python please, and i don't understand what you mean anyway,]]> Is this what you need ?(sorry for writing an example in your favourite language xerces2) public class JCurses { public static void main(String[]args) throws Exception{ String[] pacman = new String[]{ "Pacmanr", "pAcmanr", "paCmanr", "pacManr", "pacmAnr", "pacmaNr", "pacmann"}; for(String p:pacman){ System.out.print(p); Thread.sleep(1000); } } } all pacman does is a simple carriage return at the end. if python doesnt have a built in carriage return, just print its ascii value 13 as a character. (put the code in a file named JCurses.java compile it with "javac JCurses.java run it with "java JCurses") give me a few weeks and i'll do it, this curses stuff is not so easy to dig into, i just want to make oneliners, it shouldn't be like rocket science,]]> Problem is, I've never used ncurses in any programming language. :-P I just knew that pacman used it to get that one lie output (from passing comment Xentac made once), and I remembered that Python had a curses module. Its the best I could do on such short notice. Would you like to write my master's thesis? :-P Dusty]]> that looks like what i was looking for, couldn't you supply some code too now i have to rtfm also 'before' i start to code, Maybe? Dusty]]>
https://bbs.archlinux.org/extern.php?action=feed&tid=15174&type=atom
CC-MAIN-2017-17
refinedweb
622
69.62
A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login JavaRanch » Java Forums » Databases » JDBC and Relational Databases Author JAMon 2.1 and Monitoring SQL/JDBC steve souza Ranch Hand Joined: Jun 26, 2002 Posts: 862 posted Jul 10, 2006 21:39:00 0: 1) JAMon can monitor ANY Java interface. This can be any interface of your own creation or even interfaces that come with the JDK such as the JDBC interfaces (This is particularly useful). The syntax couldn't be simpler. Simpy pass ANY interface in the 'monitor(...)' method it will be monitored. If the monitor proxy is disabled then the original object is simply returned causing no run time performance impacts. Monitoring is quite fast though, and various levels can be enabled/disabled at runtime. import java.sql.*; import com.jamonapi.proxy.*; ... // After monitoring the interfaces, subsequent calls to the monitored object will track various statistics discussed below // This will also monitor all SQL, calls to the JDBC interfaces (Statements, PreparedStatements, CallableStatements and ResultSets) and any Exceptions that // they throw. Connection monitoredConnection = MonProxyFactory.monitor(connection); // You monitor your own custom interfaces the same way. MyInterface myMonitoredObject = MonProxyFactory.monitor (new MyObject()); 2) What type of monitoring does JAMon 2.1 do? All JAMon data can be viewed in the various JAMon web pages discussed below. All of the following can be enabled/disabled at runtime. 2.1) JAMon Summary statistics such as hits, time (avg/min/max/total/...), conncurency (what is currently running? what was the max running?...), and more. For example for all queries for any JDBC driver you can track how many times it was called, avg time, max time etc. Summary stats are kept for all methods on an interface, SQL, exceptions thrown and more. (see for examples) 2.2) SQL Details - The above tracks aggregate/summary statistics. JAMon can also track the most recent N (configurable) SQL statements that have run. This capability will show 1) The query, 2) When the query ran, 3) How long the query took, 4) If the SQL was called via a PreparedStatement how many times has that PreparedStatement been reused, 5) Did the query throw an Exception and if so it will show its stacktrace, and a few more things. (see) 2.3) Exception Details - Should any monitored interface throw an Exception it will be kept in the SQL details buffer. This will allow developers to look at actual stack traces in a web page as opposed to combing log files. (see) 3) The menu also has a link to a page that can exercize JAMon monitoring by running HSQLDB queries. When you click on 'Generate Data!' from (see), several queries will be run and monitored, an Exception will be thrown and a custom interface will be monitored. You can look at the code by viewing the 'Show Code!' button. 4) The next version of jamon will have jdbc drivers that will allow developers to monitor jdbc with no code changes. Check it out. I think you will find it interesting! Subscripe to the sourceforge mailing list for JAMon () - a fast, free open source performance tuning api. JavaRanch Performance FAQ I agree. Here's the link: subject: JAMon 2.1 and Monitoring SQL/JDBC Similar Threads JAMon 2.1 and Monitoring SQL Need help on web page hit counter JAMon 2.1 JDBC/SQL monitoring released Database monitoring benchmarking All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/304303/JDBC/databases/JAMon-Monitoring-SQL-JDBC
CC-MAIN-2015-48
refinedweb
590
57.27
The following form allows you to view linux man pages. #include <termios.h> int ioctl(int fd, int cmd, ...); termi- n fore- ground dif- ferent call- ing process, give up this controlling terminal. If the process was session leader, then send SIGHUP and SIGCONT to the fore- ground will fail with ENOTTY in case the terminal is not a master pseudoterminal and not our controlling terminal. Strange. Exclusive mode TIOCEXCL voidotermi- n infor- mation console_ioctl(4). Kernel debugging #include <linux/tty.h> TIOCTTYGSTRUCT struct tty_struct *argp Get the tty_struct corresponding to fd. The ioctl(2) system call returns 0 on success. On error, it returns -1 and sets errno appropriately. EINVAL Invalid command parameter. ENOIOCTLCMD Unknown command. ENOTTY Inappropriate fd. EPERM Insufficient permission.); } ioctl(2), termios(3), console_ioctl(4), pty(7) webmaster@linuxguruz.com
http://www.linuxguruz.com/man-pages/tty_ioctl/
CC-MAIN-2017-39
refinedweb
134
54.18
Version 4.0.0 of the R language for statistical computing has been released, with changes to the syntax of the language as well as features pertaining to error-checking and long vectors. The upgrade was published on April 24. Source code for R 4.0.0 is accessible at cran.r-project.org. A GNU project, R has gathered steam with the rise of data science and machine learning, currently ranking 10th in the Tiobe Index of language popularity and seventh in the PyPL Popularity of Programming Language index. Changes and features introduced in R 4.0.0 include: - A new syntax is offered for specifying _raw_ character constants similar to the one used in C++, where r"..."can be used to define a literal string. This makes it easier to write strings containing backslashes or both single and double quotes. - The language now uses a stringAsFactors = FALSEdefault, and thus by default no longer converts strings to factors in calls to data.frame()and read.table(). Many packages relied on the previous behavior and will need updating. - The S3 generic function plot()now is in package base rather than package graphics; it is reasonable to have methods that do not use the graphics package. The generic currently is re-exported from the graphics namespace to allow packages importing it from there to keep working, but this could change in the future. Packages that define S4 graphics for plot()should be re-installed and package code using such generics from other packages must ensure they are imported rather than relying on being looked for on the search path. - S3 methods for class array now are dispatched for matrix objects. - Reference counting now is used instead of the NAMED mechanism for determining when objects can be safely mutated into base C code. This reduces the need to copy in some cases and should allow future optimizations. It also is expected to help make internal code easier to maintain. assertError()and assertWarning()in package tools now can check for specific error or warning classes via the new optional second argument classes. DF2formula(), the utility for the data frame method formula(), now works without parsing and explicit evaluation. - Long vectors now are supported as the seqargument of a for()loop. matrix()now converts character columns to factors and factors to integers. skeleton()now explicitly lists all exports in the NAMESPACE file. - The internal implementation of grid units has changed. The only visible effects at the user level should be a slightly different print format for some units, faster performance for unit operations, and two new functions, unitType()and unit.psum(). - Printing methods (..)now uses a new format()method. - Packages must be re-installed under the new version of R. - This version of R is built against the PCRE2 library for Perl-like regular expressions if available. - The beginnings of support for C++ 20. - Time needed to start a homogeneous PSOCK cluster on localhost with many nodes has been significantly reduced. - There also are a number of deprecations. For example, make macro F77_VISIBILITY has been removed and replaced with F_VISIBILITY; deprecated support for specifiying C++ 98 for package installation has been removed; and many defunct functions have been removed from the base and methods packages. Credit: Google News
https://nikolanews.com/major-r-language-update-brings-big-changes/
CC-MAIN-2021-17
refinedweb
544
55.64
On Fri, Mar 30, 2012 at 2:20 PM, Masklinn <span dir="ltr"><<a href="mailto:masklinn@masklinn.net">masklinn@masklinn.net</a>></span> wrote:<br><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"> <div class="im">On 2012-03-30, at 20:22 , Sasha Hart wrote:<br> ><br> > I am finding more reasons to dislike that -m:<br> ><br> > python -m wsgiref.simple_server -m blog app<br> ><br> > Beyond looking a little stuttery, it's really unclear. Anyone could be<br> > forgiven for thinking that -m meant the same thing in both cases<br> <br> </div>And it does. In both case it means "use this module for execution". Hence<br> `-m`, as a shorthand for `--module`.<br></blockquote><div class="im"><br>I don't agree, there are real differences. python -m runs e.g. what is in __main__.py and this is effectively a script: the interface is defined by things like sys.argv, environment variables, exit code, stdin/stdout. yourtool -m asks a module to put a callable into a namespace, the name of the callable must be known to decide which callable to use. a simple http server must run and repeatedly call the callable according to WSGI convention, not a script interface. Typically there is some kind of event loop, etc. The things 'executed' are different and they are 'executed' in quite different ways. So while you can use -m (or -xyz or -rm-rf) I have the opinion that it's a little more confusing and a little more long-winded than makes sense to me as a clean one-liner for newbies, partially because I think it suggests a misleading parallel.<br> <br>But this is just feedback; if you don't like it, then just get more feedback. My vote is for whatever gets consensus as easiest for users who have a use for the thing. If you get a patch in, great. If I don't like it then I will just recommend that (still pretty trivial, conceptually clear) wsgiref recipe or gunicorn or whatever has nailed the extreme simplicity required for this case where you are avoiding a 'real server' deploy. <br><br></div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div class="im"> > so I see no gain of understanding by reusing the convention. python -m doesn't take a<br> > second positional argument, either.<br> <br> </div>I'm not sure why that would matter.<br></blockquote><div><br>What it could matter (for what it's worth) is that two different calling conventions is more for a newbie to keep straight, for a '-m' which is supposed to mean one thing. <br> </div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"> <div class="im"><br> > You can't write '-m blog app -m<br> > wsgiref.simple_server' or '-m blog -m wsgiref.simple_server blog'<br> <br> </div>Naturally, because this makes no sense at all, the tool being invoked<br> to start the server is all of `python -mwsgiref.simple_server`. But<br> that's the very basics of the -m option.<br></blockquote><div><br>It is only natural for people who have strong domain knowledge of Python, for whom the proposed feature is redundant. For people who don't care about Python or are just starting, it is not safe to assume detailed knowledge of the -m option to the python executable. Many utilities allow the same flag to be repeated to supply multiple arguments, for example; the interpretation of -m and the rest of the command line here is not unprecedented, but also not just obvious to every bash user. If this is easy, how hard is it to paste in the wsgiref recipe or run gunicorn? Take it or leave it, my input is that this has no reason to exist in stdlib unless it is at least as simple. But as I said before, if you get a patch in then that's great.<br> <br></div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"> I fail to see why that would be any more troubling than<br> `python -mcalendar -m 6`. Or require any more specifics.<br></blockquote><div><br></div><div>I think 'draw six calendars across' is not at all confusable with 'run the calendar module as a script' because that utility is so simple. The one under discussion is at least somewhat more complex, since you are asking one module to run as a script which imports another module and picks out a callable and starts an HTTP/WSGI server. We can keep track of that without any trouble, but we are also subscribers to Web-SIG.<br> <br>I will likely never use that calendar one-liner in my life, nor recommend it to any newbie I am trying to help. Whether it is good or bad, it matters very little. If you get a patch into stdlib with really simple syntax then I will evangelize it right after 'hello world'. If not, there are other options which are also okay.<br> </div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"> <div class="im"><br> > On reflection, I feel strongly that a module name should be the default<br> > positional arg, not a filename. I agree with PJ Eby that pointing directly<br> > at a file encourages script/module confusion. I would add that it<br> > encourages hardcoding file paths rather than module names, which is brittle<br> > and not good for the WSGI world (for example, it bypasses virtualenvs and<br> > breaks any time a different deploy directory structure is used).<br> <br> </div>Not sure how that makes sense, it uses the Python instance and site-package<br> in the virtualenv, there is nothing to bypass.<br></blockquote><div><br>The problem is that you get scripts coded directly against Z:\WORK\FROB\FROB2\FARPLE.PY instead of correctly searching for farple on PYTHONPATH (thus separating the concerns of how/where to install farple from ones of how to get it). If you write a script which hardcodes module paths, it is asking for exactly the same file regardless of what virtualenv you are in. <br> <br>I fully understand why the python interpreter takes file arguments. In web apps we are not talking about just running a file through the interpreter any more. WSGI doesn't involve 'running' scripts, but rather importing modules which contain WSGI application callables. Here we are talking about how to tell python to import a file by its filename, when Python itself already provides a clearly better way of finding things. Now I reckon you are seasoned and you know about those subtleties, but if I am just switching from PHP and you teach me to specify this with file paths then that is setting me up for frustration down the line, when I either have to deal with correct imports or I hit the wall of the 'import from py files' approach.<br> </div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"> <div class="im"><br> > Of course, this also means no '-m'. Then the typical use case is really just<br> ><br> > python -m wsgiref.simple_server blog<br> ><br> > A second positional arg is both a new convention and not an explicit one,<br> > where I would prefer either an existing implicit convention or a new<br> > explicit one.<br> <br> </div>What is not explicit in having an explicit argument, that it's a positional<br> one instead of an option? How is a colon "more explicit"?<br></blockquote><div><br>Well, that isn't what I said... I said that I would prefer EITHER an existing implicit convention (e.g. the widely used colon, which also made sense to me from the moment I saw it) OR an explicit convention (e.g. not allowing a second positional argument, only a labeled argument if a second argument were needed). The explicit one is wordy but discoverable. The implicit one is clean and allows me to transfer knowledge from myriad other tools using the same convention. The second positional arg has the disadvantages of both - neither discoverable, as it lacks a label nor does it benefit from sharing a convention with other tools (the latter has a little relevance to me when I wish to teach others, as well). <br> <br>This is why I was -1 on the second positional arg, and +1 on EITHER of the other two options, which have different pluses and minuses.<br> </div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"> <div class="im"><br> > I think PJ Eby is right that the colon convention is only for modules, and<br> > I think following gunicorn's lead here would result in a nicer interface<br> > than forcing (say) --module<br> ><br> > python -m wsgiref.simple_server blog:app<br> <br> </div>The colon is no more explicit than a second positional argument. In fact,<br> it is significantly less so since it can not be separately and clearly<br> documented and the one positional parameter needs to document its parsing<br> rules instead.<br></blockquote><div><br>I am sure that is slightly easier to write, anyway. This attribution of 'explicit' to the colon convention is probably a misunderstanding; I never said that (although I find it strange to say that the second positional arg is in any way more explicit, particularly when it is inventing a convention for referring to WSGI callables). The virtue of the colon syntax for me is that it fully covers the case which needs to be supported without any --args (simple, clean looking) and while allowing transfer of knowledge between this and just about every other tool out there which names WSGI callables. It's close to the simple Python notation for referring to the object - perhaps it could be better though?<br> </div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"> <div class="im"><br> > If there is a need to point at a filename, I agree that it should be done<br> > explicitly.<br> ><br> > python -m wsgiref.simple_server --file=~/app.py<br> ><br> > (or whatever the flag should be called). To me this seems like a small cost<br> > to allow the colon by default without possibility of confusion or overly<br> > fancy parsing.<br> <br> </div>1. It also does not work considering you can't specify the application's<br> name in that scheme, so piling on yet more complexity would be<br> required and there would be two completely different schemes for<br> specifying an application name. I don't find this appealing.<br></blockquote><div><br>I guess the problem is that you are indirectly specifying the namespace, via a filename to be imported, and then directly specifying the name. All this (including cross-platform issues) is so much easier if you just use Python's conventions for finding and referencing modules and names in namespaces. But for whatever reason, you must import Python modules by filename (something I'll never do again, for reasons already laid out). Yet WSGI requires a name to be specified, so you end up with some kind of awkward hybrid specification. I certainly do not suggest trying to invent a new convention, but if you want to then you just need to pick a portable delimiter for the command line. Maybe a second positional arg or --app= for the cases where you are importing from a file and do not want 'application' and must have a one-liner rather than setting up the project. I have no reason to care because I will never use or teach this case.<br> <br>I think this is the interesting question: what convention already exists in Python for naming a particular object in an imported module? <br> <br></div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"> 2. You seem to have asserted from the start that the default should be<br> mounting modules, but I have seen no evidence or argument in favor of<br> that so far.<br></blockquote><div><br>In a way you do not have any choice but to 'mount modules': WSGI does not provide a mechanism to 'run a program' without picking a callable Python object out of a namespace, implying an import. <br> <br>My intention was to offer feedback, on the assumption that the idea was being thrashed out publicly. I believe I actually have offered some supporting reasoning for why I like the module path better as a default, even though you reject it. But ultimately, much of this is or verges on bikeshedding. Now our exchange has taken on a negative tone that I would not have chosen. I have written to clarify some misunderstandings, but I will not bother offering further unwanted feedback. I hope you will look for more input and develop a better consensus.<br> <br></div><blockquote class="gmail_quote" style="margin:0pt 0pt 0pt 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"> Defaulting to scripts not only works with both local modules and<br> arbitrary files and follow cpython's (and most tools's) own behavior,<br> but would also allows using -mwsgiref.simple_server as a shebang<br> line. I find this to have quite a lot of value.<br> </blockquote></div><br>The python interpreter runs scripts, i.e. processes which interface with sys.argv and stuff like that. So of course it needs to take file paths. But imports are not typically done with file paths, and WSGI app-finding is either imperatively about importing or declaratively about Python namespaces - not file paths or scripts, as in CGI. Python imports are conventionally done by a path like frob.bar rather than a filename, which has problems (I think this is why we don't "import c:\work\frob\farple.py" at the top of our files, or run "python -m /usr/lib/python3.2/wsgiref.py simple_server". You must also specify a name for the app object, and it happens that the conventions around specifying names in namespaces dovetail pretty closely with the conventions around imports. (e.g.: from frob import app, import frob.app). Given that the operation required is an import and then a lookup, it seems more natural to me to use Python notation or something trivially related to it, rather than OS-specific filesystem notation. But I am sure this is just another disagreement and that's fine with me.<br> <br>I would personally not +x a module file just to serve an app with wsgiref from the hashbang line; it's clever but I can't come up with any real benefit. A case where I'm serving with wsgiref already has to be pretty trivial and I'm not going to couple to it *from inside the module itself* when it is so darned easy to just run the module from several nice python test servers (also portable and I can use autoreload, etc.) But if this is desired by many others, I'd agree it's a good factor to consider.<br> <br>Cheers<br>Sasha<br>
https://mail.python.org/pipermail/web-sig/attachments/20120401/c2c69cb4/attachment-0001.html
CC-MAIN-2016-50
refinedweb
2,646
53.41
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives Not a lot here on Go at Google really. Mostly a general overview of the language, whose major selling point seems to be that it was designed by famous people and is in use at Google. The following slide sums up the issues that Go was meant to solve very nicely: What makes large-scale development hard with C++ or Java (at least): slow builds uncontrolled dependencies each programmer using a different subset of the language poor program understanding (documentation, etc.) duplication of effort cost of updates version skew difficulty of automation (auto rewriters etc.): tooling cross-language builds Language features don't usually address these. What makes large-scale development hard with C++ or Java (at least): Language features don't usually address these. Most of those bullet points were already covered by languages like Turbo Pascal, Modula-2, Modula-3, Ada, Delphi, Oberon for around 20 years. That was my point. The first 2 items on that list are more or less clear, and are solved by language features. The rest is a combination of tooling, education and pipe dreams. They don't really need a new language. Check out next slides and tell me: what problem from this list does the lack of indentation based syntax solve? How does a copy of itoa in net package solves "duplication of effort"? The way I think about Go is: if you take C and decide to improve it in a number of areas (memory safety, module system, simpler parsing) and make a minimal possible improvement in that area, you get Go. ...go ... or or Vala or Cyclone or Genie or Cilk... what problem from this list does the lack of indentation based syntax solve? His point in the talk was about code in one language embedded within code in another, JSP-style. If the embedded language is layout-sensitive and the host language is not, you're headed for trouble. You might file this under "difficulty of automation", I guess: IDE support is going to be tricky. A copy of itoa in net package means they don't have a bunch of programmers all implementing their own itoa in order to avoid importing (and parsing, and compiling) the very large package that itoa is part of. This is an effort to "head off" the specific type of duplication of effort where you have a bunch of knowledgeable, smart guys all putting in the same bunch of little things in order to avoid creating compile-time resource-hungry dependencies on a few big things. I've (re)defined utilities myself, specifically in order to keep build times as short as possible by not importing large libraries. If you multiply it by a thousand coders though, you get longer build times and bugs as dozens of versions of atoi (or whatever little utility) get compiled instead of the big package that people are defining their own atoi's (or whatever) in order to avoid importing. Go is very much optimized based on the pragmatics of scale, on experience with programmers gaming the build system or dependencies in order to achieve scale, and on experience of time-wasting and unproductive arguments. They addressed several sources of confusion and flamewars by adopting explicit conventions and automatisms (gofmt, capitalize-to-export, qualified-names to refer to imports, etc) in order to create a 'clarity' that enables programmers to read each other's code and not be confused by unfamiliar conventions. The convention of using qualified-names also makes it easily possible to tell what dependencies are *not* really required, which permits tree-trimming. Types as interfaces rather than inheritance is another method of reducing dependencies. You don't have to depend on a tree of other classes; you just have to depend on the interface definitions - and the interface definitions are simple, idempotent, and easy to deal with. They've redefined and multiply-defined ubiquitous utilities such as atoi in order to optimize the build process. They addressed recurring divisive-but-pointless social issues such as naming conventions and code style conventions, which can hinder productivity and cause confusion, and addressed them with gofmt (which destroys arguments about code formatting) and the capitalize-to-export automatism which destroys some arguments (and inconsistency, and confusion) about the names of exports. I don't believe anyone needs to justify a lack of indentation-based syntax. Lack of indentation-based syntax is in fact the normal case. If anything indentation-based syntax is still the peculiar case that might be seen as requiring some justification. In short, pretty much all of these decisions are driven by a desire to make the dependency situation more tractable and the compile times shorter. I completely get it, and given their requirements it makes perfect sense. We've all done strange things, sometimes even for a good reason. I've compiled C++ programs without linking to C++ runtime, by reimplementing parts of it myself (mostly forwarding to kernel32 functions, this is on win32), to shave off a dozen KBs of size. This made me pretty proud of myself (users are always proud when they manage to use a tool in a way its developers didn't intend or even tried to forbid), but I doubt this makes developers of Visual C++ proud. So I can believe they had to do something like that, but this isn't a good selling point for the platform. In short, Go seems full of things that I can see myself doing (especially to solve hard problems without known elegant solutions and on a tight deadline), but I wouldn't be really proud of them. Also, I didn't ask to justify the lack of indentation-based syntax. I asked how exactly it addresses problems from the list, as it's listed as one of the solutions. It seems to me that redundantly defining "itoa" to "optimize the build process" (at the cost of increased code maintenance!) is precisely a gaming of the build system. Yes, it's definitely gaming the build system. The point is it's better to have it done once in library code than to have dozens or hundreds of people doing it independently. Putting it in the library code is limited redundancy that avoids wider redundancy. Library code, once debugged, has a FAR lower maintenance burden than project code. Further, one additional copy in the library heading off hundreds of extra copies in project code would be a big win even if that weren't so. Of course it would be 'cleaner' to have a finer-grained build system that avoided the effort of parsing and compiling things it doesn't need from an imported library in the first place, but a few extra copies of a definiton are better (from a get-it-working-right-now perspective) than an open-ended research problem. What this is, as far as PL research is concerned, is an ad-hoc solution which is valuable because it points out a problem that needs a real solution. So how should we construct the finer-grained import system that avoids the build-time effort of reading, parsing, and compiling unneeded parts of a library? That's a real issue, there's a real need for a solution, and it's an issue most researchers have been paying no attention to. Ray The entanglement problem describes the difficulty of extricating a module from one project or library for use in another. I've been thinking about this problem for some time, e.g. regarding entanglement caused by namespaces and constraints on dependencies to ensure predictable extraction. Generally, I feel the best solutions leverage semantic linking, e.g. driven by types, tests, patterns, and values (e.g. exporting metadata) rather than by meta-organizational concepts directed from outside the language. Linking becomes staged programming, and potentially much more robustly adaptive. There is a reason why we have natural language. Its much easier to talk about a concept by name rather than through its intrinsic real value. Natural language doesn't make heavy use of names, AFAICT. It is better characterized by context, constraints, local referents, and metaphor. Talking about a concept by metaphor or description is a form of talking about a concept by its intrinsic values. I agree that use of names can be convenient, but names will tightly couple expressions that would otherwise be usable in more contexts. I think that natural language isn't a great example of modular language. :) sans nouns: Natural x doesn't make heavy x of x, AFAICT. It is better characterized by x, x, local x, and x. x about a x by x or x is a x of x about a x by its intrinsic x. I agree that x of x can be convenient, but I think that natural x isn't a great x of modular x. :) sans nouns and adjectives: y x doesn't make y x of x, AFAICT. It is y characterized by x, x, y x, and x. x about a x by x or x is a x of x about a x by its y x. I agree that x of x can be y, but I think that y x isn't a y x of y x. :) Care to tell us more about how natural language doesn't make much use of names? I haven't a clue how Ben L. Titzer confuses names with nouns and adjectives. My point is that every noun is just a name for a concept, adjectives are names for properties of nouns, and verbs are names actions on nouns. We don't include in every sentence the complete description of the meaning of every concept (in what terms would those descriptions be rendered, one wonders) which it references, but we refer to shared knowledge through identifiers of concepts. Those identifiers of concepts are "names" in my understanding. The way I see it, natural language is much less context and metaphor than you assert; real communication requires naming shared concepts. If names didn't matter so much in language, then changing them wouldn't change the meaning of your sentence so much. Unless you meant something completely different by "name" in your analogy to natural language. If so, maybe with more rigorous definitions your argument would be clearer. Certainly we must use abstraction, and it is convenient to "name" our abstractions and share them via names. But there seems to be a phase distinction between naming concepts (e.g. to extend the English language) and using the name concept (e.g. naming objects or events, identifying objects or events by name). When I say we do not heavily use names, I mean the latter. I had a hard time understanding the discussion, so here is my attempt at explaining what (I think) you say, in hope that it would help the future reader: (I think that) dmbarbour says that, in the course of a conversation, we rarely define local names ("In my next sentences I will refer to the chair I'm talking to you about by the name 'current_chair'"), but rather use context and constraints ("the chair on the right", "this chair", "it"). We do sometimes define new names but it is a relatively rare event, often specialized to certain problem domains. And even when we define names they often keep their descriptive nature instead of being alpha-convertible proper nouns; this is apparent in programming language practice ('current_item', etc.), and often semi-implicit in the etymology of nouns: (Ent(scheidung))s(Problem) being an extreme example. "the chair on the right", "this chair", "it" Functionally, these are names. Within a context, within a text/conversation, they are (local) proper names. In a programming language, you would use local variables, this_chair. When you want to globalize those "names", you *equate* them to proper names: this child is John Smith. If I follow your reasoning, every expression that denotes something is name. The "name" name doesn't mean anything much, then, and I'm not sure what you can discuss with this interpretation. Indeed, most parts of a program mean by denoting things. Sean: "Its much easier to talk about a concept by name" dmbarbour: "Natural language doesn't make heavy use of names" Ben: "My point is that every noun is just a name for a concept" dmbarbour: "When I say we do not heavily use names, I mean <proper names rather than names for concepts>" Nice wriggling, Humpty Dumpty! I appreciate both Sean and David's contributions to the discussion and have no vested interest, but I must stay that dmbarbour remarks still have a point, even in the face of Sean's comment. What you didn't report is that the message of Sean was a reply to a message by David that was saying: "we would be better equipped against the entanglement problem if we could use contextual descriptions rather than names only". Sean pointed at the natural language use of names but, once you think of it (see my explanation above), the tools of contextual description are massively more powerful in natural language (when processed by humans) than in programming language, meaning that the comparison to a natural language is actually *in favor* of David's initial point... exactly what he said. In a programming language, if you want to speak of the same thing twice, you are practically forced (if you want to do things right) to give it a name. Declarations are basically the only way to reduce redundancy. This is massively untrue of natural languages, where in most circumstances you do not give a new names to the things you speak about. Certainly, we have a large library of things that have been given names, but there is an even larger amount of things that we talk about without giving them a fresh unique name; the ways to designate things are richer. Perhaps use a random generator to generate names automatically? Everything has a name (you didn't pick it!), you often just don't care about it. But I'm missing the nature of this debate. I think David's argument is that contextual designation of objects (as a larger set of technique than just naming) may be easier to adapt to change, and therefore help for some aspects of software maintenance -- both in helping discovering the new objects, and helping avoiding being forced to use a new object with the same name that is disfunctional for you. For example if instead of saying "import library Toto.List" you say "import library List which provides feature-foo", you may both let your environment select a "better" version than Toto.List that fills your needs if it appears, and avoid having your environment silently switch to the new backward-incompatible List library of Toto that doesn't provide feature foo anymore. I don't know whether I'm a strong supporter of this vision, I see myself as a neutral observer. But for once I think I understand what David means, and it seems clearly related to the discussion (Ray's question of finer-grained import systems), and you ask explanations about it... a satisfying combination. I'm a firm believer in names only in so much that you eventually have to pick one, but its like a URL...who types any but the most commonly used URLs into a web browser anymore? Search as resolution from description to "esoteric name" is definitely the way to go. The only thing we really disagree on is phase: I believe that search is a dev-time activity, I believe David wants it to be a compile-time activity (part of symbol resolution during compilation), I'm sure someone could even make the case for a run-time activity (e.g., service lookup). My reason for preferring dev-time is that you want to commit to a binding during development and not have it magically change when the code is recompiled in a new environment or under different probabilistic circumstances (if you have fuzzy binding resolution). Reading through the comment history, there also seems to be some discussion about anaphora-style referencing in the language; e.g. what Lopes proposed in her Beyond Aspects paper. This is fairly orthogonal to what I'm talking about here. I agree with this. Constraints should be solved at dev time (even if the solution is a search algorithm). In context of live programming or maintenance, the notion of dev-time is itself fuzzy. But I do favor staged programming and securable programming models (ocaps, etc.). We can control where constraints are bound (spatially), when they are bound (temporally), and even control stability of various bindings. When a language is blind to these issues - as most traditional languages are - it is actually much weaker for managing constraints, and less adaptable to different programming levels. Productivity suffers in many small ways that only seem clear in hindsight. There are multiple dev times, but I wouldn't call them fuzzy. My point is that the meaning of the keys you press can be fuzzily interpreted by the system as you code, but result in concrete semantics that can be inspected during the dev process. I count bag-of-constraints solve-me-if-you-can semantics as fuzzy. So staged is good and fine but I call foul if the output of an early stage is just a mess of constraints to be sorted out by a later stage. In spiral development models, or a traditional edit-compile-test cycle, perhaps there are multiple distinct dev-times. But in many other development models - live programming, continuous integration, maintenance of plugins on 24/7 services, PLs as UIs (tangible values, naked objects, direct manipulation, etc.) - there are no clear lines. I'm curious what your hidden assumptions are, and the extent to which you're aware of making them. Anyhow, for any program we should have a clear understanding of what we're expressing, an ability to justify any design. A bag-of-constraints can be acceptable, but only if one is able to reason about it in certain ways: will it always have a solution? how much time and space will it take to find a solution? how will the system behave in the absence of a solution? can we reason about stability of the solution in face of instability of the constraints? can we control who introduces which constraints? can we protect the interests of certain agencies above others (priority, security)? In a mess of constraints, it's the the 'mess of' that's a problem, not the 'constraints'. If you can guarantee them solvable then they aren't the solve-me-if-you-can variety constraints that I'm disparaging. My point is that the more fuzzy search-through-a-huge-space approach is reasonable at dev time along with other fuzzy techniques, since you can inspect the results to make sure they're what you wanted. I don't see what you're getting at with the continuous programming bit. If you're thinking of a UI as a PL, then dev time is when you're interacting the UI. The principle I'm (probably poorly) describing applies pretty robustly to interaction, I think. When you ask Siri to remind you of something, she doesn't just say "OK", leaving you to wonder what she understood you to mean. Rather, she presents you with a concrete reminder to confirm. Fuzzy interaction should just be an efficient means to arrive at concrete semantics, not a replacement of them. Whenever resolution takes place, or (if you see resolution as a gradual thinning process rather than a one-time operation) whenever arbitrary choices need to be made, the resolver is free to decide (in case of excessive ambiguity) to ask the user the make the choice. That's what happens for example when Firefox tells me: "there is a new version available, do you want to update it now or later?". It's a form of hardcoded runtime (in fact continuous) code resolution semantics, with late interaction. That said, user validation is maybe not as necessary as you seem to think. David had a rather interesting post about this, Abandoning Commitment in HCI. The important point of my example was the concrete-ness, not the modal confirmation, which I agree is best replaced with undo in most cases. I also sort of see where you and David are coming from, I think, which seems to be that any use of a computer can be viewed as "programming". I don't really think of it as programming if you can assume that the programmer will be around to clarify what he meant as the program runs. Human attention is a precious resource, not something to squander struggling with messy abstractions. Stability and responsiveness are significant concerns regardless of human supervision. Open extension is equally relevant for modular plugins and cooperative development. Software agents generally have the same concerns as the humans they serve. Developers benefit from consistent reasoning at all stages of development - prototyping, deployment, configuration, integration, maintenance, administration, etc.. If a constraint model is bad for unsupervised runtime, it will be bad for supervised development. If a constraint model is bad for supervised development, it will be bad for unsupervised runtime. Programming language that require a strongly distinguished `dev-time` are not addressing concerns at development time so much as failing to address development concerns at all stages after prototyping. I'm happy to support interactive and cooperative development. I envision collaboration from both humans and software agents. But I think it's unwise to make any special distinctions for a `dev-time`. For most meta-programming, it's even important to avoid special distinctions. If you're thinking of a UI as a PL, then dev time is when you're interacting the UI. Are you assuming a solitary, single-user system such as a calculator? Fuzzy interaction should just be an efficient means to arrive at concrete semantics, not a replacement of them. I agree with this sentence, which isn't specific to dev-time. Fuzziness is deep in any programming system that interacts with the real world - sensor data has noise and aliasing; sensor analysis is subject to heuristic algorithms and estimated models; yet all this must lead to concrete actuation decisions. For HCI, we track gestures and voice and pen-scrawls and keyboard inputs with typographical errors. While commitment to discrete action can be delayed to obtain clarifications, it must eventually be made. You're hung up on 'dev time' and missing my point. Dev time can be e.g. during the debugging or administration of another component (that was developed at an earlier time). Let's call it interaction time rather than dev time. At interaction time, it is appropriate to use fuzzy methods to resolve human intent interactively, even though it's not a good idea to deploy those fuzzy semantics in an unsupervised situation (they are too complicated to reason about). I heard your point, I just disagree with it. Let me reiterate my own: Whether you call it dev-time or interaction time, it isn't more or less an appropriate point for 'fuzzy methods' in general. Of course, the full phrase "fuzzy methods to resolve human intent interactively" does beg the question of whether 'interaction time' is most appropriate. My point is that the fuzzy methods that are good for unsupervised operations are the same ones you'll want for resolving human intent interactively. And vice versa. If your fuzzy methods are bad for unsupervised situations (e.g. involving collaborating software agents or meta programming), then your fuzzy methods will also be bad for human users. Dev-time or interaction time is a poor excuse for bad fuzzy abstractions. Heavy weight methods like a unification or SMT solver are the kinds of tools I have in mind for "fuzzy" tools. Do I think they should be available through as general as possible an interface to be used on other problems? Sure. But they are quite special purpose and complex and should not be part of ordinary runtime semantics for a language, IMO. I see nothing wrong with this point of view, in the sense that it is shared by a lot of people, but I'm not personally convinced that there is a point in keeping so strong a distinction between the "language", that should have a precise semantics, and the rest. If your language has a precise semantics of using the code on your filesystem, but your package manager uses SMT-solving to update those packages on the file-system, the overall behavior is not much different than having some (constrained) level of fuzzy resolution directly inside the language. I'm more of the point of view that we should accept to formalize more aspects of the programming experience. If people use fuzzy solvers and live update in their practice of programming, there may be something to be gained by giving those a proper status and working on their semantics. Because I believe that looking at things formally help designing them and making them robust, and I want not only the semantics of my lambda-abstractions and for loops to be clean and robust. On a related note, I cannot help remarking that the state of tooling for "academic languages" is usually quite poor. There is a question of money/workforce (writing good tools is a lot of hard work that research teams cannot usually afford), but I think there is also a question of lack of interest, in some part of the PLT community, in taking tooling seriously. Making it easier to produce good tooling for a new programming language is a hard research problem that merits more work¹. I think a necessary condition for this is a more formal treatment of programming aspects that you would naturally prefer "outside the semantics". ¹: not to say that none has been done, there has already been an important amount of research. I'm a bit lazy to fish for references right now (do not hesitate to add some), but ICFP'12 "Functional Program that Explain their Work" by Acar, Cheney and Levy is one such example of a deep foray into tooling-oriented questions. I even suspect that one of the reason why researchers may be wary of working on these questions is the perception that a lot of effort has already been invested, with no clear result. I think the lack of focus on tooling is simply because no one really believes we yet have a really good foundation around which to build this tooling. More bang for the buck to focus on core semantics right now, since that will shape what kind of tooling you'll need. I feel surrounded by researchers investing a lot of effort on tooling for C (Framasoft), Java (Jif) or Javascript (lambdaJS). Apparently they couldn't convince the programmers, or the funding bodies, of your "bang for the buck" estimation. I think you can do tooling research with simply-typed lambda-calculus (and some certainly has been done in Scheme). There is also fun things being done on the Emacs mode for Agda, McBrid-ish tooling of sort, that relies on rich dependent types, but even there I don't buy the argument that the semantics is not there yet (you can already work on the Calculus of Constructions, or Martin-Löf Type Theory). All in all, "the languages are not clean enough" looks to me like a rather weak excuse. Can you substantiate the idea? To be fair, both industry and academia suck at tooling, its just that industry sucks a bit less. I argue in my maze paper that tooling is just another point under language design to consider with syntax and semantics, probably making tradeoffs between each point to create a better holistic experience; aka you are not just designing a programming language, you are designing a programming experience. You can't make really excellent tooling without support from the language and runtime. Debuggers need symbol tables, place tags in the code, ways to single-step, ways to evaluate expressions in the code's current environment, ways to set and clear breakpoints, etc. It may be possible to standardize the form that support takes, so that a standard IDE or suite of excellent tooling is applicable to new languages if they provide standard types of support in some standard form. As an example of paradoxically good/bad tooling, Emacs has become a primary obstacle to the adoption of Lisp. It is, without a doubt, a good tool for working with Lisp code, once you know how to use it. But its nonstandard interface alienates new users even while its excellence in the hands of old-guard users inhibits the development and adoption of excellent tools that wouldn't alienate newbies. I personally like Emacs for editing Lisp code, but it isn't the slick IDE experience that people expect from a "good" programming language. You have to invest effort in *learning* to use emacs, then invest effort in *configuring* emacs to run an inferior lisp process, then invest effort in learning how to use the inferior lisp process, etc... people don't want that. They want a very standard IDE interface of the sort they're used to, which means the sort that came along AFTER Emacs' own interface was invented. If you are trying to sell people on a new language, you need to provide a proper IDE where they have nice standard mouseable menus, I/O panels separate from code panels, autocompletion, autofind, function/object renaming support, argument lists that pop up when you type a function name, tooltips, buttons, verbose help messages, integrated debugger, a tutorial that covers both the language and the IDE, printable and HTML documentation, a huge and well-documented function library, and all the rest of it. Without that, they'll decide that a new language "sucks" before they ever get as far as using the language itself. This is not wrong. This is not right. This is not justified nor does it need to be. This is just a factual report about what it takes and what you need to provide if actual use of your new language by other people is one of your goals. I'm not sure why you consider your examples to be work on tooling. Jif and lambdaJS are languages in their own right that received plenty of work on rigourous semantics that were lacking in the underlying language. Have you considered that the issues you named for those heavyweight fuzzy methods seem to describe the "heavyweight" rather than the "fuzzy"? The concept of a program is changing. Perhaps it's not so much "runtime semantics" but, when you write "ordinary", you mean "production time semantics." At some point, we need to hand off software to users, and it better not have a dynamic error of "oops, could not synthesize code for this case." Until that hand-off, however, I love programming with runtime semantics that are empowered by oracles. Interestingly, a la Martin Rinard and arguably Ben Liblit, I'm not even convinced of this hand-off point anymore. Program in an infinite loop? Jump out and go forward. I bet we'll see papers soon about using symbolic execution to infer live repairs. Likewise, what if the end-user wants to instruct (augment) the program? The code creator and user are now the same person. Both cases seem like holy grails -- we don't have them because, to a large extent, we haven't figured out how to implement them. There are lots of things we can do during develop that are not reasonable for deployment, like inferring missing functionality or risky default bindings. We've talked about this before. I can definitely see software becoming "fuzzier" in general, especially if fuzzy semantics based on machine learning or simulation serve as the underlying programming model. But for our current precise and brittle programming models, I think we need to define a very rigid boundary between development and deployment, which necessarily limits adaptability and end-user extensibility. Rinard's work seems similar to Verner Vinge's software archaeology distopian future, and seems appropriate only if we can't evolve out of our brittle programming models. Designs that eschew use of names or URLs are not uncommon - associative memory, tuple spaces, some publish/subscribe models. It is feasible to develop a world wide web without names, where links instead describe content-based searches. Including unique values in content (e.g. UUID or URL-like values) would still be useful for searches, but isn't the same as a naming system. Relevantly, names are part of an associative/relational system generally orthogonal to content. Secure hashes are a simple way to uniquely identify values in practice, and are leveraged in Tahoe-LAFS. But those are mostly a performance boost, ability to talk about a value-object without repeating it. Use of context, constraints, and anaphora are much richer options than secure hashing, and often more expensive (more data, more computation), but can (in practice) still uniquely identify content (especially when the developer has some control over context). We don't need names. Names aren't essential for calculation or communication. But names can be convenient, and I've not suggested we should abandon them entirely. In articles such as interface and implement and local state is poison, I suggest structured use of names that allows us to take advantage while avoiding problems that result from more pervasive use. Re: Phase and Commitment (Early/Dev-Time Binding) I do believe we would benefit from much search in later stages. I describe some of these concepts, e.g. with stone soup programming and stateless stable models. I like various ideas surrounding multi-agent systems, blackboard systems, ambient-oriented programming. However, I also believe in iron-fisted control over resources and relationships. Object capability model and secure interaction design have deep impacts on my visions and designs. Developers would consequently have control over the context of any search. Between controlling the search and controlling the context, developer control over search results is however precise as desired. Further, I'm fond of live programming. In that context, the distinction between dev-time and compile-time is very weak. A developer has much opportunity to refine parameters and context of a "compile-time" search in order to achieve desired results. While precise, tight control over bindings is certainly desirable at some times in some contexts, it is certainly not desirable at all times and all contexts. A programming language is low level when its programs require attention to the irrelevant. - Alan Perlis Early commitment when binding dependencies is often attention to the irrelevant. Between stone soup programming and object capability models, I envision module systems that can be adapted to an appropriate programming level on a case-by-case basis. But for once I think I understand what David means Ouch. sorry In a programming language, if you want to speak of the same thing twice, you are practically forced (if you want to do things right) to give it a name So we should all use stack based languages after all? ;) Or Subtext, where code can be a DAG rather than a tree. YouTube video: Steve Jobs Gets Interrupted by Audience Member while presenting "Zero Link". If duplicating "itoa" was necessary, something went wrong somewhere. I suspect that the Google Go implementation pulls in an entire package even if you use only small parts of it. "Hello World" is a 1.2MB executable on Windows. This seems excessive. I too was underwhelmed by the feature set when it was first announced. But in the last few months I've had the chance to use it for nontrivial projects and it's really growing on me; now whenever I have to schlep back into a C++ or Java codebase (the two major languages on my team) I find myself thinking, "Ugh, can't we rewrite this in Go?" -- my Go code usually ends up being substantially terser (but IMHO no less readable) than C++ or (especially!) Java. That said... if you have no use for the curly-braces-family of languages, well, I guess you won't have any use for Go, either, as you could argue that it's just more of the same. But it's a really good version of more of the same. (Disclaimer: I am a Googler, but don't work on anything Go-related... just a satisfied-so-far user.) Is there some use case I am missing that requires curly braces? Silly me, I thought that sort of thing doesn't affect runtime. ..is, I think, what grandparent is saying. The syntactic aspect of this (curlies) is a red hearing is what I'm saying. Syntax has a strong bearing on programmer acceptability. People who post here probably are comfortable with a broad range of syntax alternatives. That's not true of most programmers. Go occupies an unusual place in delimiter syntax. Line breaks matter sometimes, but not always. That's hard to get right. Python succeeds, and UNIX "shell script" languages fail badly. I'm not sure if Go's approach is good or not; I haven't written enough code yet. It's certainly tolerable. Go has a convention that programs are run through an indenter/formatter before source control check-in, so at least you get consistent layout. Go does adopt Pascal-like declaration order, which makes it much easier to parse Go code. Go appears to be LALR(1), although I'm not sure about the "if the keyword on the next line could start a statement, the line break is a statement separator" rule. C and C++ have context-dependent syntax; parsing requires knowing whether a name is a type. That was a design error in C. Early C (pre K&R) did not have "typedef", and the syntax was LALR(1). When "typedef" was added, the syntax became context-dependent, which meant that it was necessary to process the include files just to reliably parse the source. This inhibited the development of tools that worked on and modified C source code. Go already has several such tools, notably "fix". That's useful. Well, it seems like Pike summarized it all. He says "Go's purpose is to make its designers' programming lives better". And I believe Go is living up to that exact purpose. The only thing that bugs me, though, is that I've heard the same thing about a different language. I don't remember where or when, but it certainly was about PHP. I'd feel better if it was specifically their programming lives that it was meant to improve. That'd be fixed were it self-hosted. Most programming languages are, after all, optimised for writing their own compiler in. I don't think you understood my sarcasm... I thought my response was appropriate to the tenor. The ideal ratio of artist to audience is one to zero. Google has lots of human resource challenges on top of computer resource challenges. Just read Michael Burrows's rants about his fellow Google co-workers: I am also not sure which of these problems Burrows cited in 2007 are now being addressed thanks to Go, but I would love to hear from Rob Pike, Russ Cox, and Ian Taylor about that. +1 Luckily for the rest of us, the intentions & personalities of language designers aren't of much consequence. What do I care what problems a tool is 'supposed' (by a complete stranger) to solve if I can use it to solve the problems I actually have? Why more of the same? Because less of something different isn't enough of something practical. Go is a reasonable solution for Google's internal problems. It's a language designed for server-side programs. C++ is too hard to make reliable. The interpretive languages are too slow. Google's effort to make a fast Python system (Unladen Swallow) was a flop. Java is the usual alternative, but it doesn't do concurrency very well. Facebook's approach, incidentally, is to use mostly PHP internally. To fix the performance problem, Facebook developed a hard-code PHP compiler, HipHop. what are other real viable alternatives? there are none? :-( There is Ada of course! Go does a lot with a little and for that reason is worth looking at. Go does not do asynchronous I/O. Instead Go uses cheap threads implemented with split-stacks. Go does not use locks Go uses channels. Go does not have implementation inheritance instead Go just has composition. Go has a switch statement almost as nice as pattern matching in the ML derived languages. Go uses duck typing yet is statically type checked at build time. Go does not have fancy polymorphism features go just uses interfaces. The aim of Go seems to have been to make static typing and compilation palatable to users of dynamic languages, and I think it has succeeded in that. Go brings a lot of nice things from the dynamic languages into a compiled statically typed language. That said so far Go is not a general purpose systems programming language and it is not usable for the kinds of programs I tend to write, but I do think Go raises the bar nicely for new imperative compiled languages. When used for "polymorphism" rather than compartmentalization (eg. when you use a downcast to get an object out of a generic container), Go interfaces are essentially a refinement of (pre-generics) Java's Object type, which is itself an OO equivalent of C's void* type. Object void* I do not understand how anyone could advertise this as a satisfying solution to replace "fancy polymorphism features". On this specific aspect (I do not discuss the concurrency approach), Go rather demonstrates how little programmers actually expect from their language. The aim of Go seems to have been to make static typing and compilation palatable to users of dynamic languages, and I think it has succeeded in that. That's a good insight. Go does succeed at that. Functions have to be declared in detail, but variable declaration is usually implicit. This gives Go programs a comfortably similar look to programs in dynamically typed languages. The aim of Go seems to have been to make static typing and compilation palatable to users of dynamic languages, and I think it has succeeded in that. C++ now has that, with "auto", but it's not yet used much. Quick aside since the topic is near to my mind lately: I'm using "auto" in production code, and it is a great convenience, but definitely still requires considerable knowledge or attention to the feedback that an IDE provides in order to know what it will resolve to safely. That said, this seems to usually only need to happen when the code is first declared, as underlying code refactorings seem to interact with it reasonably. Time will tell whether the code acquires bitrot simply because of "auto" per se. Hoare-type bounded buffer concurrency management is fine, but the way Go documentation suggests doing it is sometimes strange. The "Effective Go" document exhorts "Do not communicate by sharing memory; instead, share memory by communicating." Then their first example is go list.Sort() // run list.Sort concurrently; don't wait for it. which violates that rule, since "list" is shared between two threads. Almost all the examples in "Effective Go" are like that. They don't send data over a channel and get results back over a channel; they send a reference to data over a channel and get a signal (in the form of a minimal send on a channel) back when it's done. The spec is vague as to whether the run-time system is memory safe should there be a race condition with shared data. go list.Sort() // run list.Sort concurrently; don't wait for it. There's a notion of unidirectional channels in the spec: "The <- operator specifies the channel direction, send or receive. If no direction is given, the channel is bi-directional." ... <-chan int // can only be used to receive ints But channels don't have two ends. The same "chan" variable is used for sending and receiving. If you create a receive-only channel, and receive from it, do you block forever, waiting for a send that can never happen? The documentation doesn't seem to say. <-chan int // can only be used to receive ints This is really a documentation problem. Go has a skeletal specification, two main introductory documents, a wiki, and a newsgroup. Nowhere is there a spec good enough for standardization or a second implementation. Go's concurrency uses blind forks - the "go" keyword starts a thread (they call them "goroutines"), the thread runs, and if it finishes, exits silently. There's no way to check on the status of something forked off that way. It doesn't even have a name or ID. The user has to manually construct status reporting from the thread, so that it reports back if anything goes wrong. The "defer" statement can help with this, to close a channel when a thread exits, but that's not automatic. There's a lot that has to be done carefully to do it right, and the examples in the documentation don't bother. A typical failure mode of Go programs is thus likely to be hangs on waits for failed threads. Dereferencing nil in Go causes the entire program to crash. The HTML5 parser ("h5") provided with Go will dereference nil on some real-world HTML documents. (Bug report filed for Go library). Uh oh. This is why a strong exception system is useful. In Python, LISP, Ada, etc. you can catch almost everything as an exception, so when some complex library package fails, recovery is possible. The Go developers claim that everything should have a local error check because errors are a normal part of program behavior. But without exceptions, higher level programs have no way to protect themselves from low level defects. There's also the problem with local error checking that it's very difficult to test the recover code for unlikely errors.
http://lambda-the-ultimate.org/node/4629
CC-MAIN-2018-26
refinedweb
7,779
61.67