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 |
|---|---|---|---|---|---|
wctomb - convert a wide-character code to a character
#include <stdlib.h> int wctomb(char *s, wchar_t wchar);
The wctomb() function determines the number of bytes needed to represent the character corresponding to the wide-character code whose value is wchar (including any change in the shift state). It stores the character representation (possibly multiple bytes and any special bytes to change shift state) in the array object pointed to by s (if s is not a null pointer). At most {MB_CUR_MAX} bytes are stored. If wchar is 0, wctomb() is left in the initial shift state.. Changing the LC_CTYPE category causes the shift state of this function to be indeterminate.
The implementation will behave as if no function defined in this document calls wctomb().
If s is a null pointer, wctomb() returns a non-zero or 0 value, if character encodings, respectively, do or do not have state-dependent encodings..
None.
None.
None.
mblen(), mbtowc(), mbstowcs(), wcstombs(), <stdlib.h>.
Derived from the ANSI C standard. | http://pubs.opengroup.org/onlinepubs/007908775/xsh/wctomb.html | CC-MAIN-2014-52 | refinedweb | 166 | 63.8 |
I cannot seem to get my program to run. I know it seems like a simple program but i am new to this.
I am trying to:
- create a 5 element integer array
- cin 6 numbers
- then cout that array to see what my program looks like at runtime.
but keep getting errors. Here is what i have coded so far:
Code:#include<iostream> #include<string> using namespace std; using std::cin; int main() { //n is an array of 5 elements. int firstString[5]; cin >> int; cout << firstString << endl; cout << endl; cout << "firstString is: " << firstString << endl; cout << endl; for (int i = 0; firstString[i] != '\0'; i++) cout << firstString[i] << ' '; cout << endl; return 0; } | https://cboard.cprogramming.com/cplusplus-programming/36750-trying-create-5-element-integer-array.html | CC-MAIN-2018-05 | refinedweb | 113 | 73.07 |
Sque - Background job processing based on Resque, using Stomp
version 0.009
First you create a Sque instance where you configure the Stomp backend and then you can start sending jobs to be done by workers:
use Sque; my $s = Sque->new( stomp => '127.0.0.1:61613' ); # Or, for failover $s = Sque->new( stomp => [ '127.0.0.1:61613', '127.0.0.2:61613' ] ); $s->push( my_queue => { class => 'My::Task', args => [ 'Hello world!' ] });
You can also send by just using:
$s->push({ class => 'My::Task', args => [ 'Hello world!' ] });
In this case, the queue will be set automatically automatically to the job class name with colons removed, which in this case would be 'MyTask'.
You can set custom
STOMP headers by passing them in as follows:
$s->push( my_queue => { class => 'My::Task', args => [ 'Hello world!' ], headers => { header1 => 'val1', header2 => 'val2' } });
Additionally, the sque command-line tool can be used to send messages:
$ sque send -h 127.0.0.1 -p 61613 -c My::Task 'Hello world!'
Background jobs can be any perl module that implement a perform() function. The Sque::Job object is passed as the only argument to this function:
package My::Task; use strict; use 5.10.0; sub perform { my ( $job ) = @_; say $job->args->[0]; } 1;
Background jobs can also be OO. The perform function will still be called with the Sque::Job object as the only argument:
package My::Task; use strict; use 5.10.0; use Moose; with 'Role::Awesome'; has attr => ( is => 'ro', default => 'Where am I?' ); sub perform { my ( $self, $job ) = @_; say $self->attr; say $job->args->[0]; } 1;
Finally, you run your jobs by instancing a Sque::Worker and telling it to listen to one or more queues:
use Sque; my $w = Sque->new( stomp => '127.0.0.1:61613' )->worker; $w->add_queues('my_queue'); $w->work;
Or you can simply use the sque command-line tool which uses App::Sque like so:
$ sque work --host 127.0.0.1 --port 61613 --workers 5 --lib ./lib --lib ./lib2 --queues Queue1,Queue2,Queue3
This is a copy of resque-perl by Diego Kuperman simplified a little bit (for better or worse) and made to work with any stomp server rather than Redis.
A Stomp Client on this sque instance.
Namespace for queues, default is 'sque'
A Sque::Worker on this sque instance.
Pushes a job onto a queue. Queue name should be a string and the item should be a Sque::Job object or a hashref containing: class - The String name of the job class to run. args - Any arrayref of arguments to pass the job.
Example:
$sque->push( archive => { class => 'Archive', args => [ 35, 'tar' ] } )
Pops a job off a queue. Queue name should be a string. Returns a l<Sque::Job> object.
Concatenate
$self-namespace> with the received array of names to build a redis key name for this sque instance.
Build a Sque::Job object on this system for the given hashref(see Sque::Job) or string(payload for object).. | http://search.cpan.org/~wwolf/Sque-0.009/README.pod | CC-MAIN-2015-27 | refinedweb | 500 | 81.12 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi everyone,
I am trying to set up Eclipse for Processing and I followed Daniel's Processing in Eclipse tutorial on the website. But the sample code doesn't compile anymore in Eclipse. I do realize that the tutorial is for Processing 1.1+ and I am using 3a5. But I was wondering whether anyone has figured out what needs to be changed?
Below is the link to the tutorial.
And I basically followed it step by step and pasted the following code into Eclipse.
import processing.core.*; public class MyProcessingSketch extends PApplet { public void setup() { size(200,200); background(0); } public void draw() { stroke(255); if (mousePressed) { line(mouseX,mouseY,pmouseX,pmouseY); } } }
Eclipse shows a warning message that says "The serializable class MySketch does not declare a static final serialVersionUID field of type long" which I don't really understand what it means.
If anyone can help I would really appreciate it.
Thanks, Frank
You can ignore this warning. In fact you can ignore all warnings in Eclipse and still run the sketch, what you can't do is ignore errors.
I can see nothing in the code that would generate an error.
The name of the class MUST match the name of the file. I notice that the message says 'MySketch' but the class is called 'MyProcessingSketch' :-?
More pedantic: Name of the
publictop-class gotta match ".java"'s file name where it resides. :-B
Thanks quark and GotoLoop for your help. I checked the points both of you said and updated the project files and code to make sure everything matches but I still get the same error message. For the project, I am using JavaSE-1.6 as the JRE System Library. Does this matter?
Newest Processing versions are finally using Java 7! B-)
I guess I need to find out how to get Eclipse to corporate with Java 7. ;)
Before configuring Eclipse to use a chosen Java version, it gotta exist 1st!
Why don't you install latest Java SE 8u31 from the link below?
I have Java SE 8u31 installed already. I have started to look at how to set it up. It seems tricky. Thank you for your help GoToLoop!
As I said that the serializable message is a warning, it will NOT stop the sketch code above from compiling and running. If your code doesn't compile/run then something else is wrong. The Java version you are using will have not change the fact you get this warning.
Check the output in the Eclipse console for any messages.
Hi quark,
Thank you for your help. I was able to resolve the build path problem by change the JRE library back to 1.6. And now the project does not have any errors. But it still has this warning message says that "The serializable class HelloWorldApp does not declare a static final serialVersionUID field of type long" which I have no idea of what's causing it. When I run it below is the error message I see.
Exception in thread "main" java.lang.UnsupportedClassVersionError: HelloWorld I am still investigating what's causing it.
Thanks again for your help.
-Frank
You need to google 'Java serialization'
Probably the most common use of serialization is to save objects to disc. When an object is serialized it saves the object state (the values stored in the objects field) and information about the objects class. This can be deseriazed later to retrieve the object in its previous state.
If you save an object and then modify the class then it cannot be deserialised and throws an error. It is possible to generate a serial version ID which is a hash value created from the class source code, this can be used to test whether an object can be deserialized using the current version of the class.
To get rid of the warning click on the yellow symbol to the left of the
classline and either select the suppress warning option. Alternatively you can also create the serial version ID from the Eclipse menus, but you have to regenerate it everytime you modify the class source code.
This happens because your class inherits from PApplet which inherits from Applet which implements the
Serializableinterface.
I finally found time to figure out what was wrong. It's a stupid mistake. I didn't have JDK 8 installed on my Mac. After installed the latest JDK 8 from Oracle's website. Everything in the tutorial worked perfectly. Thanks both @quark and @GoToLoop for your help. | https://forum.processing.org/two/discussion/9419/daniel-s-processing-in-eclipse-tutorial-no-longer-works | CC-MAIN-2020-45 | refinedweb | 775 | 75.1 |
Using Audio Code
In order for RadCaptcha to be accessible by visually impaired users, the control can generate an audio code. Every alphanumeric character is read out using the NATO phonetic alphabet.
To enable this functionality you need to simply set the CaptchaImage-EnableCaptchaAudio property to true.
This will cause a link button, that retrieves the audio code, to be rendered below the CaptchaImage. To control the visual appearance of the link button, the user should use the .rcCaptchaAudioLink CSS class.
Since the Q3 2013 release of Telerik® UI for ASP.NET AJAX, RadCaptcha has an option for enabling a random background noise for the generated audio code in order to improve the control's security. This functionality can be used by setting the property CaptchaImage-EnableAudioNoise to true.
How the audio code is generated?
By default, the System.Speech.Synthesis namespace is used to "Speak" the randomly generated text code by default.
If you set the CaptchaImage-UseAudioFiles property to true, the audio code will be generated by concatenating
.wav files from the application directory.
This can be useful if you cannot provide elevated privileges for speech synthesis (see below), or it has poor performance, or you want to provide your own sounds.
In order for the Captcha to be able to output an audio file the web application must be run in a ASP.NET Full Trust level environment.
The application must run as a user account that has permissions to call the SpeechSynthesizer.Speak(textToSpeak) method on the server. Usually the user account does not have the needed permissions and the administrator has to grant them. For example in IIS 6+ the Application Pools run as the ApplicationPoolIdentity built-in account (this is by default) which does not have enough permissions to call SpeechSynthesizer.Speak(textToSpeak). To be able to generate the code the Application Pools should have permissions as the LocalSystem built-in account.
In case the web application does not have enough permissions to "Speak" the text code, the audio file will be generated by concatenation of ".wav" files that correspond to the specific character from the text code. By default RadCaptcha will look for the files in the ~/App_Data/RadCaptcha directory, so you need to supply the folder and the files. You can copy the App_Data\RadCaptcha directory located in the App_Data folder of your Telerik® UI for ASP.NET AJAX installation. A different location for the audio files can be used by setting the directory path to RadCaptcha's CaptchaImage-AudioFilesPath property.
In order for the audio code to be generated correctly when concatenating files, there must be a
.wavfile for every possible character that can appear on the image, and the file must be named as the character itself -
<Char>.wav(for example,.
A.wav,
B.wav,
C.wav,
1.wav,
2.wavand so on).
Tutorial - How to configure RadCaptcha to generate audio code?
The following tutorial demonstrates how to configure RadCaptcha to generate audio code.
Follow the steps from the "Getting Started" tutorial to create a web-site with RadCaptcha control.
In the Solution Explorer, right-click the project and select Add > Add ASP.NET Folder > App_Data.
Locate the App_Data folder in your Telerik® UI for ASP.NET AJAX installation.
Copy the App_Data\RadCaptcha to the project's ~/App_Data folder.
The project structure should now look like the screenshot below.
Enable the CaptchaAudio feature by setting the CaptchaImage-EnableCaptchaAudio property to true.
Press F5 to run the Application. RadCaptcha validates the input on a post back. | https://docs.telerik.com/devtools/aspnet-ajax/controls/captcha/functionality/using-audio-code | CC-MAIN-2021-10 | refinedweb | 585 | 50.02 |
8.2.
Subversion
If you read the previous section about using
git svn, you can easily use those instructions to
git svn clone a repository; then, stop using the Subversion server, push to a new Git server, and start using that. If you want the history, you can accomplish that as quickly as you can pull the data out of the Subversion server (which may take a while).
However, the import isn’t perfect; and because it will take so long, you may as well do it right. The first problem is the author information. In Subversion, each person committing has a user on the system who is recorded in the commit information. The examples in the previous section show
schacon in some places, such as the
blame output and the
git svn log. If you want to map this to better Git author data, you need a mapping from the Subversion users to the Git authors. Create a file called
users.txt that has this mapping in a format like this:
schacon = Scott Chacon <schacon@geemail.com> selse = Someo Nelse <selse@geemail.com>
To get a list of the author names that SVN uses, you can run this:
$ svn log ^/ --xml | grep -P "^<author" | sort -u | \ perl -pe 's/<author>(.*?)<\/author>/$1 = /' > users.txt
That gives you the log output in XML format — you can look for the authors, create a unique list, and then strip out the XML. (Obviously this only works on a machine with
grep,
sort, and
perl installed.) Then, redirect that output into your users.txt file so you can add the equivalent Git user data next to each entry.
You can provide this file to
git svn to help it map the author data more accurately. You can also tell
git svn not to include the metadata that Subversion normally imports, by passing
--no-metadata to the
clone or
init command. This makes your
import command look like this:
$ git-svn clone \ --authors-file=users.txt --no-metadata -s my_project
Now you should have a nicer Subversion import in your
my_project directory. Instead of commits that look like this
commit 37efa680e8473b615de980fa935944215428a35a Author: schacon <schacon@4c93b258-373f-11de-be05-5f7a86268029> Date: Sun May 3 00:12:22 2009 +0000 fixed install - go to trunk git-svn-id: 4c93b258-373f-11de- be05-5f7a86268029
they look like this:
commit 03a8785f44c8ea5cdb0e8834b7c8e6c469be2ff2 Author: Scott Chacon <schacon@geemail.com> Date: Sun May 3 00:12:22 2009 +0000 fixed install - go to trunk
Not only does the Author field look a lot better, but the
git-svn-id is no longer there, either.
You need to do a bit of
post-import cleanup. For one thing, you should clean up the weird references that
git svn set up. First you’ll move the tags so they’re actual tags rather than strange remote branches, and then you’ll move the rest of the branches so they’re local.
To move the tags to be proper Git tags, run
$ cp -Rf .git/refs/remotes/tags/* .git/refs/tags/ $ rm -Rf .git/refs/remotes/tags
This takes the references that were remote branches that started with
tag/ and makes them real (lightweight) tags.
Next, move the rest of the references under
refs/remotes to be local branches:
$ cp -Rf .git/refs/remotes/* .git/refs/heads/ $ rm -Rf .git/refs/remotes
Now all the old branches are real Git branches and all the old tags are real Git tags. The last thing to do is add your new Git server as a remote and push to it. Because you want all your branches and tags to go up, you can run this:
$ git push origin --all
All your branches and tags should be on your new Git server in a nice, clean import.
Perforce
The next system you’ll look at importing from is Perforce. A Perforce importer is also distributed with Git, but only in the
contrib section of the source code — it isn’t available by default like
git svn. To run it,, you’ll import the Jam project from the Perforce Public Depot. To set up your client, you must export the P4PORT environment variable to point to the Perforce depot:
$ export P4PORT=public.perforce.com:1666
Run the
git-p4 clone command to import the Jam project from the Perforce server, supplying the depot and project path and the path into which you want to import the project:
$ git-p4 clone /. It’s fine to keep that identifier there, in case you need to reference the Perforce change number later. However, if you’d like to remove the identifier, now is the time to do so — before you start doing work on the new repository. You can use
git filter-branch to remove the identifier strings en masse:
$ git filter-branch --msg-filter ' sed -e "/^\[git-p4:/d" ' Rewrite tool, or you otherwise need a more custom importing process, you should use
git fast-import. This command reads simple instructions from stdin to write specific Git data. It’s much easier to create Git objects this way than to run the raw Git commands or try to write the raw objects (see Chapter 9 for more information). This way, you can write an import script that reads the necessary information out of the system you’re importing from and prints straightforward instructions to stdout. You can then run this program and pipe its output through
git fast-import.
To quickly demonstrate, you’ll write a simple importer. Suppose you work in current, you back up your project by occasionally copying the directory into a time-stamped
back_YYYY_MM_DD backup directory, and you want to import this into Git. Your directory structure looks like this:
$ ls /opt/import_from back_2009_01_02 back_2009_01_04 back_2009_01_14 back_2009_02_03 current
In order to import a Git directory, you need to review how Git stores its data. As you may remember, Git is fundamentally a linked list of commit objects that point to a snapshot of content. All you have to do is tell
fast-import what the content snapshots are, what commit data points to them, and the order they go in. Your strategy will be to go through the snapshots one at a time and create commits with the contents of each directory, linking each commit back to the previous one.
As you did in the "An Example Git Enforced Policy" section of Chapter 7, we’ll write this in Ruby, because it’s what I generally work with and it tends to be easy to read. You can write this example pretty easily in anything you’re familiar with — it just needs to print the appropriate information to stdout. And, if you are running on Windows, this means you'll need to take special care to not introduce carriage returns at the end your lines — git fast-import is very particular about just wanting line feeds (LF) not the carriage return line feeds (CRLF) that Windows uses.
To begin, you’ll change into the target directory and identify every subdirectory, each of which is a snapshot that you want to import as a commit. You’ll change into each subdirectory and print the commands necessary to export it. Your basic main loop looks like this:
last_mark = nil # loop through the directories Dir.chdir(ARGV[0]) do Dir.glob("*").each do |dir| next if File.file?(dir) # move into the target directory Dir.chdir(dir) do last_mark = print_export(dir, last_mark) end end end
You run
print_export inside each directory, which takes the manifest and mark of the previous snapshot and returns the manifest and mark of this one; that way, you can link them properly. "Mark" is the
fast-import term for an identifier you give to a commit; as you create commits, you give each one a mark that you can use to link to it from other commits. So, the first thing to do in your
print_export method is generate a mark from the directory name:
mark = convert_dir_to_mark(dir)
You’ll do this by creating an array of directories and using the index value as the mark, because a mark must be an integer. Your method looks like this:
$marks = [] def convert_dir_to_mark(dir) if !$marks.include?(dir) $marks << dir end ($marks.index(dir) + 1).to_s end
Now that you have an integer representation of your commit, you need a date for the commit metadata. Because the date is expressed in the name of the directory, you’ll parse it out. The next line in your
print_export file is
date = convert_dir_to_date(dir)
where
convert_dir_to_date is defined as
def convert_dir_to_date(dir) if dir == 'current' return Time.now().to_i else dir = dir.gsub('back_', '') (year, month, day) = dir.split('_') return Time.local(year, month, day).to_i end end
That returns an integer value for the date of each directory. The last piece of meta-information you need for each commit is the committer data, which you hardcode in a global variable:
$author = 'Scott Chacon <schacon@example.com>'
Now you’re ready to begin printing out the commit data for your importer. The initial information states that you’re defining a commit object and what branch it’s on, followed by the mark you’ve generated, the committer information and commit message, and then the previous commit, if any. The code looks like this:
# print the import information puts 'commit refs/heads/master' puts 'mark :' + mark puts "committer #{$author} #{date} -0700" export_data('imported from ' + dir) puts 'from :' + last_mark if last_mark
You hardcode the time zone (-0700) because doing so is easy. If you’re importing from another system, you must specify the time zone as an offset. The commit message must be expressed in a special format:
data (size)\n(contents)
The format consists of the word data, the size of the data to be read, a newline, and finally the data. Because you need to use the same format to specify the file contents later, you create a helper method,
export_data:
def export_data(string) print "data #{string.size}\n#{string}" end
All that’s left is to specify the file contents for each snapshot. This is easy, because you have each one in a directory — you can print out the
deleteall command followed by the contents of each file in the directory. Git will then record each snapshot appropriately:
puts 'deleteall' Dir.glob("**/*").each do |file| next if !File.file?(file) inline_data(file) end
Note: Because many systems think of their revisions as changes from one commit to another, fast-import can also take commands with each commit to specify which files have been added, removed, or modified and what the new contents are. You could calculate the differences between snapshots and provide only this data, but doing so is more complex — you may as well give Git all the data and let it figure it out. If this is better suited to your data, check the
fast-import man page for details about how to provide your data in this manner.
The format for listing the new file contents or specifying a modified file with the new contents is as follows:
M 644 inline path/to/file data (size) (file contents)
Here, 644 is the mode (if you have executable files, you need to detect and specify 755 instead), and inline says you’ll list the contents immediately after this line. Your
inline_data method looks like this:
def inline_data(file, code = 'M', mode = '644') content = File.read(file) puts "#{code} #{mode} inline #{file}" export_data(content) end
You reuse the
export_data method you defined earlier, because it’s the same as the way you specified your commit message data.
The last thing you need to do is to return the current mark so it can be passed to the next iteration:
return mark
NOTE: If you are running on Windows you'll need to make sure that you add one extra step. As metioned directory you want to import into. You can create a new directory and then run
git init in it for a starting point, and then run your script:
$ git init Initialized empty Git repository in /opt/import_to/.git/ $ ruby import.rb /opt/import_from | git fast-import git-fast-import statistics: --------------------------------------------------------------------- Alloc'd objects: 5000 Total objects:_02_03
There you go — a nice, clean Git repository. It’s important to note that nothing is checked out — you don’t have any files in your working directory at first. To get them, you must reset your branch to where
master is now:
$ ls $ git reset --hard master HEAD is now at. | http://git-scm.com/book/th/v1/Git-and-Other-Systems-Migrating-to-Git | CC-MAIN-2015-35 | refinedweb | 2,096 | 67.99 |
I'm currently porting image style transfer neural networks to CoreML and it works great so far. The only downside is that the only output format seems to be a MLMultiArray, which I have to (slowly) convert back into an image.
Is there any chance we can get support for image outputs in the future? Or is there a way I can use the output data in Metal so I can do the conversion on the GPU myself?
Anyways, thanks for CoreML! It's great so far and I can't wait to see what's coming in the future.
Re: Support for image outputsFrankSchlegel Jul 2, 2017 2:02 PM (in response to FrankSchlegel)
I just tried to get the result into a Metal buffer to convert it in a compute shader, but I'm running into the issue that Metal doesn't support doubles. And CoreML seem to always return doubles in the output (even if I tell it to use FLOAT32 in the spec).
How does CoreML actually do it under the hood when the GPU doesn't support double precision?
Re: Support for image outputskerfuffle Jul 3, 2017 5:08 AM (in response to FrankSchlegel)
If your model outputs an image (i.e. something with width, height, and a depth of 3 or 4 channels), then Core ML can interpret that as an image. You need to pass a parameter for this in the coremltools conversion script, so that Core ML knows this output should be interpreted as an image.
Re: Support for image outputsFrankSchlegel Jul 3, 2017 5:53 AM (in response to kerfuffle)
How do I do that? The NeuralNetworkBilder has only a method for pre-processing image inputs, but not for post-processing outputs. If I try to convert the type of the output directly in the spec, the model compiles (and Xcode shows the format correctly), but the result is wrong.
Re: Support for image outputskerfuffle Jul 3, 2017 7:36 AM (in response to FrankSchlegel)
I guess the output only becomes an image if you specify `class_labels` in the call to convert(), but you're not really building a classifier so that wouldn't work. So what I had in mind is not actually a solution to your problem.
This is why I prefer implementing neural networks with MPS. ;-)
Re: Support for image outputsmichael_s Jul 3, 2017 11:07 AM (in response to FrankSchlegel)
While the NeuralNetworkBuilder currently does not have options for image outputs, you can use coremtools to modify the resulting model so that the desired multiarray output is treated as an image.
Here is an example helper function:
def convert_multiarray_output_to_image(spec, feature_name, is_bgr=False): """ Convert an output multiarray to be represented as an image This will modify the Model_pb spec passed in. Example: model = coremltools.models.MLModel('MyNeuralNetwork.mlmodel') spec = model.get_spec() convert_multiarray_output_to_image(spec,'imageOutput',is_bgr=False) newModel = coremltools.models.MLModel(spec) newModel.save('MyNeuralNetworkWithImageOutput.mlmodel') Parameters ---------- spec: Model_pb The specification containing the output feature to convert feature_name: str The name of the multiarray output feature you want to convert is_bgr: boolean If multiarray has 3 channels, set to True for RGB pixel order or false for BGR """: if is_bgr: output.type.imageType.colorSpace = ft.ImageFeatureType.ColorSpace.Value('BGR') else: output.type.imageType.colorSpace = ft.ImageFeatureType.ColorSpace.Value('RGB') else: raise ValueError("Channel Value %d not supported for image inputs" % channels) output.type.imageType.width = width output.type.imageType.height = height
Note: Neural Networks can output images from a layer (as CVPixelBuffer), but it clamps the values between 0 and 255. i.e. values < 0 become 0, values > 255 become 255.
You can also just keep the output an MLMultiArray and index into pixels with something like this in swfit:)])
Re: Support for image outputsFrankSchlegel Jul 3, 2017 1:49 PM (in response to michael_s)
I actually tried pretty much exactly that (tagging the output as image). But my problem is that I can't seem to get the CVPixelBuffer back into some displayable format. I gonna keep on trying.
I still don't really understand how CoreML can give me doubles when it's doing its computation on the GPU, though...
Re: Support for image outputsmichael_s Jul 3, 2017 3:27 PM (in response to FrankSchlegel)
What displayable format are you looking for? Here are some potentially useful methods for converting a CVPixelBuffer output into other representations:
Construct CIImage from CVPixelBuffer:
Construct UIImage from CIImage:
Construct a CV Metal Texture from existing CoreVideo buffer:
Re: Support for image outputsFrankSchlegel Jul 3, 2017 11:26 PM (in response to michael_s)
Thank's for your help, Michael.
It acutally works! As it turns out I kinda wasn't trying hard enough. I had the CIImage approach, but the image simply didn't show—neither when inspecting with Quick Look in Xcode nor when displaying in a view. Now I checked the memory and as it turnes out the alpha channel of the result is 0. So if I render it into a new context with CGImageAlphaInfo.noneSkipLast it works.
I can work with that, thanks!
Re: Support for image outputsBrianOn99 Jul 10, 2017 1:12 AM (in response to michael_s)
HI Michael, could the team responsible for coreml compiler set the alpha channel to 255 by default? Though it is not very inconvenience to set it ourself, I think it will confuse more people as time goes by.
Could it be considered a bug?
Re: Support for image outputsBrianOn99 Jul 7, 2017 2:09 AM (in response to michael_s)
To use the helper you provided, "convert_multiarray_output_to_image", does the model output dataType need to be DOUBLE or INT32, or both?
Re: Support for image outputsFrankSchlegel Jul 7, 2017 6:10 AM (in response to BrianOn99)
There is no requirement for the type, I think. The has to be in the shape (channels, height, width) and have either 1 or 3 channels. I guess the internal conversion step will handle the rest.
Re: Support for image outputsBrianOn99 Jul 9, 2017 7:22 PM (in response to FrankSchlegel)
Thanks a lot. I will try this out.
Re: Support for image outputsBrianOn99 Jul 9, 2017 11:10 PM (in response to FrankSchlegel)
Edit:
I have solved the problem by taking another approach. I take a CVPixelBufferGetBaseAddress(myCVPixelBuffer), and then directly set the alpha chennel to 255 to "remove" the alpha channel. This approach might be a bit raw as it use UnsafeRawPointer and assume the alpha pixels are located at 3, 7, 11, ... But at least it works.
[Old message]
I think I have got the same problem of getting a "not displayable format", in other word, the image does not show in quick look. I can already get the image when MLMutiArray is returned, but not when converted CVPixelBuffer in the mlmodel. Sorry I am quite new to ios development so I don't understand how to use "CGImageAlphaInfo.noneSkipLast". I guessed that I need to do the conversion cvPixelBuffer -> CIImage -> CGImage, and then create a CGContext with CGImageAlphaInfo.noneSkipLast, then draw the CGImage to the CGContext, finally get a CGImage from the CGContext.
But somehow the image becomes black. Is the Is this the correct approach? Could you please share some steps of your approach?
Thanks for your many helps.
Re: Support for image outputsFrankSchlegel Jul 10, 2017 12:06 AM (in response to BrianOn99)
For me this works without changing the pixel buffer (output is your CVPixelBuffer):
CVPixelBufferLockBaseAddress(output, .readOnly) let width = CVPixelBufferGetWidth(output) let height = CVPixelBufferGetHeight(output) let data = CVPixelBufferGetBaseAddress(output)! let outContext = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(output), space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)! let outImage = outContext.makeImage()! CVPixelBufferUnlockBaseAddress(output, .readOnly)
Re: Support for image outputsBrianOn99 Jul 10, 2017 1:05 AM (in response to FrankSchlegel)
Thanks!
Re: Support for image outputslozanoleonardo Jul 9, 2017 11:03 PM (in response to michael_s)
Hey Michael, can I use this script to conver my MLMultiArray input to be an Image instead? I'm guessing that it needs to consider
spec.description.input
in this case.
Re: Support for image outputsBrianOn99 Jul 9, 2017 11:23 PM (in response to lozanoleonardo)
Just for your reference, if you network orginal output shape is [3, 511, 511] then after conversion to CVPixelBuffer as output, the diff is only:
--- oil_mlmodel_yespost.pb 2017-07-10 11:00:21.078301960 +0800 +++ oil_mlmodel_yespost_cvbuffer.pb 2017-07-10 10:59:38.374233180 +0800 @@ -13,11 +13,10 @@ output { name: "output" type { - multiArrayType { - shape: 3 - shape: 511 - shape: 511 - dataType: DOUBLE + imageType { + width: 511 + height: 511 + colorSpace: RGB } } }
And in my case I just need to run convert_multiarray_output_to_image(tm, 'output'), where tm is my model. I don't need to specify the input.
Re: Support for image outputslozanoleonardo Jul 10, 2017 10:38 PM (in response to BrianOn99)
I guess my question is about converting the input type MLMultiArray to Image instead of the output.
Re: Support for image outputsBrianOn99 Jul 12, 2017 3:48 AM (in response to lozanoleonardo)
Sorry I misunderstood that.
Conversion of input to image is usually achieved by supplying the parameter "image_input_names" in the coreml conversion function. Why didn't you take that approach?
Re: Support for image outputslozanoleonardo Jul 14, 2017 2:40 PM (in response to BrianOn99)
Oh, I didn't take that approach becuase a couple of user in stackoverflow reported that this approach didn't work and provided the link to this thread. I guess it's my fault that didn't try before asking.
Thanks again.
Re: Support for image outputsfakrueger Aug 23, 2017 8:13 PM (in response to michael_s)
Thanks for those details, it really helped! One question though:
How would you apply scale and biases to the image data before conversion? For instance, my network outputs in the range [-1, 1] and I need to convert that to [0, 255].
When using the Keras converter, the input image can thankfully be scaled and biased. Can that code be reused somehow?
Re: Support for image outputsBrianOn99 Aug 24, 2017 2:21 AM (in response to fakrueger)
I have tackled a similar problem (subtract VGG constants) of post processing by manually inserting some 1x1 convolution. For your particular problem, you may try adding a 1x1x3x3 (1by1 kernel, 3 for image channel) conv layer of weight
[127.5, 0, 0
0, 127.5, 0
0, 0, 127.5]
and bias
[127.5, 127.5, 127.5]
Place it after you model's final layer.
This operation will scale each channel seperately into [-127.5, 127.5] and then add 127.5 into each channel. I have not tried it, just to give you a direction to work on.
As an aside, resetting alpha channel is no longer required at xcode beta 5.
Re: Support for image outputsFrankSchlegel Aug 24, 2017 2:47 AM (in response to BrianOn99)
There's actually a bias layer in the spec that does exactly that. No need for the work-around. Here is my helper for the NeuralNetworkBuilder:
def _add_bias(self, name, bias, shape, input_name, output_name): """ Add bias layer to the model. Parameters ---------- name: str The name of this layer. bias: numpy.array The biases to apply to the inputs. The size must be equal to the product of the ``shape`` dimensions. shape: tuple The shape of the bias. Must be one of the following: ``[1]``, ``[C]``, ``[1, H, W]`` or ``[C, H, W]``. input_name: str The input blob name of this layer. output_name: str The output blob name of this layer. """ nn_spec = self.nn_spec # Add a new bias layer spec_layer = nn_spec.layers.add() spec_layer.name = name spec_layer.input.append(input_name) spec_layer.output.append(output_name) spec_layer_params = spec_layer.bias spec_layer_params.bias.floatValue.extend(map(float, bias.flatten())) spec_layer_params.shape.extend(shape) _NeuralNetworkBuilder.add_bias = _add_bias
Re: Support for image outputsadib Dec 27, 2018 1:29 AM (in response to FrankSchlegel)
How to incorporate the bias layer to the conversion process?
Re: Support for image outputsktak199 Oct 14, 2017 1:47 AM (in response to michael_s)
I'm trying to convert outputs of mlmodel to UIImage, but it's not working...
outputs of mlmodel : Image(Grayscale width x height)
guard let results = request.results as? [VNPixelBufferObservation] else{ fatalError("Fatal error")} print(String(describing: type(of: results)) print(String(describing: type(of: results[0]))) let ciImage = CIImage(cvPixelBuffer: results[0].pixelBuffer)
Outputs:
Array<VNPixelBufferObservation>
VNPixelBufferObservation
Error occurs on line 04 :
Thread 1: EXC_BAD_ACCESS (code=1, address=0xe136dbec8)
-------------------------------------------------------------------------------------------
I'm trying to keep mlmodel MultiArray.
outputs of mlmodel : MultiArray (Double 1 x width x height)
guard let results = request.results as? [VNCoreMLFeatureValueObservation] else{ fatalError("Fatal error")} print(String(describing: type(of: results)) print(String(describing: type(of: results[0])) print(String(describing: type(of: results[0].featureValue))) print(results[0].featureValue) print(results[0].featureValue.multiArrayValue) let imageMultiArray = results.[0].featureValue.multiArrayValue)])
Outputs:
Array<VNCoreMLFeatureValueObservation>
VNCoreMLFeatureValueObservation
Optional<MLFeatureValue>
Optional(MultiArray : Double 1 x width x height array)
Optional(Double 1 x width x height array)
Error occurs on line 19 :Use of unresolved identifier 'Unit8
shoud be replaced by Uint8 ? and how to convert to UIImage?
Thank you for your any help in advance!
Re: Support for image outputsFrankSchlegel Oct 16, 2017 11:38 PM (in response to ktak199)
Yes, Unit8 is a typo and should be Uint8.
But regardless, you should really try to adjust the spec of your model to produce image outputs (instead of an multi-array). This way you should be able to get the pixel buffer directly from the prediction. In the answer above you can see the Python function that can do that for you.
Re: Support for image outputsktak199 Oct 17, 2017 5:53 AM (in response to FrankSchlegel)
Thank you for your response.
The output of my mlmodel is already image outputs (Grayscale width x height).
Error does not occur in getting outputs on line1.
But error occurs when I try to access to pixelBuffer on line 04
Error message: Thread 1: EXC_BAD_ACCESS (code=1, address=0xe136dbec8)
guard let results = request.results as? [VNPixelBufferObservation] else{ fatalError("Fatal error")} print(String(describing: type(of: results)) //->Array<VNPixelBufferObservation> print(String(describing: type(of: results[0]))) //->VNPixelBufferObservation let ciImage = CIImage(cvPixelBuffer: results[0].pixelBuffer)
Thank you.
Re: Support for image outputsFrankSchlegel Oct 17, 2017 5:56 AM (in response to ktak199)
Ok, that's indeed strange. Do you get any console output?
Also maybe try to use your model with CoreML directly, without Vision. Do you get the same error there?
Re: Support for image outputsktak199 Oct 17, 2017 6:51 AM (in response to FrankSchlegel)
print(String(describing: type(of: results)) print(String(describing: type(of: results[0]))) let ciImage = CIImage(cvPixelBuffer: results[0].pixelBuffer)
Output is
Array<VNPixelBufferObservation>
VNPixelBufferObservation
Thread 1: EXC_BAD_ACCESS (code=1, address=0xe136dbec8)
How to use CoreML directly, without Vision? Any URL?
Re: Support for image outputsFrankSchlegel Oct 17, 2017 11:17 PM (in response to ktak199)
It's a bit tedious because you have to do the pixel buffer conversion yourself. Check out the repo hollance/CoreMLHelpers on Github so see how it's done (sorry for no link, but wanted to avoid waiting for moderation).
Re: Support for image outputsktak199 Oct 17, 2017 9:51 PM (in response to FrankSchlegel)
It worked! Thank you.
Re: Support for image outputsFrankSchlegel Oct 17, 2017 11:19 PM (in response to ktak199)
Glad to hear that!
It's a bit curious that it's not working with Vision, though. Maybe it's because your output is grey-scale and Vision expects RGB?
Re: Support for image outputsOliDem Nov 5, 2017 1:40 PM (in response to FrankSchlegel)
Dear Frank and ktak199, I think I am facing the same issue.
I converted my torch-model for style transfer to coreml using the torch2coreml converter.
As soon as I access the pixelBuffer property of the VNPixelBufferObservation in the completionHandler of the VNCoreMLRequest, the program crashes with EXC_BAD_ACCESS.
Can you confirm that this problem is caused by using the vision framework, and not by the model conversion procedure?
So, if I use „plain“ CoreML, chances are high that the model will work?
Thanks a lot in advance
Oliver
Re: Support for image outputsFrankSchlegel Nov 8, 2018 1:02 AM (in response to OliDem)
Hey Oliver,
Sorry for the late response.
While I can't confirm that this is definitely an issue with the Vision framework, I would at least recommend you give the manual approach a try. It's not that hard and it gives you much more control over the conversion. I don't know why Vision can't handle your model output, though.
Re: Support for image outputstyro tyro Jun 17, 2018 12:04 AM (in response to michael_s)
Unlike others who have used this(forcing the model to output an image) method and gotten back CVPixelBuffers with alpha 0, I am getting back an alpha of 255 and r,g,b in [0,1]. Ignoring the alpha channel, PIL displays an image that is definitely related to the desired output. Could it have something to do with the image scale/rgb biases when i convert the model from keras? I am not really sure where to go with this, we're trying to convert the CVPixelBuffer output into a MetalTexture and want to avoid extra post-processing steps.
For clarity: I am converting from keras to coreML, and then calling "convert_multiarray_output_to_image(...)" on the coreML model. I have an image scale of 1/127.5 and rgb biases of -1 at the keras conversion step.
Re: Support for image outputsadib Apr 25, 2019 10:23 PM (in response to tyro tyro)
You probably need to alter the resulting Core ML model using the coremltools library (Python side). In short, add a bias layer at the end which performs the final linear transformation that you need.
I’ve written it out in detail here:
That took me a few weeks to figure out, hence I made a post that’s hopefully useful (and hopefully the functionality can be built into coremltools itself).
Re: Support for image outputs_newcoder_ Feb 7, 2018 5:00 AM (in response to FrankSchlegel)
array_shape = tuple(output.type.multiArrayType.shape)
This is returning an enpty tuple. I checked the shape of my model on xcode and the dimension is 1*1*2*224*224 which i guess corresponds to channel=2,height=224,width=224(no idea about other two dimensions). So my question is why empty tuple is being returned ?
And also i want to know what does channel value 2 represent??? The output of my model was suppossed to be grayscale , so value should have been 1 i guess.
Thanks in advance!!!
Re: Support for image outputsFrankSchlegel Feb 7, 2018 5:21 AM (in response to _newcoder_)
Hmm, it seems there is something off with your model spec. Can you maybe print output and post it here? It should have a 3-dimensional shape and only one channel if it's a grayscale image.
The first two dimensions you see are used for internal batch processing and should actually not be exposed in the output of the model.
Re: Support for image outputsbruce25796 Nov 7, 2018 12:48 AM (in response to FrankSchlegel)
Dear Developers:
I transform a Keras model of input a gray single-channel image and output a gray single-channel image.
In using a "coremltools", coremltools.converters.keras.convert , setting
----------------------
coreml_model = coremltools.converters.keras.convert(model, input_names = 'data',
image_input_names='data',
output_names='outputImage',
image_scale= 1/255.0)
------------------------
coreml_model only sets Inputs data: Image(Grayscale 256x256)
Outputs outputImage:MutliArray( Double 1x256x256)
if writing codes below,
--------------------------
def convert_multiarray_output_to_image(spec, feature_name, is_bgr=False)::
spec = coreml_model.get_spec()
convert_multiarray_output_to_image( spec, 'outputImage', is_bgr=False)
newModel = coremltools.models.MLModel(spec)
------------------------
coreml_model only sets Inputs inputImage: MutliArray( Double 1x256x256 )
Outputs outputImage:Image( Grayscale 256x256)
Question:
Is there any way to output coreml_model as below ?
Inputs inputImage: image( Grayscale 256x256 )
Outputs outputImage:Image( Grayscale 256x256)
Thanks
Re: Support for image outputsFrankSchlegel Nov 8, 2018 11:56 PM (in response to bruce25796)
Hi Bruce,
You also need to convert the input into an image. You can do that using the same method as for outputs. Just replace all instances of "output" with "input" in your convert_multiarray_output_to_image method and you got yourself a convert_multiarray_input_to_image method. Then you just need to apply that to the spec as well before creating your model. | https://forums.developer.apple.com/message/338972 | CC-MAIN-2019-51 | refinedweb | 3,381 | 54.93 |
How do I print the complete trace using the python reader api of babeltrace ?
Using below I can get the fields of an event, but how can I print the complete trace as babeltrace does.
import babeltrace
import sys
trace_collection = babeltrace.TraceCollection()
trace_path = sys.argv[1]
trace_collection.add_traces_recursive(trace_path, 'ctf')
for event in trace_collection.events:
print event.timestamp, event.cycles, event.name
for event in trace_collection.events:
for field in event.items():
print field
[2015-10-20 15:16:34.600508066] (+1.481059687) samplehost sample_trace_provider:INFO: { cpu_id = 1 }, { fileAndLine = "sampletest.cpp:330", msg = "Directing trace stream to channel #0" }
You can't do this in a single statement as you would expect. This is because the Babeltrace Python bindings classes do not implement
__str__ recursively.
The default output format you're getting when running the
babeltrace command is called ctf-text and is implemented in C. There is certainly a way to replicate ctf-text's output, but you would need to implement a pretty-printer manually in Python. | https://codedump.io/share/gEiCr7MvfWnJ/1/how-to-print-complete-trace-event-using-babeltrace-python-api | CC-MAIN-2017-04 | refinedweb | 169 | 52.66 |
chalst: Thanks for your highly relevant comments. Let me see if I can answer.
"You don't need to encode first-order terms as singleton second-order variables..." Right. Actually, thanks for reminding me about the need to quantify over things like total functions. I was pretty much only thinking about building them up as terms, for which the proof that the function is total follows directly from the structure. For quantifiers, probably the easiest technique is to put this predicate into an assumption.
"...you may not be respecting the distinction between the set of total functions and the set of function that SOA can prove total." This is entirely possible. Presumably, the important difference is that you you quantify over the total functions, but when you build up from terms, you're restricted to the provably total. I'm not sure yet how this might bite me.
"Finally, you need to check your translation actually captures the properties you are after." Actually, I may take the heretical position that this is not necessary. You may want to allow the translation to have essentially arbitrary properties. Of course, in many cases there will be a meaningful translation back from target language to source language, and it may be worth capturing that formally.
Your point about a rich set of datatypes is well taken. Basically, what I'm trying to figure out is whether such a set of datatypes can be mapped to a simple Z_2 axiomatization using a straightforward definitional scheme. I'm not even sure that growth in the size of propositions matters much: as I said, in most cases, you won't be doing the translation explicitly.
What's the best source to read about these things, especially the polymorphic lambda calculus systems with the same provability strength as Z_2?
I poked around at Google Answers a bit. It seems like a useful service, but I don't see any reason to get excited about it. There are two features I might have hoped for.
First, I don't see that the Answers provided help, or even particularly influence, the results of ordinary searches. This is disappointing, because it seems to me that Google's trust metric has the best chance of working when there's high quality manual input, especially regarding the trusted "seed". It's entirely possible that Google has two completely disjoint sets of people manually reviewing Internet sites (one set for Answers, another for deciding the seed), but that they don't talk to each other. I'm not sure.
The second missing feature is a bit harder to define, but it has to do with whether Answers is a true community. There are glimmerings of this. For example, having all the questions and Answers posted, along with comment posting open to all users, is cool. Many of the questions are interesting, and I can see people hanging out there. Another pro-community sign is that ordinary users and Researchers share the same namespace in the account/login system.
Most importantly, a lot of the Researchers seem to know each other, so there is something of a community there. But users don't really get to take part in it, even when (or perhaps because) they buy in monetarily. Part of the problem may be the way identities are concealed
If Google (or somebody else) figured out a way to build a real knowledge-seeking community, with money lubricating the system, I think they'd have something big. As it is, they have a reasonable service with a solid-gold brand behind it. | http://www.advogato.org/person/raph/diary.html?start=293 | CC-MAIN-2017-04 | refinedweb | 599 | 62.68 |
Created on 2003-02-05 11:00 by jneb, last changed 2003-04-29 21:51 by jackjansen. This issue is now closed.
This is a bug and a partial patch.
If I debug a program that contains a ridiculously large array (8M entries in my case), the debugger takes forever.
It happens in Mac OS X, Python 2.2, but I found the bug in is the repr module, so it is probably universal.
The thing is, that after the fix below, it still doesn't work!
Did I miss something trivial (like repr is builtin, or something like that?). Would someone with Mac OS X experience help out here, please (Jack?).
Here's the diff to make repr.repr work with large arrays:
13a14
> self.maxarray = 5
50a52,62
> def repr_array(self, x, level):
> n = len(x)
> if n == 0: return header+"])"
> if level <= 0: return header+"...])"
> for i in range(min(n, self.maxarray)):
> if s: s = s + ', '
> s = s + self.repr1(x[i], level-1)
> if n > self.maxarray: s = s + ', ...'
> return header + s + "])"
Logged In: YES
user_id=31435
Nice to see you, Jurgen! I checked this into current CVS,
and it works fine for me in isolation:
>>> len(a)
11055060
>>> repr.repr(a)
"array('i', [0, 1, 2, 3, 4, ...])"
>>>
That goes in an eyeblink. So more detail is needed about
what "it still doesn't work!" means. Assigned to Jack, and he
can use current CVS to try it.
Lib/repr.py; new revision: 1.15
Lib/test/test_repr.py; new revision: 1.16
Misc/NEWS; new revision: 1.642
Logged In: YES
user_id=45365
The fix is fine (it works for me the same way as for Tim), but I think we're shooting past the problem here.
First, pdb doesn't use repr.repr(), it uses the normal builtin repr().
Second, I don't see any sluggishness in pdb with large arrays. I tried
debugging
def foo():
a = range(8000000)
and there was no problem. Allocating the object took a bit of time, yes, and if you actually try to print it you'll stare at about 800K lines filled with digits scrolling over your screen, but that is to be expected.
Could it be your sluggishness is coming from something else? For example, MacOSX starts behaving *very* badly if your root disk is full, because then it can't allocate swap space, and due to its optimistic behaviour it comes to a grinding halt.
Logged In: YES
user_id=31435
pdb does import repr.py, but probably doesn't use it in
whatever way Jurjen is using to display his big array.
WRT that, note that Jurjen is using array.array objects, not
lists. The internal array.array tp_repr slot is quadratic-time in
the size of the array, while list's tp_repr is linear time.
Logged In: YES
user_id=45365
Okay, so the real bug is that tp_repr of array objects takes quadratic time.
I'm changing the summary of this report then, and assigning back to you (Tim), on the basis that you did more checkins on arraymodule than I did. Feel free to pass the potato on:-)
Logged In: YES
user_id=31435
I can't make time for this, so unassigned it. It would make
a good, brief project for someone -- the list and dict
tp_reprs are linear-time, and tp_repr for array.array
objects shouldn't be any harder than they were.
Logged In: YES
user_id=699438
arraymodule's repr used "string += ',' + el" for each element in
the array. Lists and dicts did a string.join to build the repr.
Attached patch builds a tuple of array elements and then
joins them. (actually for some reason I can't attach now, I'll
post the patch in patch manager)
This fixes the time issue, but I don't know enough about how
you guys manage memory in each case to tell what impact
that'll have on really, really big arrays (although I imagine it
takes more memory).
Logged In: YES
user_id=80475
Fixed this up by converting the array to a list and then
using the list object's efficient repr().
See Modules/arraymodule.c 2.87.
Since I categorize this as a performance issue and not a
bug, I've applied the fix to Py2.3 but am not
recommending for backport.
Logged In: YES
user_id=446428
The debugger I use, is not pdb, but the Mac only IDE debugger. I thought
this was only a front end on pdb, but it apparently is not.
It seems that it is still slow in 2.3. (I can't check it at the moment, I am
running a multiple hour computation...)
May it will automatically be fixed if Jack manages to get IDLE working on the
Mac...
Logged In: YES
user_id=45365
Jurjen,
could you submit a separate bug report for the MacPython IDE? It needs a
different solution (and I'm not going to come around to it soon, so otherwise
I may forget). | http://bugs.python.org/issue680789 | CC-MAIN-2017-17 | refinedweb | 838 | 83.76 |
Opened 8 years ago
Closed 8 years ago
#4751 closed Bugs (fixed)
Breaking change between 1.41 and 1.44in split
Description
I noticed a breaking change in the split function when the input string is empty. Consider the following example:
#include <string> #include <vector> #include <iostream> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp>
int main() {
std::vector<std::string> result; std::string empty_string; boost::algorithm::split( result,
empty_string,boost::algorithm::is_any_of( "\t" ),boost::algorithm::token_compress_off);
std::cout << "result size: " << result.size() << std::endl; return 0;
}
With boost 1.41 I get: result size: 1 With 1.44 I get: result size: 0
Meaning that splitting an empty string now has a new meaning. All I found to this subject was that 1 seems to be the correct answer (). Furthermore, there has been, according to the release notes, no change to string algo since the 1.41.
Attachments (0)
Change History (5)
comment:1 Changed 8 years ago by
comment:2 Changed 8 years ago by
comment:3 Changed 8 years ago by
Actually, there was one change. A small fix, that should not have such an effect. But it might be possible that the fix uncovered another problem. Anyway I will fix the issue soon. Just give me a coupe of days.
comment:4 Changed 8 years ago by
I have just commited the fix into the trunk. But I probably cannot merge to the release now. Sorry I was not able to fix it sooner.
It's not apparent to me that new behaviour is wrong. Anyway, how about looking at SVN log to determine who changed that, and talk to that person?
I'm marking this Showstopper since Eric expressed a wish to have this resolved for 1.45. | https://svn.boost.org/trac10/ticket/4751 | CC-MAIN-2018-26 | refinedweb | 297 | 67.76 |
Requires 0.0.3')
Note.
You can now download the package with PIP, and it is available under the name Requires. Feel free to require it within any of your unit test suites. You can easily install the package with the following command:
$ pip install Requires
Overview
Requires uses a chainable object in order to create tests that are really concise and readable. It is meant for use in the BDD style, i.e.:
from requires.expect import expect from library import function res, err = function(0) expect(err).to.Not.exist() expect(res).to.be.equal(1)
- Downloads (All Versions):
- 15 downloads in the last day
- 152 downloads in the last week
- 519 downloads in the last month
- Author: Eugene Eeo
- Bug Tracker:
- Package Index Owner: eugene-eeo
- DOAP record: Requires-0.0.3.xml | https://pypi.python.org/pypi/Requires/0.0.3 | CC-MAIN-2015-32 | refinedweb | 136 | 60.14 |
been doing python, and im not that great at it, but am trying to learn the ins and outs.
im having a problem with some code, this is what i want;
*user inputs some information after a question* this is an interger under a word... here's some code to explain:
aaoc=raw_input("enter your selection, between 1-9:")
I then want to do something like the following...
import random
random.randint(1,aaoc)
I'm sure you can see what im trying to do, simply give the user a range option on a random output.
I've never really understood the conversions, I'm guessing ill need to add some "str" somewhere, I've tried a few spots and none work.
Thanks in advance, having this answered if possible will clear ALOT up for me, because int and str functions i never actually caught onto when in class.
p.s my programming jargon sucks, so i probably look silly, hope you don't mind
edit: i also realize this isn't really a spot to ask python support, but i've seen some of the stuff some of you have said regarding python and you all seem quite knowledgeable, and im unsure where else to ask.
Use "input" rather than "raw_input", as raw_input will always give you a string.
aaoc = input("enter your selection, between 1-9:")
Then you can use this to verify the input:
assert(type(aaoc) is int and 1 <= aaoc <= 9)
This verifies that aaoc is an int and is a value between 1 and 9.
thanks for your help
Develop games in your browser. Powerful, performant & highly capable.
Ahhh Python.
I will have to sit down and learn all the syntaxical nuances with the language sometime.
Its good to know some of you guys here are well-versed in it already. | https://www.construct.net/en/forum/construct-classic/help-support-using-construct-38/python-help-30640 | CC-MAIN-2022-27 | refinedweb | 307 | 67.59 |
Art of Unix Programming is certainly not a beginner's
programming manual. It assumes, instead, that the reader is already a
competent hacker and is looking to learn more about the Unix way of doing
things. So there is a lot of talk about philosophy and history, and a
wealth of case studies. There is a lot of language like:
Eric would, seemingly, like his book to be seen as a successor to the
Kernighan and Plauger classics The Elements of Programming Style and
Software Tools. This book shows some of the classic Raymond traits:
no less than six case studies feature fetchmail (which he wrote), and the
examples demonstrating the fortune file format are all about the evils of
gun control.
But there is some good stuff in there which has not necessarily been
written down before. Eric is a good writer, and he has experience in the
realm he is writing about. The Art of Unix Programming is worth a
look.
We asked Eric a few questions about the draft release; here are his
answers.
LWN: If you could characterize the art of programming in/for Unix as
described in your book, in a single paragraph, how would you do it?
ESR:
I'll do better, I'll boil it down to a single phrase. Keep it simple, stupid!
The true art of programming -- and this is something Unix guys were
arguably the first to figure out and the most consistent at applying --
is minimizing global complexity. Most of the rest of the Unix philosophy
pretty much falls out of that.
LWN:
The draft as posted does not include any sort of licensing; will the final
version be available under a free license?
ESR:
Yes, but I haven't decided which one. There will be some restrictions
on print reproduction, but none on electronic.
LWN:
When you first announced the book project, it seemed you were planning to
put the chapters out gradually and make use of a lot of community input.
After chapter four, however (released almost exactly two years ago), things
went quiet, and the rest of the book, seemingly, was done in a "cathedral"
mode. Why is that? Did the more open approach not work out?
ESR:
No, it's just that I stalled out for a long time and then gave it six
weeks of intense work. This happened after an acquisitions editor at
Addison-Wesley called me and said "Uh. Apparently you had an
agreement to do a book with my predecessor, but I can't find a
contract." There wasn't one; I have a twitch that way, I don't sign a
contract until the book is essentially complete. He successfully
nudged me into working on it again.
LWN:
The book talks little about the programming of complex graphical
applications, and avoids the GNOME/KDE issue altogether. Yet one could
argue that complex applications are a big part of the future of Unix-like
systems. There is often, however, a sort of impedance mismatch between
fancy applications (think StarOffice 5) and the Unix way of doing things.
What suggestions do you have for authors of graphical applications to help
them carry forward the Unix tradition in the graphical world?
ESR:
Separate policy from mechanism, because policy ages much faster than
mechanism. Separate engines from interfaces, because tangling the two
together tends to lead to unmaintainable messes. Don't give it a GUI
if it doesn't need one.
Policy-mechanism separation is a major theme in the book. It's
usually thought of in connection with X, but it can be applied a lot
more widely -- and, in fact, Unix programmers *do* apply it a lot more
widely without being really aware of the principle consciously.
(Yes, that's right, I'm doing another yet another book that's
basically about conscious expression of unconscious folk practices.
This would be #3. Is there anybody left who still finds this
surprising? No? I thought not... :-))
One of the insights I got, one that's especially applicable to big
gnarly GUI applications, is that Unix programmers divide all Gaul into
three parts -- policy, mechanism, and glue. Mechanism is code that
tells how to do things, policy is code that tells what to do -- and glue
is the stuff that binds policy and mechanism together.
The punch line: glue is evil and must be destroyed, or at least minimized.
Your typical huge honkin' C++ application with classes stacked twelve
deep is an unmaintainable mess because the top two layers are policy,
the bottom two are mechanism, and the middle eight are glue. And the
trouble with glue is that it's opaque -- it impedes your ability to see
clear down through the system from the top, or clear up from the bottom.
You can't debug what you can't see through, because you can't form an
adequate mental model of its behavior.
So my advice to GUI programmers is this: Decide what's policy and
what's mechanism. Separate them cleanly -- ideally, have the GUI and
engine running in separate processes, like gv and ghostscript or
xcdroast and cdrecord. Then *ruthlessly eliminate all glue*. Or
as much of it as you can, anyway.
LWN:
There is very little treatment of security in the book. Why is that? Is,
in your mind, security peripheral to the main art of Unix programming, or
is something else going on?
ESR:
It's peripheral. This is not a book about system administration, it's
about how to design well. There's an aspect of that that has to do with
secirity of course, but most of the things that make for good security
(like minimizing code that has to be trusted) are just good engineering
practice. That I *do* talk about a lot.
LWN:
Unix has had a long run in the computing world, and, by all indications, it
has a while to go yet. All good things come to an end eventually,
however. What do you think might bring about the end of the Unix era, and
what might replace Unix in the future?
ESR:
My money is on capability-based persistent-object systems like EROS.
But prophecy is difficult, especially about the future.
[This article was contributed by Joe 'Zonker'
Brockmeier]
The.
Page editor: Jonathan Corbet
Security
Brief items
[This article was contributed by Tom Owen]
Being sued is one possible outcome.
In Europe,
criminal charges are possible, though unlikely.
Even if all you have to worry about is an embarrassingly public gap between
your privacy policy
and your real operations, it may be time to look more closely
at what might emerge if your data partitions ended up on eBay.
The problem is that the ordinary techniques of host security are useless
against an explorer who can install your disks in a lab machine.
0600 modes won't be noticed by an attacker who is root already.
Wipes and sanitizers won't have been used if the equipment was stolen.
The only option is to encrypt the information you don't want to leak.
If you do it right you can publish the contents of your disks without a qualm.
Encryption is doubly important for Linux administrators because the range of
software is so great that failure to encrypt is that much less excusable.
The only plausible objections relate to performance and convenience issues.
In the past, the US imposed export restrictions on cryptographic software.
Those rules obliged Linux kernels from
kernel.org to
exclude cryptographic software.
Something like that never stops hackers,
and the kernel code for encrypted disks and networks was hosted
and has continued
outside the US. The 2.5 kernel has
crypto built in, but users of the current stable kernels must get their
encryption code from another source.
Incorporating crypto code into a standard kernel is
well
documented
but it's simpler to use a distribution like SuSE which includes crypto out of
the box.
Beyond the offerings from your distribution the broad choice is rather daunting.
The
standard approach
uses encryption in the loopback device to create
a secure partition "hosted" in a big contiguous file.
A filesystem can be created on that device and mounted as the data directory.
The host file is unintelligible without the passphrase.
Encrypted loopback can't handle swapfiles,
and so there's a risk of leaving decrypted application information on the disk.
If you can't configure enough memory,
ppdd,
which layers encryption on top of the plain loopback device
does support swap files.
Other
approaches
like CFS don't use loopback, instead running a userspace daemon to encrypt
on a file by file basis.
These suffer under I/O load and wouldn't be a good choice to host a database.
All of this is relatively well documented.
But the manuals seem to skate around the hard problems:
It's unfortunate that the commonest server setup, remote hosting,
is one of the toughest operational security challenges.
But if remote servers are the only possible answer,
then encryption security is still possible.
Linux is solid enough that unattended restart isn't strictly necessary.
Instead, the machine can boot far enough to page the admin to ssh in and mount
the loopback devices.
And a backup can be prepared on the encrypted volume and
once it's
re-encrypted
with the admin's public key any transfer method will do.
This is all convoluted to say the least.
It's not standard, and it goes beyond what's commonly done.
It's easy to feel that keeping the site going and current is challenge enough.
But if you take privacy seriously there are no other choices.
Once your hosts are as secure as you can make them against attacks from
the network,
it's time to move up a level.
If you have other people's personal data,
you should probably encrypt it.
New vulnerabilities
An attacker could craft a long filename for an attachment that would
overflow two buffers when a certain option for interactive use was
given, opening the possibility to inject arbitrary code. This code
would then be executed under the user id hypermail runs as, mostly as
a local user. Automatic and silent use of hypermail does not seem to
be affected.
The CGI program mail, which is not installed by the Debian package,
does a reverse look-up of the user's IP number and copies the
resulting hostname into a fixed-size buffer. A specially crafted DNS
reply could overflow this buffer, opening the program to an exploit.
An XSS vulnerability in w3m 0.3.2 allows remote attackers to insert
arbitrary HTML and web script into frames. Frames are disabled by default
in the version of w3m shipped with Red Hat Linux.
On servers which are configured to allow anonymous read-only access, this
bug could be used by anonymous users to gain write privileges. Users with
CVS write privileges can then use the Update-prog and Checkin-prog features
to execute arbitrary commands on the server.
All users of CVS are advised to upgrade to erratum packages which contain
patches to correct the double-free bug.
See also this CERT advisoryline.
arbitary commands on a vulnerable sytem using the victim's account and
privileges.
See this announcement for more details..
A problem has been found in the Kerberos ftp client. When retrieving a
file with a filename beginning with a pipe character, the ftp client will
pass the filename distribution.
Another vulnerability is due to the way libmcrypt loads algorithms via
libtool. When the algorithms are loaded dynamically the each time the
algorithm is loaded a small (few kilobytes) of memory are leaked. In a
persistant enviroment (web server) this could lead to a memory exhaustion
attack that will exhaust all avaliable memory by launching repeated
requests at an application utilizing the mcrypt library.
CAN-2002-1405
Read the full advisory at.
Since there is no workaround possible except shutting down the LDAP server,
an update is strongly recommended.
CAN-2002-0985
CAN-2002-0986
CAN-2002-1119
Read the full announcment at:s,
etc.) that can then be used for later attacks against the client machine.
See also
this Bugtraq article from 1997.
CAN-2002-1344
Many Linux systems do not run
libgtop by default, but applying the update is a good idea anyway.
CAN-2002-0818
Read the full advisory at
Resources
Page editor: Jonathan Corbet
Kernel development
Linus's (pre-2.5.61) BitKeeper tree includes a big x86-64 update, some
fixups for signal problems in 2.5.60, some kbuild work, and another set of
AGP patches.
Dave Jones has released 2.5.60-dj2, which
adds some driver fixes and a number of 2.4 fixes to the 2.5.60 kernel.
The current stable kernel is 2.4.20; Marcelo has not released any
2.4.21 prepatches since January 29.
The current patch from Alan Cox is 2.4.21-pre4-ac4. It contains another set of
IDE fixes and a few other repairs.
Kernel development news
The technique being looked at is "stochastic fair queueing," and it is
intended to bring greater fairness to I/O scheduling decisions. In a fair
situation, all users of a particular drive would be able to execute about
the same number of I/O requests over a given time. This approach to
fairness gets rid of starvation problems, and ensures that all processes
can get some work done. The hope would be, for example, that a streaming
media application would be able to move its data without outages, even in
the presence of other, disk-intensive applications.
The stochastic fair queueing approach was first developed in the networking
world by Paul E. McKenney; his paper on the subject can be found on this page. In the
networking context, stochastic fair queueing tries to divide the available
bandwidth equally among all users. Ideally, a separate queue would be used
for each ongoing connection, but high-performance routers lack the
resources to do things that way. So a smaller number of queues is used,
with each connection being assigned to a queue via a hash function.
Packets are then taken from each queue in turn, dividing the bandwidth
between them. If two high-bandwidth connections happen to land on the same
queue, they will be penalized relative to the other queues; to address this
problem, the hash function is periodically changed to redistribute
connections among the queues. The algorithm works reasonably well and is
easy to make fast; the Linux networking code has had a stochastic queueing
module available for some time.
In the disk I/O context, the aim is to divide the available disk bandwidth
fairly between processes. The initial
implementation by Jens Axboe creates 64 subqueues for each block I/O
request queue, and distributes requests among the subqueues based on the
process ID of the requestor. (Actually, it uses the process ID of the
currently running process, which could, in some situations, not be the
originator of the request). When the time comes to dispatch requests, one
is taken from each subqueue, and the whole set is ordered before being sent
to the drive for execution.
Taking things even further, Jens has also posted a complete fair queueing scheduler, which does
away with the hash function used in the stochastic approach. Each process
has its own queue, and requests are taken equally from all queues. It is
hard to get fairer than that. Of course, as Jens points out, once you have
this infrastructure in place, it is relatively easy to make things less
fair again by adding, say, I/O priorities to processes.
Where this all appears to be heading (though probably not in the 2.5
series) is toward a configurable I/O scheduler with several possible
algorithms which can be mixed and matched according to a site's local
policy. In other words, it looks a lot like the traffic control code which
has existed in the networking subsystem for a few years. As with
networking, most sites will probably not need to tweak their disk
scheduling regimes. Users with special needs, however, will be glad for
the ability to fine-tune things to their specifications.
These articles will be collected at lwn.net/Articles/driver-porting as the
series continues to develop. With
luck, they will become a useful resource for the kernel development
community. Stay tuned...
Modules with parameters should now include <linux/moduleparam.h>
explicitly. Parameters are then declared with module_param:
module_param(name, type, perm);
If the name of the parameter as seen outside the module differs from the
name of the variable used to hold the parameter's value, a variant on
module param may be used:
module_param_named(name, value, type, perm);
String parameters will normally be declared with the charp type;
the associated variable is a char pointer which will be set to the
parameter's value. If you need to have a string value copied directly into
a char array, declare it as:
module_param_string(name, string, len, perm);
Finally, array parameters (supplied at module load time as a
comma-separated list) may be declared with:
module_param_array(name, type, num, perm);
The one parameter not found in module_param() (num) is
an output parameter; if a value for name is supplied when the
module is loaded, num will be set to the number of values given.
This macro uses the declared length of the array to ensure that it is not
overrun if too many values are provided.
As an example of how the new module parameter code works, here is a
paramaterized version of the "hello world" module shown previously:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
MODULE_LICENSE("Dual BSD/GPL");
/*
* A couple of parameters that can be passed in: how many times we say
* hello, and to whom.
*/
static char *whom = "world";
module_param(whom, charp, 0);
static int howmany = 1;
module_param(howmany, int, 0);
static int hello_init(void)
{
int i;
for (i = 0; i < howmany; i++)
printk(KERN_ALERT "(%d) Hello, %s\n", i, whom);
return 0;
}
static void hello_exit(void)
{
printk(KERN_ALERT "Goodbye, cruel %s\n", whom);
}
module_init(hello_init);
module_exit(hello_exit);
insmod ./hellop.ko howmany=2 whom=universe
MODULE_ALIAS("alias-name");
The only safe way to manipulate the count of references to a module is
outside of the module's code. Otherwise, there will always be times when
the kernel is executing within the module, but the reference count is
zero. So this work has been moved outside of the modules, and life is
generally easier for module authors.
Any code which wishes to call into a module (or use some other module
resource) must first attempt to increment
that module's reference count:
int try_module_get(&module);
A reference to a module can be released with module_put().
Again, modules will not normally have to manage their own reference
counts. The only exception may be if a module provides a reference to an
internal data structure or function that is not accounted for otherwise.
In that (rare) case, a module could conceivably call
try_module_get() on itself.
As of this writing, modules are considered "live" during initialization,
meaning that a try_module_get() will succeed at that time. There
is still talk
of changing things, however, so that modules are not accessible until they
have completed their initialization process. That change will help prevent
a whole set of race conditions that come about when a module fails
initialization, but it also creates difficulties for modules which have to
be available early on. For example, block drivers should be available to read
partition tables off of disks when those disks are registered, which
usually happens when the module is initializing itself. If the policy
changes and modules go back off-limits during initialization, a call to a
function like make_module_live() may be required for those modules
which must be available sooner. (Update 2.6.0-test9: this change
has not happened and seems highly unlikely at this point).
Finally, it is not entirely uncommon for driver authors to put in a special
ioctl() function which sets the module use count to zero.
Sometimes, during module development, errors can leave the module reference
count in a state where it will never reach zero, and there was no other way
to get the kernel to unload the module. The new module code supports
forced unloading of modules which appear to have outstanding references -
if the CONFIG_MODULE_FORCE_UNLOAD option has been set.
Needless to say, this option should only be used on development systems,
and, even then, with great caution.
Chances are that change will cause few problems. When you get a chance,
however, you can remove EXPORT_NO_SYMBOLS lines from your module
source. Exporting no symbols is now the default, so
EXPORT_NO_SYMBOLS is a no-op.
The 2.4 inter_module_ functions have been deprecated as unsafe.
The symbol_get() function exists for the cases when normal symbol
linking does not work well enough. Its use requires setting up weak
references at compile time, and is beyond the scope of this document; there
are no users of symbol_get() in the 2.6.0-test9 kernel
source.
In 2.5, things still work mostly that way. The kernel version is loaded
into a separate, "link-once" ELF section, however, rather than being a
visible variable within the module itself. As a result, multi-file modules
no longer need to define __NO_VERSION__ before including
<linux/module.h>.
The new "version magic" scheme also records other information, including
the compiler version, SMP status, and preempt status; it is thus able to
catch more incompatible situations than the old scheme did.
Module symbol versioning ("modversions") has been completely reworked for
the 2.6 kernel. Module authors who use the makefiles shipped with the kernel
(and that is about the only way to work now) will find that dealing with
modversions has gotten easier than before. The #define hack which
tacked checksums onto kernel symbols has gone away in favor of a scheme
which stores checksum information in a separate ELF section.
The issue of access to the BitKeeper repositories via free software will
not go away, however; there is a determined subset of the kernel hacker
community that simply does not want to use proprietary code. Fortunately,
there appears to be an answer on the horizon: BitMover has promised to make Linus's repository available
as an automatically updated CVS repository. That repository, presumably,
will be hosted at kernel.org. At that point, a lot of minds should be
eased about access to the repository - and about long-term preservation of
the
kernel's revision history in an open format (not that the BitKeeper format,
which is based on SCCS, is particularly closed).
Incidentally, it has been just over one year since Linus let the world
know he was trying out BitKeeper in the 2.5.4-pre1 announcement.
Patches and updates
Kernel trees
Core kernel code
Development tools
Device drivers
Documentation
Filesystems and block I/O
Janitorial
Memory management
Architecture-specific
Benchmarks and bugs
Miscellaneous
Distributions
Distribution News
Stephen Frost discussed problems in OpenSSL
0.9.6/0.9.7, LDAP, SSH. "There are quite a few bugs that are
probably because of the problem I'm about to describe (177868, 178061,
173821, probably others..) so it was felt that this might be something to
make other developers aware of."
Full Story (comments: none)
New Distributions
Minor distribution updates
Distribution reviews
Page editor: Rebecca Sobol
Development
"The alpha release is mostly feature-complete, but lots of tuning will still be needed for installation and user interfaces. Midgard experience is required for installing and using the package."
TownPortal provides a dynamic content-driven site structure that is
managed with the Aegir CMS
content management system, it works under the
Midgard
open source application server.
TownPortal is organized as a Linux, Apache, MySQL and PHP (LAMP) system.
The system currently has the following features:
TownPortal is licensed under the GPL, it may be downloaded
here. The
screenshots
page shows the system in action. If your town or group needs a new web
site, TownPortal looks like a nicely organized system.
System Applications
Audio Projects
Database Software
Education
Electronics
Mail Software
Printing
Web Site Development
Desktop Applications
Audio Applications
Desktop Environments
Graphics
GUI Packages
Interoperability
Office Applications
Web Browsers
Languages and Tools
Caml
HTML
Java
Lisp
Perl
PHP
Python
Ruby
New Ruby software includes:
ZenWeb 2.15.0 Released, sys-uname 0.4.0, Text::Format 0.61,
Digest::CRC32 0.1.0, bdb, FXRuby-1.0.19 Now Available, plruby,
math-const 1.0.0, Ruby-GNOME2-0.3.0, MIME::Types 1.005, and
ruby syntax file for GNU Source-highlight.
Scheme
Tcl/Tk
XML
Page editor: Forrest Cook
Linux in the news
Recommended Reading
Companies
Linux Adoption
Interviews.
Reviews
Announcements
Non-Commercial announcements
Full Story (comments: 9)
Commercial announcements
Full Story (comments: 3)
Upcoming Events
Web sites
Software announcements
Letters to the editor
In "Cross-site tracing attacks" it says:
The whitepaper is more tempered, but it implies that the TRACE
method has a defect which compromises every web server.
This is misleading. Having read the white paper I cannot see where it
implies or states that.
The information is being leaked from the client. The client wrongly
sends the sensitive information to the server, which is then echoed
back, and this reply containing the sensitive information is wrongly
made available to the untrusted code.
The problem clearly lies with a bug in the ActiveX, etc. objects, not
the server, as the white paper states. It does recommend that TRACE be
disabled to make it impossible for the vulnerability to affect
vulnerable clients, but the problem will not lead to the compromise of
any web server unless it is possible to do that by reading someone's
cookie. Which is very, very doubtful.
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/22025/bigpage | crawl-003 | refinedweb | 4,324 | 62.27 |
17.1.
threading — Thread-based parallelism¶
Code source::
threading.
active_count()¶
Return the number of
Threadobjects currently alive. The returned count is equal to the length of the list returned by
enumerate().
threading.
current_thread()¶
Return the current
Threadobject, corresponding to the caller’s thread of control. If the caller’s thread of control was not created through the
threadingmodule, a dummy thread object with limited functionality is returned.
threading.
get_ident()¶
Return the “thread.
Nouveau dans la version 3.3.
threading.
enumerate()¶
Return a list of all
Threadobjects currently alive. The list includes daemonic threads, dummy thread objects created by
current_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started.
threading.
main_thread()¶
Return the main
Threadobject. In normal conditions, the main thread is the thread from which the Python interpreter was started.
Nouveau dans la version 3.4.
threading.
settrace(func)¶
Set a trace function for all threads started from the
threadingmodule. The func will be passed to
sys.settrace()for each thread, before its
run()method is called.
threading.
setprofile(func)¶
Set a profile function for all threads started from the
threadingmodule. The func will be passed to
sys.setprofile()for each thread, before its
run()method is called..
This module also defines the following constant:
threading.
TIMEOUT_MAX¶
The maximum value allowed for the timeout parameter of blocking functions (
Lock.acquire(),
RLock.acquire(),
Condition.wait(), etc.). Specifying a timeout greater than this value will raise an
OverflowError.
Nouveau dans la version 3.2.
This module defines a number of classes, which are detailed in the sections.
17.1.1. Thread-Local Data¶
Thread-local data is data whose values are thread specific. To manage
thread-local data, just create an instance of
local (or a
subclass) and store attributes on it:
mydata = threading.local() mydata.x = 1
The instance’s values will be different for separate threads.
17.1.2. Thread Objects¶
The
Thread or the daemon constructor
argument.={}, *, daemon=None not
None, daemon explicitly sets whether the thread is daemonic. If
None(the default), the daemonic property is inherited from the current thread.
If the subclass overrides the constructor, it must make sure to invoke the base class constructor (
Thread.__init__()) before doing anything else to the thread.
Modifié dans la version 3.3: Added the daemon argument._alive( raise the same exception.
name¶
A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.
ident¶
The “thread identifier” of this thread or
Noneif the threadjust before the
run()method starts until just after the
run()method terminates. The module function
enumerate()returns a list of all alive threads..
Particularité de l’implémentation CPython :.
17.1.3..
Locks also support the context management protocol..
- class
threading.
Lock¶
The class implementing primitive lock objects. Once a thread has acquired a lock, subsequent attempts to acquire it block, until it is released; any thread may release it.
Note that
Lockis actually a factory function which returns an instance of the most efficient version of the concrete Lock class that is supported by the platform.
acquire(blocking=True, timeout=-1.
When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. A timeout argument of
-1specifies an unbounded wait. It is forbidden to specify a timeout when blocking is false.
The return value is
Trueif the lock is acquired successfully,
Falseif not (for example if the timeout expired).
Modifié dans la version 3.2: Le paramètre timeout est nouveau.
Modifié dans la version 3.2: Lock acquires can now be interrupted by signals on POSIX.
release()¶is raised.
Il n’y a pas de valeur de retour.
17.1.
Reentrant locks also support the context management protocol.
- class
threading.
RLock¶is actually a factory function which returns an instance of the most efficient version of the concrete RLock class that is supported by the platform.
acquire(blocking=True, timeout= invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return true if the lock has been acquired, false if the timeout has elapsed.
Modifié dans la version 3.2: Le paramètre timeout est nouveau..
Il n’y a pas de valeur de retour.
17.1.5. Condition Objects¶
A condition variable is always associated with some kind of lock; this can be passed in or one will be created by default. Passing one in is useful when several condition variables must share the same lock. The lock is part of the condition object: you don’t have to track it separately.
A condition variable obeys the context management.
- class
threading.
Condition(lock=None)¶
This class implements condition variable objects. A condition variable allows one or more threads to wait until they are notified by another thread.
If the lock argument is given and not
None, it must be a
Lockor
RLockobject, and it is used as the underlying lock. Otherwise, a new
RLockobject is created and used as the underlying lock.
Modifié dans la version 3.3: changed from a factory function to a class.
acquire(*args)¶
Acquire the underlying lock. This method calls the corresponding method on the underlying lock; the return value is whatever that method returns.
release()¶
Release the underlying lock. This method calls the corresponding method on the underlying lock; there is no return value.
wait(timeout=None)¶
Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a
RuntimeErroris raised.
This method releases the underlying lock, and then blocks until it is awakened by a
notify()or
notify.
The return value is
Trueunless a given timeout expired, in which case it is
False.
Modifié dans la version 3.2: Previously, the method always returned
None.
wait_for(predicate, timeout=None)¶if the method timed out.
Ignoring the timeout feature, calling this method is roughly equivalent to writing:
while not predicate(): cv.wait()
Therefore, the same rules apply as with
wait(): The lock must be held when called and is re-acquired on return. The predicate is evaluated with the lock held.
Nouveau dans la version 3.2.
Wake up all threads waiting on this condition. This method acts like
notify(), but wakes up all waiting threads instead of one. If the calling thread has not acquired the lock when this method is called, a
RuntimeErroris raised.
17.1.6. Semaphore Objects¶
This is one of the oldest synchronization primitives in the history of computer
science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
used the names().
Semaphores also support the context management protocol.
- class
threading.
Semaphore(value=1)¶is raised.
Modifié dans la version 3.3: changed from a factory function to a class.
acquire(blocking=True, timeout=None..
Modifié dans la version 3.2: Le paramètre timeout est nouveau.
- class
threading.
BoundedSemaphore(value=1)¶
Class implementing bounded semaphore objects..
Modifié dans la version 3.3: changed from a factory function to a class.
17.1:
with pool_sema: conn = connectdb() try: # ... use connection ... finally: conn.close()
The use of a bounded semaphore reduces the chance that a programming error which causes the semaphore to be released more than it’s acquired will go undetected.
17.1
Class implementing event objects. An event manages a flag that can be set to true with the
set()method and reset to false with the
clear()method. The
wait()method blocks until the flag is true. The flag is initially false.
Modifié dans la version 3.3: changed from a factory function to a class.=None true if and only if the internal flag has been set to true, either before the wait call or after the wait starts, so it will always return
Trueexcept if a timeout is given and the operation times out.
Modifié dans la version 3.1: Previously, the method always returned
None.
17.1.8..
Par exemple :
def hello(): print("hello, world") t = Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printed
- class
threading.
Timer(interval, function, args=None, kwargs=None)¶
Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is
None(the default) then an empty list will be used. If kwargs is
None(the default) then an empty dict will be used.
Modifié dans la version 3.3: changed from a factory function to a class.
17.1.9. Barrier Objects¶
Nouveau dans la version 3.2.
This class provides a simple synchronization primitive for use by a fixed number
of threads that need to wait for each other. Each of the threads tries to pass
the barrier by calling the
wait() method and will block until
all of the threads have made their
wait() calls. At this point,
the threads are released simultaneously.)
- class
threading.
Barrier(parties, action=None, timeout=None)¶
Create a barrier object for parties number of threads. An action, when provided, is a callable to be called by one of the threads when they are released. timeout is the default timeout value if none is specified for the
wait()method.
wait(timeout=None)¶rorexception if the barrier is broken or reset while a thread is waiting.
reset()¶
Return the barrier to the default, empty state. Any threads waiting on it will receive the
BrokenBarrierErrorexception.
Note that using this function may can require some external synchronization if there are other threads whose state is unknown. If a barrier is broken it may be better to just leave it and create a new one.
abort()¶.
- exception
threading.
BrokenBarrierError¶
This exception, a subclass of
RuntimeError, is raised when the
Barrierobject is reset or broken.
17.1. Hence,
the following snippet:
with some_lock: # do something...
is equivalent to:
some_lock.acquire() try: # do something... finally: some_lock.release()
Currently,
Lock,
RLock,
Condition,
Semaphore, and
BoundedSemaphore objects may be used as
with statement context managers. | https://docs.python.org/fr/3/library/threading.html | CC-MAIN-2017-47 | refinedweb | 1,695 | 59.7 |
Walkthrough: Writing a Visualizer in C#
This walkthrough shows how to write a simple visualizer by using C#. The visualizer you will create in this walkthrough displays the contents of a string using a Windows forms message box. This simple string visualizer is not especially useful in itself, but it shows the basic steps that you must follow to create more useful visualizers for other data types.
Note
The dialog boxes and menu commands you see might differ from those described in Help, depending on your active settings or edition. To change your settings, go to the Tools menu and choose Import and Export Settings. For more information, see Reset settings.
Visualizer code must be placed in a DLL, which will be read by the debugger. Therefore, the first step is to create a Class Library project for the DLL.
Create a visualizer manually
Follow the tasks below to create a visualizer.
To create a class library project
Create a new class library project.
Press Esc to close the start window. Type Ctrl + Q to open the search box, type class library, choose Templates, then choose Create a new Class Library (.NET Standard). In the dialog box that appears, choose Create.
From the top menu bar, choose File > New > Project. In the left pane of the New project dialog box, under Visual C#, choose .NET Standard, and then in the middle pane choose Class Library (.NET Standard).
Type an appropriate name for the class library, such as
MyFirstVisualizer, and then click Create or OK.
After you have created the class library, you must add a reference to Microsoft.VisualStudio.DebuggerVisualizers.DLL so that you can use the classes defined there. Before you add the reference, however, you must rename some classes so that they have meaningful names.
To rename Class1.cs and add Microsoft.VisualStudio.DebuggerVisualizers
In Solution Explorer, right-click Class1.cs and choose Rename on the shortcut menu.
Change the name from Class1.cs to something meaningful, such as DebuggerSide.cs.
Note
Visual Studio automatically changes the class declaration in DebuggerSide.cs to match the new file name.
In Solution Explorer, right-click References and choose Add Reference on the shortcut menu.
In the Add Reference dialog box, on the Browse tab, select Browse and find the Microsoft.VisualStudio.DebuggerVisualizers.DLL.
You can find the DLL in <Visual Studio Install Directory>\Common7\IDE\PublicAssemblies subdirectory of Visual Studio's installation directory.
Click OK.
In DebuggerSide.cs, add the following to the
usingdirectives:
using Microsoft.VisualStudio.DebuggerVisualizers;
Now you are ready to create the debugger-side code. This is the code that runs within the debugger to display the information that you want to visualize. First, you have to change the declaration of the
DebuggerSideobject so that inherits from the base class
DialogDebuggerVisualizer.
To inherit from DialogDebuggerVisualizer
In DebuggerSide.cs, go to the following line of code:
public class DebuggerSide
Change the code to:
public class DebuggerSide : DialogDebuggerVisualizer
DialogDebuggerVisualizerhas one abstract method (
Show) that you must override.
To override the DialogDebuggerVisualizer.Show method
In
public class DebuggerSide, add the following method:
protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider) { }
The
Showmethod contains the code that actually creates the visualizer dialog box or other user interface and displays the information that has been passed to the visualizer from the debugger. You must add the code that creates the dialog box and displays the information. In this walkthrough, you will do this using a Windows forms message box. First, you must add a reference and
usingdirective for System.Windows.Forms.
To add System.Windows.Forms
In Solution Explorer, right-click References and choose Add Reference on the shortcut menu.
In the Add Reference dialog box, on the Browse tab, select Browse, and find the System.Windows.Forms.DLL.
You can find the DLL in C:\Windows\Microsoft.NET\Framework\v4.0.30319.
Click OK.
In DebuggerSide.cs, add the following to the
usingdirectives:
using System.Windows.Forms;
Now, you will add some code to create and show the user interface for your visualizer. Because this is your first visualizer, we will keep the user interface simple and use a Message Box.
To show the Visualizer Output in a dialog box
In the
Showmethod, add the following line of code:
MessageBox.Show(objectProvider.GetObject().ToString());
This example code does not include error handling. You should include error handling in a real visualizer or any other kind of application.
On the Build menu, choose Build MyFirstVisualizer. The project should build successfully. Correct any build errors before continuing.
That is the end of the debugger side code. There is one more step, however; the attribute that tells the debuggee side which collection of classes comprises the visualizer.
To add the debuggee-side code
Add the following attribute code to DebuggerSide.cs, after the
usingdirectives but before
namespace MyFirstVisualizer:
[assembly:System.Diagnostics.DebuggerVisualizer( typeof(MyFirstVisualizer.DebuggerSide), typeof(VisualizerObjectSource), Target = typeof(System.String), Description = "My First Visualizer")]
On the Build menu, choose Build MyFirstVisualizer. The project should build successfully. Correct any build errors before continuing.
At this point, your first visualizer is finished. If you have followed the steps correctly, you can build the visualizer and install it into Visual Studio. Before you install a visualizer into Visual Studio, however, you should test it to make sure that it runs correctly. You will now create a test harness to run the visualizer without installing it into Visual Studio.
To add a Test Method to show the visualizer
Add the following method to class
public DebuggerSide:
public static void TestShowVisualizer(object objectToVisualize) { VisualizerDevelopmentHost visualizerHost = new VisualizerDevelopmentHost(objectToVisualize, typeof(DebuggerSide)); visualizerHost.ShowVisualizer(); }
On the Build menu, choose Build MyFirstVisualizer. The project should build successfully. Correct any build errors before continuing.
Next, you must create an executable project to call your visualizer DLL. For simplicity, we will use a Console Application project.
To add a console application project to the solution
In Solution Explorer, right-click the solution, choose Add, and then click New Project.
In the Search box, type console app, choose Templates, then choose Create a new Console App (.NET Framework). In the dialog box that appears, choose Create.
From the top menu bar, choose File > New > Project. In the left pane of the New project dialog box, under Visual C#, choose Windows Desktop, and then in the middle pane choose Console App (.NET Framework).
Type an appropriate name for the class library, such as
MyTestConsole, and then click Create or OK.
Now, you must add the necessary references so MyTestConsole can call MyFirstVisualizer.
To add necessary references to MyTestConsole
In Solution Explorer, right-click MyTestConsole and choose Add Reference on the shortcut menu.
In the Add Reference dialog box, Browse tab, choose Microsoft.VisualStudio.DebuggerVisualizers.DLL.
Click OK.
Right-click MyTestConsole and choose Add Reference again.
In the Add Reference dialog box, click the Projects tab and then click MyFirstVisualizer.
Click OK.
Now, you will add the code to finish the test harness.
To add code to MyTestConsole
In Solution Explorer, right-click Program.cs and choose Rename on the shortcut menu.
Edit the name from Program.cs to something more meaningful, such as TestConsole.cs.
Note
Visual Studio automatically changes the class declaration in TestConsole.cs to match the new file name.
In TestConsole.cs, add the following code to the
usingdirectives:
using MyFirstVisualizer;
In method
Main, add the following code:
String myString = "Hello, World"; DebuggerSide.TestShowVisualizer(myString);
Now, you are ready to test your first visualizer.
To test the visualizer
In Solution Explorer, right-click MyTestConsole and choose Set as Startup Project on the shortcut menu.
On the Debug menu, choose Start.
The console application starts and the Visualizer appears and displays the string, "Hello, World."
Congratulations. You have just built and tested your first visualizer.
If you want to use your visualizer in Visual Studio rather than just calling it from the test harness, you have to install it. For more information, see How to: Install a Visualizer.
Create a visualizer using the Visualizer item template
So far, this walkthrough has shown you how to create a visualizer manually. This was done as a learning exercise. Now that you know how a simple visualizer works, there is an easier way to create one: using the visualizer item template.
First, you have to create a new class library project.
To create a new class library
On the File menu, choose New > Project.
In the New Project dialog box, under Visual C#, select .NET Standard.
In the middle pane, choose Class Library.
In the Name box, type an appropriate name for the class library, such as MySecondVisualizer.
Click OK.
Now, you can add a visualizer item to it:
To add a visualizer item
In Solution Explorer, right-click MySecondVisualizer.
On the shortcut menu, choose Add and then click New Item.
In the Add New Item dialog box, under Visual C# Items, select Debugger Visualizer.
In the Name box, type an appropriate name, such as SecondVisualizer.cs.
Click Add.
That is all there is to it. Look at the file SecondVisualizer.cs and view the code that the template added for you. Go ahead and experiment with the code. Now that you know the basics, you are on your way to creating more complex and useful visualizers of your own.
See also
Feedback | https://docs.microsoft.com/en-us/visualstudio/debugger/walkthrough-writing-a-visualizer-in-csharp?view=vs-2019 | CC-MAIN-2020-05 | refinedweb | 1,547 | 50.33 |
Write code using synchronized wait notify and notifyAll to protect against concurrent access problems and to communicate between threads. Define the interaction between threads and between threads and object locks when executing synchronized wait notify or notifyAll.
One way to think of the wait/notify protocol is to
imagine an item of data such as an integer variable as if it were a
field in a database. If you do not have some locking mechanism in
the database you stand a chance of corruption to the data.
Thus one user might retrieve the data and perform a calculation and write back the data. If in the meantime someone else has retrieved the data, performed the calculation and written it back, the second users calculations will be lost when the first person writes back to the database. In the way that a database has to handle updates at unpredictable times, so a multi threaded program has to cater for this possibility. You really need to know this topic for the exam. It is easy to be a generally proficient Java programmer and still not completely understand the wait/notify protocol. I strongly recommend you write plenty of sample code and find all the mock exam questions you possibly can on this topic.
The following code is an attempt to illustrate how important it is to synchronize threads that might access the same data. It consists of a class called bank, that acts as a driver to create multiple threads of running the methods of a class called Business. The Business threads act to add and subtract money from the accounts. The idea of the code is to illustrate how multiple threads can "tread on each others toes" and lead to data corruption, even though there is code that attempts to avoid this corruption. In order to "fix" and ensure this corruption I have put in a call to a sleep method, which you can consider to be the equivalent to the pause that would take place when real banking code wrote to a database. The corruption that this illustrates would still occasionally happen without this call to sleep but you might have to run the code quite a few times and for quite a long time before it manifested itself.
public class Account{ private int iBalance; public void add(int i){ iBalance = iBalance + i; System.out.println("adding " +i +" Balance = "+ iBalance); } public void withdraw(int i){ if((iBalance - i) >0 ){ try{ Thread.sleep(60); }catch(InterruptedException ie){} iBalance = iBalance - i; }else{ System.out.println("Cannot withdraw, funds would be < 0"); } if(iBalance < 0){ System.out.println("Woops, funds below 0"); System.exit(0); } System.out.println("withdrawing " + i+ " Balance = " +iBalance); } public int getBalance(){ return iBalance; } }
The synchronized keyword can be used to mark a statement or block of code so that only one thread may execute an instance of the code at a time. Entry to the code is protected by a monitor lock around it. This process is implemented by a system of locks. You may also see the words monitor, or mutex (mutually exclusive lock) used. A lock is assigned to the object and ensures only one thread at a time can access the code. Thus when a thread starts to execute a synchronized block it grabs the lock on it. Any other thread will not be able to execute the code until the first thread has finished and released the lock. Note that the lock is based on the object and not on the method.
For a method the synchronized keyword is placed before the method thus
synchronized void amethod() { /* method body */}
For a block of code the synchronized keyword comes before opening and closing brackets thus.
synchronized (ObjectReference) { /* Block body */ }
The value in parentheses indicates the object or class whose
monitor the code needs to obtain. It is generally more common to
synchronize the whole method rather than a block of code.
When a synchronized block is executed, its object is locked and it cannot be called by any other code until the lock is freed.
synchronized void first(); synchronized void second();
There is more to obtaining the benefits of synchronization than placing the keyword synchronized before a block of code. It must be used in conjunction with code that manages the lock on the synchronized code .
In addition to having a lock that can be grabbed and released, each object has a system that allows it to pause or wait whilst another thread takes over the lock. This allows Threads to communicate the condition of readiness to execute. Because of the single inheritance nature of Java, every object is a child of the great grand ancestor Object class from which it gets this Thread communication capability.
A call to wait from within synchronized code causes the thread to give up its lock and go to sleep. This normally happens to allow another thread to obtain the lock and continue some processing. The wait method is meaningless without the use of notify or notifyAll which allows code that is waiting to be notified that it can wake up and continue executing. A typical example of using the wait/notify protocol to allow communication between Threads appears to involve apparently endless loops such as
//producing code while(true){ try{ wait(); }catch (InterruptedException e) {} } //some producing action goes here notifyAll();
As true is notorious for staying true this, code looks at first glance like it will just loop forever. The wait method however effectively means give up the lock on the object and wait until the notify or notifyAll method tells you to wake up.
Unlike most aspects of Java, Threading does not act the same on different platforms. Two areas of difference are Thread scheduling and Thread priorities. The two approaches to scheduling are
Preemptive
Time slicing
In a pre-emptive system one program can "pre-empt" another to get its share of CPU time. In a time sliced system each thread gets a "slice" of the CPU time and then gets moved to the ready state. This ensures against a single thread getting all of the CPU time. The downside is that you cannot be certain how long a Thread might execute or even when it will be running. Although Java defines priorities for threads from the lowest at 1 to the highest at 10, some platforms will accurately recognise these priorities whereas others will not..
Which of the following keywords indicates a thread is releasing
its Object lock?
1) release
2) wait
3) continue
4) notifyAll
Which best describes the synchronized keyword?
1) Allows more than one Thread to access a method simultaneously
2) Allows more than one Thread to obtain the Object lock on a reference
3) Gives the notify/notifyAll keywords exclusive access to the monitor
4) Means only one thread at a time can access a method or block of code
What will happen when you attempt to compile and run the following code?
public class WaNot{ int i=0; public static void main(String argv[]){ WaNot w = new WaNot(); w.amethod(); } public void amethod(){ while(true){ try{ wait(); }catch (InterruptedException e) {} i++; }//End of while }//End of amethod }//End of class 1)Compile time error, no matching notify within the method 2)Compile and run but an infinite looping of the while method 3)Compilation and run 4)Runtime Exception "IllegalMonitorStatException"
How can you specify which thread is notified with the wait/notify protocol?
1) Pass the object reference as a parameter to the notify
method
2) Pass the method name as a parameter to the notify method
3) Use the notifyAll method and pass the object reference as a parameter
4) None of the above
Which of the following are true
1) Java uses a time-slicing scheduling system for determining
which Thread will execute
2) Java uses a pre-emptive, co-operative system for determining which Thread will execute
3) Java scheduling is platform dependent and may vary from one implementation to another
4) You can set the priority of a Thread in code
1) Wait
4) Means only one thread at a time can access a method or block of code
4) Runtime Exception "IllegalMonitorStateException"
The wait/notify protocol can only be used within code that is synchronized. In this case calling code does not have a lock on the object and will thus cause an Exception at runtime.
4) None of the above.
The wait/notify protocol does not offer a method of specifying which thread will be notified.
3) Java scheduling is platform dependent and may vary from one
implementation to another
4) You can set the priority of a Thread in code
This topic is covered in the Sun Tutorial at
Jyothi Krishnan on this topic at
Bruce Eckel Thinking in Java | http://www.jchq.net/certkey/0703certkey.htm | CC-MAIN-2015-18 | refinedweb | 1,466 | 55.88 |
Documentation in FastAI, nbdev.16 Oct 2020
You’re going to find some utterly newbie / neophyte - python / FastAI stuff in the TIL section (I don’t know, maybe I need more slashes?!) in the coming weeks and months, to which I say, “I don’t care.” If I can’t figure it out without asking, then someone else is in the same situation.
So I had heard a lot about
nbdev, and I knew that it linked up somehow with making documentation searchable. But I didn’t know how I could access the source code from a Jupyter notebook, with some code that had been indexed (right term? don’t know) with
nbdev. So to the forums!
Answer is here, first you need to have
nbdev installed, which I did, import,
from nbdev.showdoc import *
then use
doc(myfunc). A box with the function’s documentation will appear.
This is super cool, from there you can go to the source and take a look at the function.
© Amy Tabb 2018-2020. All rights reserved. The contents of this site reflect my personal perspectives and not those of any other entity. | https://amytabb.com/til/2020/10/16/using-nbdev/ | CC-MAIN-2020-45 | refinedweb | 190 | 84.78 |
The basics
The Python official interpreter ships a unittest module, that you can use in substitution of xUnit tools from other languages. Tests built for unittest are classes extending unittest.TestCase.
By convention, methods starting with *test_* are recognized as test to be run, while setUp() and tearDown() are reserved names for routines to execute once for each test, respectively at the start and at the end of it as you would expect.
Each of these methods take only self as a parameter, which means they will be actually called with no arguments. You can share references between setUp, tearDown and test_* methods via self, which is the Python equivalent of this.
However, you're not obliged to define fields in the class's body, as you can assign new ones to self at any time. This example from the manual also contains a __main__ function to run a test file by itself, which is not really necessary if you use python -m unittest.()
Assertions
Apart from the basic methods structure, unittest also features assertion methods inherited from TestCase as the main way to check the behavior of code.
- assertEqual(expected, actual) is the equivalent of assertEquals() and lets you specify an expected value along with an actual one obtained. Python's equality for objects is based on the __eq__ method.
- assertNotEqual(notExpected, actual) is the opposite of the previous assertion.
- assertTrue(expression) and assertFalse(expression) allows you to create custom assertions; expression is a boolean value obtained with <, >, other comparison operators or methods, or the combination of other booleans with and, or, and not.
- assertIsInstance(object, class) checks object is the instance of class or of a subclass.
The generation of Test Doubles such as Stubs and Mocks is not supported by default, but there are many libraries you can integrate for behavior-based testing.
Running
The files containing test cases should start with the test* prefix (like test_tennis.py), so that they can be found automatically:
python -m unittest discover
In unittest conventions, it is not necessary to map a test case class to a single: maybe it is more natural to map the tests for a module to a single file, as modules can contain many decoupled functions instead of classes. What you test in a file/test case class/method depends only on what you import and instantiate, not on restriction from the framework.
Thus file filtering can be applied to run only a file (tests for a module), only a class, or only a test method:
python -m unittest test_random python -m unittest test_random.TestSequenceFunctions python -m unittest test_random.TestSequenceFunctions.test_shuffle
A kata
To try all these tools on the field, I executed the tennis kata. It consists of implementing the scoring rules of a tennis set:
- Each player can have either of these points in one game, described as 0-15-30-40. Each time a player scores, it advances of one position in the scale.
- A player at 40 who scores wins the set. Unless...
- If both players are at 40, we are in a *deuce*. If the game is in deuce, the next scoring player will gain an *advantage*. Then if the player in advantage scores he wins, while if the player not in advantage scores they are back at deuce.
The final result (of the test) is:
from tennis import Set, Scores from unittest import TestCase class TestSetWinning(TestCase): def test_score_grows(self): set = Set() self.assertEqual("0", set.firstScore()) set.firstScores() self.assertEqual("15", set.firstScore()) self.assertEqual("0", set.secondScore()) set.secondScores() self.assertEqual("15", set.secondScore()) def test_player_1_win_when_scores_at_40(self): set = Set() set.firstScores(3) self.assertEqual(None, set.winner()) set.firstScores() self.assertEqual(1, set.winner()) def test_player_2_win_when_scores_at_40(self): set = Set() set.secondScores(3) self.assertEqual(None, set.winner()) set.secondScores() self.assertEqual(2, set.winner()) def test_deuce_requires_1_more_than_one_ball_to_win(self): set = Set() set.firstScores(3) set.secondScores(3) set.firstScores() self.assertEqual(None, set.winner()) set.firstScores() self.assertEqual(1, set.winner()) def test_deuce_requires_2_more_than_one_ball_to_win(self): set = Set() set.firstScores(3) set.secondScores(3) set.secondScores() self.assertEqual(None, set.winner()) set.secondScores() self.assertEqual(2, set.winner()) def test_player_can_return_to_deuce_by_scoring_against_the_others_advantage(self): set = Set() set.firstScores(3) set.secondScores(3) self.assertEqual(None, set.winner()) set.firstScores() set.secondScores() set.firstScores() set.secondScores() self.assertEqual(None, set.winner()) self.assertEqual("40", set.firstScore()) self.assertEqual("40", set.secondScore()) class TestScoreNames(TestCase): def test_score_names(self): scores = Scores() self.assertEqual("0", scores.scoreName(0)) self.assertEqual("15", scores.scoreName(1)) self.assertEqual("30", scores.scoreName(2)) self.assertEqual("40", scores.scoreName(3)) self.assertEqual("A", scores.scoreName(4))
Conclusion
You can check out the code (mostly procedural, it's the first time I try this kata) on Github. It's really easy after these examples to pick up TDD in Python at the unit level, while developing single classes or modules. The natural evolution will lead us to try to define end-to-end tests for whole applications.
Vinil Mehta replied on Sun, 2012/03/25 - 12:13pm
Harry Percival replied on Fri, 2014/10/03 - 11:55pm
@Vinil Mehta, I've written a whole book about TDD, using a Django web app as the main example: (it's available free under CC license, and it's published by O'Reilly if you want a physical copy). cheers! | http://css.dzone.com/articles/tdd-python-5-minutes | CC-MAIN-2014-42 | refinedweb | 884 | 50.97 |
Ok very simple task yet difficult for me as a novice to solve.
I have a bat file in a folder in my c: drive. This bat file call an EXE file inside the same folder. The BAT file also feeds some other files to teh EXE to run properly. The bat file works fine if I run it through command prompt.
I tried this code from eclipse but nothing happens i.e. Bat is not executed at all - where is the mistake?
import java.io.*; import java.util.*; public class utilities { public static void main(String[] args) throws InterruptedException { //cmd = cmd+" "+a+" "+b; try { String[] cmd = new String[]{"cmd.exe" ,"/c","C:\\EnergyPlusV6-0-0\\RunEplus.bat", "test5", "my"}; //cmd = new String[]{"cmd" ,"/c","C:\\EnergyPlusV6-0-0\\Epl-run.bat"}; Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); System.out.println(p.exitValue()); } catch (IOException e) { e.printStackTrace(); } } | http://www.javaprogrammingforums.com/file-i-o-other-i-o-streams/10257-execute-bat-file-arguments.html | CC-MAIN-2014-23 | refinedweb | 150 | 68.77 |
Feature #16296open
Alternative behavior for `...` in method body if `...` is not in method definition
Description
In #16253 we settled on a syntax where the remainder arguments captured via
... in the method definition can be forwarded via
... in the method body. I think that was the correct decision.
But I can't forget about the use case presented by zverok (and in #15049) where the method definition is used to specify mandatory and default parameters and then forward all of them to another method. I've also experienced that same use case in my code. Using the current syntax we would need to do this:
def get(path:, accept: :json, headers: {}, ...) _request(method: :get, path: path, accept: accept, headers: headers, ...) end def post(path:, body:, accept: :json, headers: {}, ...) _request(method: :post, path: path, body: body, accept: accept, headers: headers, ...) end
Which feels pointlessly repetitive to me. So I was thinking that maybe if
... is not present in the method definition, then in the method body
... could take on the meaning of "all arguments of the method". Then the code would look like this:
def get(path:, accept: :json, headers: {}, **opts) _request(method: :get, ...) end def post(path:, body:, accept: :json, headers: {}, **opts) _request(method: :post, ...) end
In those examples (no positional parameters) it would also allow
Hash[...] or
{}.replace(...) to get the hash of all keyword arguments.
Pro: it allows a new useful and powerful behavior
Con: some may consider it 'unclean' to change the behavior of
... based on the method definition
Related issues
Updated | https://bugs.ruby-lang.org/issues/16296 | CC-MAIN-2021-21 | refinedweb | 254 | 68.67 |
sc_detach()
Close any open smart card session.
Synopsis:
#include <smartcard/sc_smart_card.h>
sc_response_code_t sc_detach(sc_context_t *context, sc_card_disposition_t card_disposition)
Since:
BlackBerry 10.2.0
Arguments:
- context
The active smart card context. This value cannot be NULL.
- card_disposition
The disposition action to be performed upon termination.
Library:libscs (For the qcc command, use the -l scs option to link against this library)
Description:
If no connection is currently opened, then an error is returned.
Upon termination, the action indicated by card_disposition is performed, if possible. The allowed actions include:
- leaving the card
- resetting the card
- powering down the card
- ejecting the card
Any application may reset the card, even in shared access mode. You can turn off the power to a smart card or eject a smart card only if the app has exclusive access to the card.
Returns:
SC_SCARD_S_SUCCESS upon success, an error code otherwise. See sc_response_code_t for defined error codes.
Last modified: 2014-09-30
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.smartcard.lib_ref/topic/sc_detach.html | CC-MAIN-2017-39 | refinedweb | 171 | 52.05 |
I have an html file and I want to add some lines to specific part of that file using java. would you please guide me to the solution
Printable View
I have an html file and I want to add some lines to specific part of that file using java. would you please guide me to the solution
Hello nasi,
Does the specific part of the file always stay the same?
Please post an example of the HTML file and show me where you would like to insert the code.
no, it is not the same always.
Well you will need to identify where abouts in the HTML you wish to insert the extra code.
How else will the program know where to look?
If you want to add the code at the start or the end of the file, that won't be a problem.
Please explain where abouts you would be inserting the extra code....
actually it is not a predefined position, and it varies for different html files, the only thing that I can say is that it is inside the codes of my html file. if I can't embed my codes inside the html file, it would be good to add them to the end of the file but I don't know how to do it as well.
have you looked into using java script/jsp? these can easily and fairly quickly provide dynamic content to a webpage (PHP and ASP are some other good choices, too)
when I do that it overwrites my file and replaces the original html code with new one. I will try to send u what I am doing,I have to simplify it. it is now multiple classes
Yes please attach your code. You can stop the over write by doing this:
Code :
import java.io.*; public class WriteFile { public static void main(String[] args) throws IOException { Writer output = null; File file = new File("myFile.txt"); output = new BufferedWriter(new FileWriter(file, [B]true[/B])); output.write("Whatever string you want here"); output.close(); System.out.println("File written"); } }
Without the true, it overwrites the file each time.
You should be reading in the original file and saving it out as something new. Then you could add code to delete the original file and rename the new one.
Now if I want to add text inside the body of my html file, how should I do that? I want to select a word or phrase in the file, and add some links to it. Actually I want to make a hypertext file from my html file. so I need add some thing like this any where a selected text exists.
Code :
The <a href="">Students</a> should learn</p>
here Students is the selected text.
I think you have chosen a wrong place to publish your great Ideas. if you don't know I 'll tell you that here is for Java programming discussions, not dating.
please be kind to me as before and answer my questions dear java specialist.
If you want to insert text, the easiest way is to actually over-write the whole file.
First, identify where it is you want to insert the html code. Then, write out everything you read from the file up to that point. Then, write out the stuff you want to insert. Finally, write out everything that's after the insertion point. | http://www.javaprogrammingforums.com/%20file-i-o-other-i-o-streams/4211-how-write-specific-part-html-file-using-java-printingthethread.html | CC-MAIN-2016-18 | refinedweb | 573 | 80.92 |
This:
Imports System.Data.OracleClient
using System.Data.OracleClient;
You also must include a reference to the DLL when you compile your code. For example, if you are compiling a C# program, your command line should include:
csc /r:System.Data.OracleClient.dll
Describes requirements for using the .NET Framework Data Provider for Oracle, and describes a number of issues to be aware when using it.
Describes the OracleBFile class, which is used to work with the Oracle BFILE data type.
Describes the OracleLob class, which is used to work with Oracle LOB data types.
Describes support for the Oracle REF CURSOR data type.
Describes structures you can use to work with Oracle data types, including OracleNumber and OracleString.
Describes support for retrieving the server-generated key Oracle Sequence values.
Lists Oracle data types and their mappings to the OracleDataReader.
Describes how the OracleConnection object automatically enlists in an existing distributed transaction if it determines that a transaction is active.
Describes secure coding practices when using ADO.NET.
Describes how to create and use DataSets, typed DataSets, DataTables, and DataViews.
Describes how to work with data in ADO.NET.
Describes how to work with features and functionality that are specific to SQL Server.
Describes generic classes that allow you to write provider-independent code in ADO.NET. | http://msdn.microsoft.com/en-us/library/77d8yct7.aspx | crawl-002 | refinedweb | 217 | 51.55 |
When starting a new project, templates can be beneficial to use as a starting point. The standard boilerplate code gets generated, and before you know it, the all too familiar “Hello World” text gets printed on the screen. It almost feels like magic. While new project templates are something we have become accustomed to, the code that gets created on our behalf shouldn’t be a mystery. After all, we are the ones who will ultimately support it!
In my next few posts, I will be dissecting all the commonly used ASP.NET Core project templates that are available to us in Visual Studio, starting with the ASP.NET Core Model-View-Controller template.
Getting Started
In ASP.NET Core, we can create a new project in one of two ways.
Both approaches are very clearly documented (thanks Microsoft!) so, I won’t go into detail here.
The Host Builder
Like any .NET application, our story begins with the Main method. If you’re entirely new to .NET, this method resides in the
Program class. As you can see below, a Host gets created and launched via the CreateHostBuilder method. The host is responsible for starting up our application and managing its lifetime. Just as the name implies, the Host host’s our application. When creating a web application, it also configures the webserver by establishing the HTTP request pipeline. We will go into this in more detail in the following sections.
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
It is also worth noting the CreateHostBuilder method returns a Generic Host via the IHostBuilder interface. .NET Core 2.1 introduced the generic host concept, which makes standard components such as dependency injection, logging, and application configuration available to many other application types. Console applications and worker services can now take advantage of these same features with ease.
StartUp “ConfigureServices”
As shown in the code snippet above, the web host builder references a
Startup class. This class is the next step in fully understanding the ASP.NET Core template. The
Startup class contains two critical methods for configuring our application.
- ConfigureServices
- Configure
The
ConfigureServices method is called first and for a good reason. It is here that all of the application’s services are registered. Sometimes framework level services are registered. Sometimes they are services of our own. Sometimes both. The beauty is, once they are registered, they are accessible to the rest of the application via dependency injection. If you are not familiar with how dependency injection works, I recommend familiarizing your self with it. Below are a couple of links to help you get started.
-
-
-
-
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); }
Our project only contains a single line in the
ConfigureServices method after being generated by the template. As the name implies,
AddControllersWithViews registers all services required for commonly used features with ASP.NET Core MVC. If we have any additional services we want to add, this is where we add them.
Startup “Configure”
Next in the line up is the
Configure method. The configure method establishes an application request pipeline and ultimately drives how the application responds to HTTP requests. In the following code, each method represents a middleware component that gets added to the?}"); }); }
Reviewing these two methods brings up a question. Why would we want to split Configure and ConfigureServices into separate methods? There are two reasons for this. First, this split provides us with a separation of concerns. We have one method to configure our services and one to configure the application request pipeline. Second, it gives us the ability to inject dependencies into the Configure method as parameters. In the template, we can see the IWebHostEnvironment interface as a parameter to the Configure method. In the same way, we can inject any other services we have registered. This strategy is not always required, but as you can see below, it can be helpful in certain circumstances.
We aren’t going to go into much more detail on the middleware component architecture; however, I’ve included some additional links below if you would like to explore further.
-
-
WWWRoot
If you noticed the
app.UseStaticFiles(); code in the
Configure method, then you have probably guessed that static files get served via the HTTP request pipeline as well. To create a clear separation between server-side .NET code and static content, all static files are placed in the
wwwroot folder. This folder typically consists of JavaScript, CSS, images, etc. but, not always HTML, as most of the HTML will get generated by the views. We will discuss this more in the following section.
Models, Views, and Controllers
Everything we have discussed so far can be found in any ASP.NET Core application. This post, however, focuses on the Model-View-Controller (MVC) template. If you’ve happened to stumble across my article, you are most likely already familiar with the MVC pattern. It has been around for quite some time. ASP.NET MVC 1.0 was launched about 11 years ago at the time of this writing. In the technology world, this is an eternity. There have probably been approximately 10,324,183 different JavaScript libraries launched in the last 11 years.
For those who are not familiar with MVC (or those that need a refresher), I will explain the MVC pattern in the following section. It is essential to understand the MVC pattern to understand the MVC template. But what is the best way to describe MVC? Most people describe the Model, the View, and then the Controller. Makes sense, right? I mean, it is called Model-View-Controller pattern after all. On the other hand, I like to think of MVC in terms of the life cycle of a request.
In frameworks like ASP.NET Core MVC, a request gets routed to a Controller. The controller receives input from the request then parses and validates it. If valid, the controller does some “stuff” with the data. This “stuff” could be saving to a database, calling a web service, or sending a message to a message bus. Whatever logic your application needs to perform is facilitated by the controller. Of course, it is essential to follow good architectural patterns without putting this logic DIRECTLY in the controller. A “service” as described above would be much better suited but, we won’t go into that here. The goal of this article is to describe the template and stay high level.
When the processing is complete, the controller will create a Model. At a high-level, the model will contain the data that we want to present to the user. I prefer to think of this model as a ViewModel. It is a model that provides data to view so, the name fits. It is important, though, that we don’t get this confused with the Model-View-ViewModel pattern, which is entirely different.
Lastly, we have the View. Using the data from the model, the view generates the HTML that gets returned to the user. ASP.NET Core has a robust view engine, called Razor, to facilitate this for us. With Razor, we can directly introduce C# code into our HTML markup. Try not to get confused with Blazor, though, as this code is executed server-side.
Now that we conceptually understand the MVC components, it comes as no surprise that each of them gets physically separated into their own folders. Some of this is even required. MVC follows a “convention over configuration” paradigm. For example, the views need to be in a specific folder structure to be routed to appropriately.
IN Closing…
I hope you enjoyed this article. As I said, project templates are powerful, but it is essential to resist the urge to dive-in to quickly. Ultimately, we are responsible for the applications we produce. It is necessary to understand each of the bits and pieces before we call it a day. Next, we will be discussing the newer ASP.NET Core Razor Pages template for those who want a more modern alternative to MVC. Stay tuned! | https://espressocoder.com/2020/07/27/whats-in-the-asp-net-core-mvc-template/ | CC-MAIN-2022-27 | refinedweb | 1,380 | 59.19 |
Design Guidelines, Managed code and the .NET Framework
Continuing in the series on sharing some of the information in the .NET Framework Standard Library Annotated Reference Vol 1 here are some of the annotations on the System.ArrayList class.
JM The IndexOf(string, int, int) method used to have as its last parameter the name “lastIndex.” This name caused confusion regarding whether the index was included in the search or not (inclusive or exclusive). Thus, as part of the standardization process the name got changed to “count” to avoid that confusion.
BG Note the heavy use of wrapper collections on ArrayList to add in functionality like thread safety or making a list read-only. This is very useful in that it allows users to write their code using ArrayList and then add in thread safety without having to change more than one line of code. At least, that was the original goal. However, there are two drawbacks with this approach. One is a subtle performance penalty — every method call on ArrayList is virtual, meaning it cannot be inlined and is therefore slower than it could be. The second is that the design isn’t quite what people need, at least for synchronization. Sometimes users may want code that does two operations with an ArrayList in a consistent state, like this:
ArrayList list = ArrayList.Synchronized(someOtherArrayList);
if (list.Count > 0)
Object node = list[0];
At this point, our threadsafe wrapper will not work as expected. True, the Count property will be accessed in a thread-safe way, as will the first element of the ArrayList. However, the way our design for the threadsafe wrapper works requires that we take a lock when calling each method, then release the lock after calling each method. Therefore, after we have retrieved the Count property, another thread could add or remove an element from the list, meaning that the next line might fail. The correct way to write code like this would be to use the SyncRoot property:
lock(list.SyncRoot) {
if (list.Count > 0)
Object node = list[0];
}
This code is correct and has the added benefit of taking the lock only once, instead of twice. Note the thread-safe wrapper collections are expected to use the SyncRoot property (defined on ICollection) to implement their thread-safety guarantees, so doing this in one part of your code is fully compatible with using a thread-safe wrapper in a different section of your code.
For these reasons, the SyncRoot property is a great idea and the idea of a thread-safe wrapper is less appealing than you’d like to believe. If we were designing collections over again, we might not allow subclasses of our collections for performance reasons and because they don’t add a lot of value. The IList interface should be rich enough for most users, and if it isn’t, the correct approach is to write another interface. Classes implementing that interface are free to use ArrayList internally for their own implementation details if necessary.
And here is a sample application:
using System;
using System.Collections;
namespace Samples
{
public class ArrayListConstructor
{
public static void Main()
{
string[] s = {"damien", "mark", "brad"};
ArrayList a = new ArrayList(s);
Console.WriteLine("Count: {0}", a.Count);
Console.WriteLine("Default Capacity: {0}", a.Capacity);
PrintElements(a);
s[0] = "maire";
s[1] = "sacha";
s[2] = "tamara";
}
public static void PrintElements(IEnumerable ie)
IEnumerator e = ie.GetEnumerator();
while(e.MoveNext())
Console.Write("{0} ", e.Current );
Console.WriteLine();
}
The output is
Count: 3
Default Capacity: 3
damien mark brad
---------------
Amazon.com Sales Rank: 7,992 (up 3676 from last post)
Amazon.com Sales Rank: 7,992 (up 3676 from last post) | http://blogs.msdn.com/brada/archive/2004/04/25/120055.aspx | crawl-002 | refinedweb | 611 | 62.98 |
Freed FoxOct 9, 2018Hi, @Tova (Wix), are there any way you could have an example for a dynamic page too? I tried it on my dynamic page but it seems the codes for the dynamic page and the product page is different, :)
Hi, @Tova (Wix), are there any way you could have an example for a dynamic page too? I tried it on my dynamic page but it seems the codes for the dynamic page and the product page is different, :)
Hi Debora and Freed Fox,
Thanks for your feedback.
Yes, you can add ratings and reviews to a dynamic page, and we've added it to our list of ideas for future code examples.
In the meantime, you can try searching the example code for properties and functions that specifically relate to a Product page, and replace them with the equivalent for a dynamic page.
For example, Line 15 of the Product Page Code uses the Product page getProduct() function. You can replace it with getCurrentItem(), which runs on your dynamic item page's dataset.
Hi @Tova (Wix) ,
Please find my reply below:
Ratings & Reviews Code
First, I created (2) databases. One for Reviews-Stats and the other for Reviews. Next, I add the code found in Example Store Reviews & Ratings page and replaced the 'getProduct()' function with the 'getCurrent() function in my dynamic item page.
Here is the page for review:
Tova, how do I get the page to function similar to the sample? I have made a few layout changes.
Previous / Next Button Code Issue
Also, I am experiencing issues with my previous / next buttons. I attempted to follow the directions and added the code for the page with the dataset:
But deleted the one for the dynamic page because it wasn't working.
Please adv.
Thank you. Debora
Hi @Tova (Wix),
I would apppreciate your help with fixing the issue(s) that I’m having with the code. Please see previous message. I realily would appreciate your help with this matter.
Thank you.
Debora
Hi Debora,
I took a look at your site. Here are a few pointers:
You are using the code from the old example, which is more complicated. Please copy the code from the new example.
The code in your Review Box lightbox is missing - you can copy it from the example.
Please check that you have all the datasets used in the example and that their settings and connections are the same as in the example.
Since you are using a dynamic page instead of a product page, make sure all references to productPage1 on the Experts dynamic page are replaced with references to your dataset: dynamicDataset. So for example, your code on Line 20 should state: product = await $w('#dynamicDataset').getCurrentItem();.
HTH! Tova
Hi @Tova (Wix),
I've been struggling to add ratings and reviews to a dynamic page, and I've already set it based on code examples you provided above for Debora with replacing CODE product = await $w('#productPage1').getProduct(); with $w('#dynamicDataset').getCurrentItem();. However it doesn't work properly with no error. After submitting the review form, all I can see in the database on live is Name,Location,review title and review. No Rating and recommend plus a field that references the item in a collection as recipes in my case.
For the record, I'm testing the code before applying to my real site.
Here is the page as testing for review:
I really need to get it solved for applying to my biz. Please diagnose and let me know what I'd have done. I really would appreciate if you advise me.
Thank you.
Jay
@juneyoung park Hey Jay, good news and bad news. The bad news is that it's too early in the day for a beer. The good news is that you just need to change a Lightbox setting. Set the "Automatically display lightbox on pages" to NO so that OpenLightbox() passes the data to the Lightbox.
I hope this helps. Have fun!
Yisrael
Hi Fellas Anyone manage to attached the rating display to repeater? It is not being attached. If its bug please fix it Wix Team.
Thanks, DA
Hi, @Tova (Wix)! I've got mine to working but the Recommended Text and Reviews sometimes does not load. Sometimes the text inside does not follow the code. Why is that? For example, when it must say There are no reviews", it doesn't/ It even show the placeholder text. Why is that?
Hi @Freed Fox,
I looked at the site you posted earlier in this thread and Reviews, Recommended Text, and "There are no reviews yet" worked for me. Can you describe the exact scenario where you run into problems? Make sure you are previewing from your "index" page with the repeater (in your case, Print on Demand Suppliers), and not directly from the dynamic item page. This is because the code needs to "grab" the product ID when you click the item in the repeater.
@Tova (Wix) Are you guys working on being able to update a review? I experimented with it before but it does not update the review-stats database. How can we be able to do that? I am not a coder so I really can't solve it 😂
Hi @Tova (Wix),
I have followed your directions and updated my current page(s). I would appreciate if you could review the code for the Dynamic Item page and the review box; plus help me with a couple of other code requests. Ratings & Reviews CodeHere is the page for review:
Database
Also, I have been experiencing issues with the Databases. Rich Text: Although the 'Text' font/size on the Dynamic Item page remains the same as the database data, the 'Rich Text 'doesn't take the set fonts/colors on the Dynamic Item Page. The color/font changes from Proxima to Times, etc. In addition, when adding the content, I am unable to add a link to the content or image. Pls. adv. Also, can I change the database name? If so, please adv. how.
Star Ratings w/Rate Me
Tova, can you adv. if I can add/connect the Star Ratings to Rate Me section of the Dynamic Item page for each individual profile. Is this doable? Please adv.
Thank you. for all your help! Debora
PS. Unable to add images. Will send under separate cover. (see other comments sent earlier)
I know this is an old post, but can you use this function on a dynamic item page without the light box feature? if so how would I do this?
I can't open the example link. Can you please repost it?
Add ratings & reviews to dynamic page items
I am trying to allow users to submit and see ratings on my dynamic Item pages. I followed the step-by-step (for over 6 long hours) tutorial on this example page.
However, it is will not work correctly. The one thing that differs on my site from the example page in this tutorial is that I am not connecting the reviews to a Wix store. My website works as a directory for Veterinary offices and clinics and I need to set up reviews about individual Facilities in my database. I changed the product ids (see below) to match the field keys in my Wix data, but I am not sure if it's correct.
Example Code:
import wixData from 'wix-data'; import wixWindow from 'wix-window'; let product; $w.onReady(async function () { product = await $w('#productPage1').getProduct(); initReviews(); });
I might also add that I have the following permissions settings for my Databases: UnitedStates_Facilities–only members can add, update, anyone can update & read); Reviews & ReviewStats Database–allow anyone to read, add, and update Data. (Not sure if this would affect my anything or not.)
Here's is a link to one of the dynamic pages and bellow is the code for both myDynamic Item Page and Lightbox:
Dynamic Item Page Code:
import wixData from 'wix-data'; import wixWindow from 'wix-window'; let facilityItem; $w.onReady(async function () { facilityItem = await $w('#facilityDataset').getCurrentItem(); initReviews(); }); async function initReviews() { await $w('#reviews').setFilter(wixData.filter().eq('itemId', facilityItem._id)); showReviews(); loadStatistics(); } async function loadStatistics() { const stats = await wixData.get('ReviewStats', facilityItem._id); if (stats) { let avgRating = (Math.round(stats.rating * 10 / stats.count) / 10); let percentRecommended = Math.round(stats.recommended / stats.count * 100); let ratings = $w('#generalRatings'); ratings.rating = avgRating; ratings.numRatings = stats.count; $w('#recoPercent').text = `${percentRecommended} % would recommend`; $w('#generalRatings').show(); } else { $w('#recoPercent').text = 'There are no reviews yet'; } $w('#recoPercent').show(); } export function reviewsRepeater_itemReady($w, itemData, index) { if (itemData.recommends) { $w('#recommendation').text = 'I recommend this product.'; } else { $w('#recommendation').text = "I don't recommend this product."; } $w('#oneRating').rating = itemData.rating; let date = itemData._createdDate; $w('#submissionTime').text = date.toLocaleString(); } export function showReviews() { if ($w('#reviews').getTotalCount() > 0) { $w('#reviewsRepeater').expand(); } else { $w('#reviewsRepeater').collapse(); } } export async function addReview_click(event, $w) { const dataForLightbox = { itemId: facilityItem._id }; let result = await wixWindow.openLightbox('Add Review', dataForLightbox); $w('#reviews').refresh(); loadStatistics(); $w('#thankYouMessage').show(); }
Lightbox Code
import wixWindow from 'wix-window'; import wixData from 'wix-data'; //-------------Global Variables-------------// // Current product's ID. let itemId; //-------------Lightbox Setup-------------// $w.onReady(function () { // Get the data passed by the page that opened the lightbox. itemId = wixWindow.lightbox.getContext().facilityName; // Set the action that occurs before the review is saved. $w('#submitReviews').onBeforeSave(() => { // If no rating was set: if ($w('#radioRating').value === '') { // Display an error message. $w('#rateError').show(); // Force the save to fail. return Promise.reject(); } // If a rating was set, set the element values into the fields of the dataset item. // These values will be saved in the collection. $w('#submitReviews').setFieldValues({ itemId, rating: $w('#radioRating').value, recommends: $w('#radioGroup1').value }); }); // Set the action that occurs after the review is saved. $w('#submitReviews').onAfterSave(async () => { // Update the product's statistics using the updateStatistics() function. await updateStatistics($w('#radioGroup1').value); // When the statistics have been updated, close the lightbox to return the user to the product page. wixWindow.lightbox.close(); }); }); // Update (or create) the product statistics. async function updateStatistics(isRecommended) { // Get the review statistics for the current product from the "ReviewStats" collection. let stats = await wixData.get('ReviewStats', itemId); // If statistics data already exist for this product: if (stats) { // Add the new rating to the total rating points. stats.rating += parseInt($w('#radioRating').value, 10); // Increase the ratings count by 1. stats.count += 1; // Increase the radioGroup1s by one if the user recommends the product. stats.recommended += (isRecommended === "true") ? 1 : 0; // Update the new product statistics in the "ReviewStats" collection. return wixData.update('ReviewStats', stats) } //If no statistics data exists for this product, create a new statistics item. stats = { // Set the statistics item's ID to the current product's ID. _id: itemId, // Set the statistics item's rating to the rating entered by the user. rating: parseInt($w('#radioGroup1').value, 10), // Set the statistics item's ratings count to 1 because this is the first rating. count: 1, // Set the statistics item's recommended property to 1 if the user recommends the product. recommended: (isRecommended === "true") ? 1 : 0 }; // Insert the new product statistics item into the "ReviewStats" collection. return wixData.insert('reviewStats', stats) } Database Screenshots:
Sorry this is so long. I would greatly appreciate someone's help with this!
Thanks!
Hello, I'm wondering if anyone would be able to help me with this. I almost got my site to work perfectly, but my reviews are showing up on all product instead a specific product.
Hey @Destiny Lozano,
Please clarify the issue. You only want reviews to appear for a single product instead of all products on your Product page? The example shows how to add reviews to all products.
Two questions that seems to don't be setup and tried but couldn't figure it out.
1. The load more button is hidden on load,even though there are 5 reviews or 15 the load more button will not be visible,how can we code this?A code that somehow checks the number of reviews?
2. The message "thank you for submitting a review" appears even when there is not review inserted,even if you X the lightbox,the code is not checking if a review was inserted just shows the text
Thank you
Hey @Mels Webb,
1. The load more button should not be hidden on load. It should be visible, as in the example.
The ID of the load more button is #resultsPages.
2. True, if the site visitor opens the Review lightbox and then closes it without submitting a review, the thank you message appears.
To handle this scenario, you can add a bit of code to the lightbox and the Product page.
If a site visitor submits a review, the lightbox will close via the lightbox close() function. Closing the lightbox by clicking the 'X' will not run the close() function. You can pass an object with a boolean value of 'true' via the close() function, which will only reach the Product page if a review was submitted.
Review Box code:
On the Product page, when a site visitor clicks "Write a Review", reset the thank you message by hiding it.
Then, after the site visitor closes the lightbox, check whether the object was passed from the lightbox to the Product page, indicating that a review was submitted. Only show the thank you message if the object was passed.
Product Page code:
HTH,
Tova
@Tova (Wix) hi Tova your reply is much appreciated
I will try this approach I am trying to write a code that checks the number of items in the repeater and if there are less than 5 will hide the button. I am struggling with how to approach it
Can you please have a look at my code and see if im on the rigth way
Trying to check the no of results in the repeater if more than 5 show the load more button if no hide
Added it to the on ready part
$w("#reviewsRepeater").forEachItem( ($item, itemData, index) => {
let total = data.length;
if($item.total > 5 ){ //if bigger than 5 show the button else hidr
Or maybe it is better to get the total count of the reviews from the repeater and hide/display the button accordingly? But than how i check the total number of reviews for each product id?
Thank you
Once a user does a review, how do we restrict live view until it is approved? is that possible? @Yoav (Wix) | https://www.wix.com/corvid/forum/corvid-tips-and-updates/example-store-reviews-rating/p-2 | CC-MAIN-2019-51 | refinedweb | 2,425 | 65.93 |
Dynamic Tag Libraries
Grails has a wide range of custom tags built in for both JSP and GSP (see the Tag Library Reference here), however Grails also allows the creation of simple, logical, and iterative custom tags through its simple dynamic tag library mechanism..
Simple tags
To:
def includeJs = { attrs -> out << "<script src='scripts/${attrs['script']}.js' />" }
To call your tag your from a GSP page use the "g" prefix followed by the tag property name:
<g:includeJs
Tag namespaces
By default, tags are added to the default Grails namespace and are used with the "g" prefix in GSP pages. However, you can specify a different namespace by adding a static property to your TagLib file:
class MyTagLib { static namespace = 'my' def someTag = { attrs -> ... } }
The tags in this tag lib must then be referenced from GSP pages like this:
<my:someTag
where the prefix is the same as the value of the static namespace property. Namespaces are particularly useful for plugins.
Since:
out << my.someTag(name:"foo")
This works from GSP, controllers or tag libraries
Logical tags
You can also create logical tags by using a closure syntax that takes 2 arguments, the attributes of the tag and the body of the tag as a closure:
def isAdmin = { attrs, body -> def user = attrs['user'] if(user != null && checkUserPrivs(user)) { out << body() } }
The tag above checks if the user is an administrator and invokes the body of the tag if he/she is:
<g:isAdmin // some restricted content </g:isAdmin>:
def userForUsername = { attrs, body -> def username = attrs['username'] def user = // look up User, perhaps from database if(user != null) { request.setAttribute('curUser', user) out << body() } }
And in the GSP:
<g:userForUsername <g:link Show User </g:link> </g:userForUsername>
Iterative tags
And of course you can create iterative tags:
def repeat = { attrs, body -> def i = Integer.valueOf( attrs["times"] ) def current = 0 i.times { // pass the current iteration as the groovy default arg "it" // then pass the result to "out" to send it to the view out << body( ++current ) } }
To call your iterative tag do the following:
<g:repeat <p>Repeat this 3 times! Current repeat = ${it}</p> </g:repeat>
Markup building in tags
Grails provides a special method that allows building of markup (a common usecase in tags). To do so you invoke the 'mkp' method passing a closure with the markup you want rendered:
def dialog = { attrs, body -> def mkp = new groovy.xml.MarkupBuilder(out) //this line will be unnecessary in versions of Grails after version 0.6 mkp { div('class':'dialog') { body() } } }
Tags as method calls in GSP
GSP tags can also be used in Groovy expressions in the GSP page. For example, the hasErrors tag can be used normally as a tag like this:
<g:hasErrors <span class='label error'>There were errors on the book title</span> </g:hasErrors>
Or as a method call, like this:
<span id="title" class="label ${hasErrors(bean:book,field:'title','errors')}">Title</span>
The last argument of the method is taken as the body of the tag. Or you can pass a closure that returns a string:
<%= hasErrors(bean:book,field:'title') { 'errors' } %>
Note that, although they look like method calls, dynamic tags cannot return values for use in the GSP page. They are intended to write directly to the output.
Using Grails tag libs from JSP
To use a Grails taglib definition in JSP you can use the JSP "invokeTag" tag which will call a tag defined in the Grail tag library:
<g:invokeTag <g:invokeTag // some restricted content </g:invokeTag > <g:invokeTag <p>Repeat this 3 times! Current repeat = <c:out</p> </g:invokeTag>:
package com.mycompany.taglib; public class IncludeJsTag extends JspInvokeGrailsTagLibTag { public static final String TAG_NAME = "includeJs"; public IncludeJsTag() { super.setName(TAG_NAME); } }
2) JSP requires declarative tag library definition files (TLD) for each tag, to do this modify the "web-app/WEB-INF/tld/grails.tld" file and add the necessary entries that point to your class:
>
3) You can then call your tag from JSP like a normal JSP tag:
<g:includeJs | http://grails.org/Dynamic+Tag+Libraries | crawl-001 | refinedweb | 677 | 54.36 |
Overview
Several different collections of information contribute to the overall definition of a digital asset:
The nodes inside the asset’s subnetwork.
The asset’s parameter interface.
Metadata such as the asset’s human-readable label and icon.
Extra files embedded in the asset, such as textures.
The Python implementation of the asset’s custom viewer state.
Except for the subnetwork contents, you edit all the rest using this window. As you develop an asset, you’ll open and use this window a lot, especially as you build and refine the asset’s parameter interface.
Note
Some of the information you set up when you created the asset, such as its human-readable label and the number of inputs, can be changed in this window. However, the internal name you set when you create the asset (which may include a namespace and version) becomes intrinsic to the asset and cannot be changed. If you make a mistake or want to change it, you must create a new asset.
Type properties vs. spare parameters
You can use a similar interface to add spare parameters and/or render properties to a single node. It’s important to keep the difference between editing an asset’s node type, as in this window, and adding spare parameters to a single node.
Spare parameters are "extra" parameters added to a single node instance, which are not part of the node’s inherent parameter interface. You can add spare parameters to both assets and "factory" nodes. They are useful for one-off customizations.
Render properties are a special type of spare parameter that convey information about the node (object, camera, material) to the renderer. Most render-related nodes are created with a set of render properties that you can add to.
If you are trying to add an extra parameter to a single node, you want a spare parameter. If you are customizing rendering, you want a render property. If you want to change the base parameter interface shared by all nodes of a certain asset type, you want this window.
How to
Basic tab
Label
The human-readable label for the node type. This is what Houdini shows when the node appears in the user interface, such as in the ⇥ Tab menu..
Version
You can use this field with "upgrade handlers" to provide scripts to update old (but forward-compatible) version of a node when a new version is available. Do not confuse this field with the asset version which is part of the asset’s internal name. See the two types of asset versioning for more information.
Minimum Inputs
The number of inputs that must be connected for this node to work. The node may have more inputs than this (set by Maximum outputs below), but if the first N inputs are not connected the node will error.
Maximum Inputs
The number of inputs the node has. Note that Houdini does not check that this number is greater than or equal to Minimum inputs — You can have a node with no inputs but a minimum input count of 1, meaning it will always error.
Use controls on the Input/Output tab to give the input(s) human-readable labels.
Maximum Outputs
If the node category (for example, VOP) allows multiple outputs, this is number of outputs on the node.
Use controls on the Input/Output tab to give the output(s) human-readable labels.
Parameters tab
A significant percentage of the work on an asset will involve editing the asset’s parameter interface, which is how users will control the asset’s options.
There are several ways to build the parameter interface.
Many parameters will be promoted from nodes inside the asset.
When you "promote" a parameter, Houdini creates a copy of the parameter on the asset, and replaces the original parameter’s value with an expression that references the value of the parameter on the asset. This means the parameter on the asset drives the value of the corresponding parameter inside.
For example, you might have an asset that scatters points on a surface and copies boxes onto the points. Inside the asset you, the author, will have a network with a
Scatter node and a
Box node, but the user will see the asset as a single node, and won’t see or interact with its contents. You will want the user to be able to control the number of points and the size of the boxes from the asset’s interface, so you would promote those specific parameters from the nodes inside onto the asset.
You can create new parameters on the asset. You can set up references for these parameters manually, or use callbacks/scripting to make the parameters functional.
For example, you might want one "Size" float parameter on the asset to drive all three of a contained node’s Scale X, Scale Y, and Scale Z values. You could create a float parameter on the asset and manually set up references to it on the contained node.
If you are building a material, Material assets automatically create parameters corresponding to any
Parameter VOPs inside the asset. See building a material for more information about material assets.
The Parameters tab is divided into three panes:
Create Parameters
This contains tabs representing different sources for parameters you can add to your asset. The By type tab lets you create new parameters from scratch.
Existing Parameters
This represents the node’s current parameter interface. You can drag in parameters from the left pane or the parameter editor to add to it, or drag items within the tree to rearrange it.
Parameter Description
When a parameter is selected in the middle pane, you can edit its settings in this pane.
Import blocks
When you are developing a set of complex assets, with high-level assets that build on low-level assets, you sometimes want to promote an entire block of parameters from a lower-level asset onto the higher-level asset you're authoring. However, you want to be able to continue to edit the lower-level parameters and not have to re-promote them every time.
Import blocks let you promote a block of parameters and have them remember where they were promoted from so you can automatically update them with changes to the originals.
Parameter types
Tip
There is no "menu" parameter type. If you want the user to choose a value from a pop-up menu, create an Integer or String parameter and then use the controls on Menu sub-tab under Parameter Description to set up a menu of value choices.
Angle
A single float representing an angle in degrees. In old versions of Houdini this had a different UI than a plain float but this is no longer the case.
Button
A clickable button. You can enter a script to run when the user clicks the button.
Button Strip
A horizontal strip of labeled options. The buttons can be mutually exclusive or individually set. See how to create a button strip parameter above, and how to write a button strip callback.
Color
A 3 float vector parameter with a UI for editing the value as a color. Channels use the suffixes
rgb instead of
123.
Color and Alpha
A 4 float vector parameter with a UI for editing the value as a color with alpha channel. Channels use the suffixes
rgba instead of
1234.
Data
Stores arbitrary binary data. The parameter has no UI, you must read or write the value in a script. This can be useful for stashing data on a node instance. For example, this is how the
Stroke SOP stores stroke data.
The Data parameter type can use the following tags:
Direction Vector
A 3 float vector representing a direction. In old versions of Houdini this had a different UI than a plain vector but this is no longer the case.
File
A string representing a file path, with a UI for choosing a file from disk.
File - Directory
A string representing a directory path, with a UI for choosing a directory from disk.
File - Geometry
A string representing a path to a geometry file, with a UI for choosing a file that filters out non-geometry files by default.
File - Image
A string representing a path to an image file, with a UI for choosing a file that filters out non-image files by default.
Float
A single floating point value.
Float Vector 2
Two floating point values.
Float Vector 3
Three floating point values, for example a 3D position.
Float Vector 4
Four floating point values, for example a quaternion.
Folder
A container for other parameters. Folders let you organize the node’s parameters. You can choose to present the folder in different ways, such as a tab, group box, or collapsible section. Adjacent tabs join together automatically.
Icon Strip
Like Button Strip but with icons on the buttons instead of text labels. The buttons can be mutually exclusive or individually set. See how to create an icon strip parameter above, and how to write an icon strip callback.
Integer
A single integer value.
Integer Vector 2
Two integer values.
Integer Vector 3
Three integer values.
Integer Vector 4
Four integer values.
Key-Value Dictionary
Stores a table of string → string associations.
Label
A read-only line of text.
Logarithmic Float
A single float, but the slider UI affects the value on exponential scale.
Logarithmic Integer
A single integer, but the slider UI affects the value on exponential scale.
Min/max Float
Two floats representing a low and high. Channels use the suffixes
min and
max instead of
1 and
2. Nodes with a parameter of this type will not load in Houdini versions before 16.0.
Min/max Integer
Two integers representing a low and high. Channels use the suffixes
min and
max instead of
1 and
2. Nodes with a parameter of this type will not load in Houdini versions before 16.0.
Operator List
A string representing a space-separated list of node paths, with a UI for choosing multiple nodes.
Operator Path
A string representing a node path, with a UI for choosing a node.
RGBA Mask
An integer bitmask created from a UI allowing the user to turn each of a red, green, blue, and alpha button on or off individually.
Ramp (Color)
Ramp (Float)
Separator
Inserts a separator line into the UI to organize the parameters.
String
A text box for editing a string value.
Toggle
A checkbox for editing a boolean value.
UV
Two floats representing surface coordinates. Channels use the suffixes
uv instead of
12.
UVW
Three floats representing surface coordinates. Channels use the suffixes
uvw instead of
123.
Parameter tags
Common settings
Name
The internal name of the parameter. This is how channel references and scripts refer to the parameter.
Label
The human readable label for the parameter. This is what appears next to the parameter’s UI in the parameter editor. You can turn off the checkbox to not show any label next to the controls.
Type
The parameter type. This affects how the value is stored and how the parameter is presented to the user in the parameter editor interface.
Invisible
When this is on, the parameter is not shown in the parameter editor, but you can still read and write its value using expressions and scripts.
By default, invisible parameters are not shown under Existing parameters. If you want to show them so you can select them, rearrange them, and delete them, turn on Show invisible parameters at the top.
Horizontally join to next parameter
Put this parameter and the next parameter in the same row in the parameter editor interface. Note that you can turn this on for more than one parameter in a row to layout three or more parameters horizontally. If all the "joined" parameters can’t fit in a line, they will wrap to the next line.
When you have 2 or more related, compact controls in a row, you can join them to save space.
You can make a checkbox, turn its label off, and "join" it to the next parameter, for a UI where the checkbox controls whether the parameter applies or not, similar to the Label control in this pane. (Note that you still need to actually implement that UI using expressions.)
Show parm in
There can be a few different parameter interfaces in Houdini. This controls which of these different interfaces this parameter appears in.
Main Dialog Only
Parameter only appears in the parameter editor.
Main & Tool Dialogs
Parameter appears in the parameter editor and the floating parameter editor in the viewer.
Main & Tool Dialogs + Toolbox
Parameter appears in the parameter editor, and the operator toolbar across the top of the viewer when the node is active, and the floating parameter editor in the viewer.
Disable when
A rule for when this parameter should appear disabled/non-editable. This lets you set up parameters to dynamically disable based on the value of other parameters. See disable/hide when syntax.
Hide when
A rule for when this parameter should not appear. This lets you set up parameters to dynamically hide themselves based on the value of other parameters. See disable/hide when syntax.
Callback script
Houdini will runs this script when the value of this parameter changes.
The pop-up icon menu to the right of this field lets you set whether the callback script is in HScript command language or Python.
If the value in the field is one line, it is treated as a Python expression and evaluated. If it has more than one line, it is treated as if it was the body of a function and must use a
return statement at the end to return a value.
The script runs in an environment containing a
kwargs global dictionary variable containing information about which parameter changed.
See parameter callback scripts for more information.
Available for import
If you turn this off, this item will not be included when its parent folder is imported as a block.
This is displayed as a tooltip when the user hovers over the parameter.
String settings
Multi-line string
Display this field as a multi-line editor instead of a single line text field.
Note that all string parameters can hold multi-line text. You can get an extended multi-line editor for a single line text field by pressing Alt + E in the field. This checkbox simply changes the look/capabilities of the user interface for editing the sting.
Lines to Show
When Multi-line string is on, this is the minimum and maximum number of lines to show in the editor. The field will always be the minimum number of lines tall. If the content has fewer lines than the maximum, the field automatically sizes down to fit, and expands as the user types more, until the content has more than the maximum lines to show, at which point the content will scroll.
Language
If the field will contain source code, you can specify a programming language to enable auto-completion and syntax highlighting in the field.
Suppress Quotes in VOP Code Blocks
Whether this parameter should be expanded without quotes within VOP code blocks. A common use is to allow strings from menus to be placed verbatim in a code block. Only available for string parameters in a VOP definition.
Numeric settings
Units
Specifies a unit type for this parameter’s value, such "distance" or "mass". Choose a unit type from the pop-up menu to the right of the field, or leave this field blank if this value should not scale with a change in units.
This tells Houdini whether/how to scale the parameter’s default value when the user changes the HIP file’s units. For example, if the user changes the HIP file’s units to
cm, it will use this setting to scale any defaults related to length/distance.
The code uses the format
m/kg/sexponent[m/kg/sexponent ...]. For example, length would be
m1. Acceleration would be
m1s-2 (that is, meters/seconds2, using a negative exponent instead of division). The following are some useful unit type specifications:
Size
When Type is Integer, Float, or Angle, sets the number of components in the parameter (1 to 4).
Defaults
The default value for the parameter. If Size is greater than 1, a default can be specified for each component.
Range
The range for the slider in the interface.
If you click the lock icon next to low and/or high value, the interface prevents the user from manually entering values lower and/or higher than this range.
Node path/list settings
Op filter
Filters which types of nodes the user can see and select in the chooser interface for this parameter.
For example, if the parameter requires the path to a bone, you would set this to "Object: Bone Only" to make it easier for the user to select from just the bones in the scene.
File settings
Browse Mode
For operating systems that have a different file chooser UI depending on whether you're opening or saving a file (such as MacOS), this lets you specify which type of operation is associated with this parameter.
For example, in a parameter that specifies a geometry file to load, you would set this to "Read Only". For a parameter that specifies an output file to write to, you would set this "Write Only".
Houdini’s file chooser currently does not use this information. This only makes a difference if you are using native file dialogs (you have set the
HOUDINI_USE_NATIVE_FILE_CHOOSER environment variable) and the native file dialogs make this distinction (as on MacOS).
Folder settings
Folder type
How the parameter editor displays this group of parameters in the parameter editor.
Collapsible
Display as a collapsible heading containing the parameters.
Simple
Display as a labeled box around the parameters.
Tabs
Display as a tab. Multiple adjacent "tab" folders in the parameter tree display as a tab set in the parameter editor.
Radio buttons
Display as a tab that can change the operation of the node depending on which tab in the set is selected.
Import Block
Displays its contents as part of the normal parameter flow. This is useful when you are importing a folder as a block but don’t want the parameters to appear inside a tab or whatever other folder type you're importing.
Multiparm Block
A multiparm lets the user create multiple instances of a parameter. This folder type sets up an interface to let the user add parameters. The parameter(s) inside this folder act the template for the generated parameter blocks the user can add or delete.
"List" style adds the user-generated blocks as part of the normal parameter layout in the parameter editor. "Scrolling" style puts the user-generated blocks inside a scrolling area. "Tabs" puts each user-generated block in a separate tab in a set.
End tab group
Adjacent "tab" folders are merged into a tab set. If you want a series of tabs to be in different tab sets, turn this on for the last tab in each set. It indicates this is the last tab in its set and if the next item is also a tab it should start a new set.
Tab disable when
A rule for when all parameters in this tab should appear disabled/non-editable. See disable/hide when syntax.
Tab hide when
A rule for when this tab should be hidden. See disable/hide when syntax.
Import settings
Turn this on have this folder import its contents from a folder on a node inside this asset. See import blocks.
Source
A reference to the node or file this folder imports its contents from, when Import settings is on.
Token
A reference to which item to import from the node/file, when Import settings is on.
Mask
Only import parameters matching this pattern, when Import settings is on.
Ramp settings
Ramp type
This can be "Color" for a color ramp or "Float" for a scalar curve ramp.
Color type
When Ramp type is "Color", this specifies the model to use to generate color from the three channels in the data: "RGB", "HSV", "LAB", "HSL", "XYZ", or "TMI".
Default Points
The initial number of points when this parameter is created.
Def Interpolation
The default interpolation between ramp points for this parameter.
First Instance
The number associated with the first ramp point. This only affects how you refer to the ramp points in scripts.
VEX Ramp Variables
When this parameter is on a shader, this lets you specify VEX variable names for the basis, keys, and values parameters.
Show Controls By Default
Ramp parameters have a panel of controls below them that the user can collapse to save space. When this is on, the controls for this ramp will be visible at first when the node is created. When this is off, the controls will be collapsed at first.
Key-Value settings
Key label
The text to display at the top of the left (key) column in the parameter UI. If you leave this blank, it uses "Key".
Value label
The text to display at the top of the right (value) column in the parameter UI. If you leave this blank, it uses "Value".
Add chooser
Turn this on to add a button in the parameter UI to choose a key-value pair from a predefined list.
Chooser label
The text to display on the chooser button (when Add chooser is on).
Chooser callback
A Python script Houdini runs when the user clicks the chooser button (when Add chooser is on). This script can present an interface for the user to choose a preset (for example, using hou.ui.selectFromList() or hou.ui.selectFromTree()). It must return a
(key, value) tuple.
See how to write a key-value parameter button script for more information.
Channels sub-tab
This sub-tab shows the animatable channels associated with this parameter.
By default, Houdini creates an animated channel for each component of the parameter value (so for example, a Translate vector parameter would get three channels, one for each component of the vector). However, you can have the parameter generate more (computed) channels or fewer channels.
You can turn on the
Auto-add icon for a channel to make it key-able and automatically added to the Channel List when the node containing this parameter is selected.
You should turn this on for all commonly animated values.
If this parameter is promoted, the "Linked Channels" column shows which channels this parameter was promoted from on the contained node. When the
Link button in the middle is on, the channel gets its value from the linked channel.
Menu sub-tab
Import sub-tab
Houdini stores information here about where a parameter was promoted from, for use when updating import blocks. You should not edit this information unless you know what you're doing.
Action Button sub-tab
Disable when/Hide when syntax
Often you want to dynamically show or enable parameters based on the values of other parameters. For example, you might have a checkbox that enables some feature, and only want to enable editing parameters related to that feature when the checkbox is on.
The Disable when and Hide when settings of a parameter let you set up when the parameter should be disabled or hidden. The value is a code using the syntax shown below to calculate whether to disable/hide based on other parameter values.
The general syntax is:
{ parm_name [operator] value ...} ...
One or more comparisons inside curly braces.
Inside the curly braces are one or more comparisons with a parameter name, a comparison operator, and a value.
The following comparison operators are available:
==,
!=,
<,
>,
>=,
<=,
=~(matches pattern),
!~(doesn’t match pattern).
{ type == 1 count > 10 } { tolerance < 0.1 }
Note
You must put spaces around the comparison operator, otherwise Houdini will not accept the rule.
You can omit the comparison operator, in which case it will be assumed to be
==. For readability however we recommend you always explicitly type an operator.
{ geotype 1 } { geotype 2 }
If there are multiple comparisons inside a set of curly braces, all the comparisons must be true for that condition to be true.
For example, with the condition below, if the
enablefeaturecheckbox parameter is on and the
countparameter is more than
10, this parameter would be disabled/hidden:
{ enablefeature == 1 count > 10 }
If there are multiple conditions (sets of curly braces), any of the conditions may be true to activate disabling/hiding.
For example, with the condition below, if the
enablefeaturecheckbox parameter is on or the
countparameter is more than
10, this parameter would be disabled/hidden:
{ type == 1 } { count > 10 }
You can’t use expression functions in the rule string. However, a workaround is to create an invisible parameter containing an expression that calculates what you need, and then reference it in a comparison.
There are a few special functions you can use in place of the parameter name on the left side of a comparison. (You can not use these as a value on the right side of a comparison.)
ninputs()
The highest wired input number. This may be more than the number of wires if inputs in the middle are not connected. It also counts subnet inputs that may not be wired in the parent node.
hasinput(n)
Returns
1if the given input number is connected, or
0if not. This does not count an input wired into a subnet input if that input is not also wired in the parent node.
isparm(parmname)
Returns
1if this parameter’s name is parmname. This is meant for use with multiparm items.
For example, this rule would apply to the first item in a multiparm named
blend, but not the second (
blend1), third (
blend2), and so on:
{ isparm(blend0) == 1 }
Node tab
Representative Node
For Object assets, this lets you choose a node inside the asset to indicate the general type of object the asset is (for example, a light, or camera, or geometry object). Houdini can use this information to filter and categorize this asset in the UI, such as in the link editor.
Guide Geometry
For SOP assets, Houdini will cook this node to create guides shown along with the node’s actual output. Guide geometry lets you include "extra" geometry aside from the node’s output to serve as indicators or visualization. For example, volume SOPs often have guide geometry indicating the bounding box, with ticks indicating the voxel size.
Editable Nodes
A space-separated list of node paths. These nodes can be edited even if this asset is locked.
Usually you want assets to seem like self-sufficient black boxes to the user, however for complex operations it might be expedient to let the user dive inside and modify nodes such as paint nodes or curves that affect how the asset works.
Editability does not "bubble up" to assets containing other assets. If node A is editable in asset B, that does not automatically make it editable in an asset C which contains an instance of B. You would need to list A as an editable node of C.
Message Nodes
A space-separated list of node paths. Warnings and errors on these nodes will bubble up onto the asset node. List any nodes inside the asset that might cause problems so the user will be able to see the warning/error.
For example, if you have a File node inside your asset that loads a path defined on the asset, you should include it in this list so if it can’t find the file the error is visible on the asset.
Dive Target
If this contains a subnetwork path, when the user double-clicks the asset (or uses the "Dive into Network" command), the network jumps to the contents of this subnetwork instead of the asset’s own contents. If you have a dive target you should add the target node to the list of Editable nodes above.
Since the contents of an asset are always the asset’s definition network, this is a workaround to allow assets to seem to the user as if the asset is a subnetwork with its own contents.
Users can still navigate to other nodes inside the asset using the tree view and other means. This setting only affects the "Dive in"/"Up to parent network" actions.
NOTE: The target should be a network, as the final location is looking within the dive target. If the target is a normal node, the dive target will be ignored.
Descriptive Parm
If this contains the internal name of a parameter on this asset, Houdini will display the value of the parameter as the descriptive text badge in the network editor.
This should be a parameter whose value tells the user at-a-glance the most important thing about the node’s current settings. For example, on a File node this is the file path.
Default State
If this is not blank, when the user enters the Handles tool for this node, use this "state" instead of the generic node state.
Currently, the most common use for this is to set it to
stroke to have the Handles tool use the
Stroke state when a node of this type is active. Other built-in states are too coupled with a specific node to work here.
If you write your own interactive state using the HDK or your own custom python state, you can use this setting to associate your custom state with the asset.
Shader Name
For material nodes, this is used as the internal name of the shader (for Mantra shaders, this is the name of the VEX shader function). This should usually be the same as the asset’s internal name.
Houdini automatically converts illegal characters in this string (for example,
principledshader::2.0 might become
principledshader__2_0 internally).
Shader Type
Narrows down the type of computations a material does and indicates how it should be invoked, and what the material can be expected to compute. Choose a type from the pop-up menu to the right of the field. The most common one is "vopmaterial" (which can provide both surface and displacement shaders). But the field can be also
surface or
displace if it only generates one type of shader. For RenderMan it is often
bsdfshader or
generic.
Render Mask
For material assets, this lists the renderer(s) this material works with. For example, the Principled Shader works with Mantra and the viewport OpenGL renderer, so its mask is
VMantra OGL. The Pxr Disney shader only works with RenderMan, so its mask is
RIB.
VopNet Mask
A space-separated list of VEX contexts in which the user can create this node. If you leave this blank, the node can appear in any context.
Available context keywords are
surface (surface shading),
displace (displacement shading),
chop (motion data:
VOP CHOP),
cop2 (compositing:
VOP COP2 Generator and
VOP COP2 Filter), and
cvex (no specific context: e.g.
Attribute VOP,
Point VOP).
Unit Length
The length (in meters) of one distance unit, according to the units used for values and defaults in the asset. For example, if you developed the asset assuming 1 unit = 1 foot, you should set this to
0.3048.
Houdini uses this to scale "distance" parameters according to the HIP file’s units (Edit ▸ Preferences ▸ HIP file options). You can specify that a parameter represents distance using the Units setting for the parameter on the Parameters tab.
Unit Mass
The mass (in kilograms) of one mass unit, according to the units used for values and defaults in the asset. For example, if you developed the asset assuming 1 unit = 1 pound, you should set this to
0.45.
Houdini uses this to scale "mass" parameters according to the HIP file’s units (Edit ▸ Preferences ▸ HIP file options). You can specify that parameter as represents mass using the Units setting for the parameter on the Parameters tab.
Get Properties from Vex Code
Allow pragma statements in the VEX source code to control settings in this window.
Input/Output tab
For VOPs, this tab lets you set up the inputs and outputs that appear on the node and their types.
For other node type categories, the controls on this tab let you give human-readable labels to the asset’s inputs and outputs. These appear in the network editor as tooltips when the user hovers over a connector.
VOP assets
The tab has two table editors, one for inputs and one for outputs.
Click Create/update inputs from parameters to automatically create inputs based on the node’s parameters. This lets the user override parameter values by connecting inputs.
The button creates inputs with the same name and label, and guesses the input type from the parameter type. If an input already exists with the same name as a parameter, the button only updates the label, so that changes to the input type aren’t overwritten.
Inputs based on parameters cannot be edited in the table. They are marked with an
info icon.
If you manually create an input that has the same name as a parameter, they will automatically be linked.
To add an input or output, choose the type from the New input or New output menus above the tables.
Click the name, or label of an existing input/output in the table to edit it.
Select the first cell in a row and then drag it up or down to rearrange the row in the table.
You can select multiple rows by Shift-clicking or Ctrl-clicking the first cell of each row, and then drag multiple rows at once.
You can drag column headings to rearrange signature order.
To delete an input/output, click the
Delete icon in the row.
Some cells cannot be edited or deleted. For example, inputs corresponding to parameters, and outputs corresponding to exported parameters or VOP network outputs.
Force code generation
When a VOP operator appears in a VOP network, the VEX Builder will only include the code generated by that operator if it determines that its code is required. Generally, this is true for subnet type VOPs, the Output VOP, and any VOP that is connected, directly or indirectly, to the input of a VOP that has required code. However, you can force the VEX Builder to generate the code for your VOP by turning on Force Code Generation.
External or Procedural Shader
Turn this on if this VOP is implemented by a DSO or DLL file instead of generated VEX code.
VOP signatures
A VOP can have multiple signatures: a set of input types and output type. For example, the
Sine VOP has different signatures (float → float, vector → vector) corresponding to the different usages of the VEX sin function.
Each signature is represented by a column in the inputs table, and three columns in the output table. You can match them up by the Signature name (the first cell in a signature column). Initially, a VOP node has one signature named
default.
You can use the New signature button to add a new signature (that is, a new way of calling the underlying VEX code with a different set of typed arguments and a different output). This adds one new column to the top inputs table, and three columns to the bottom outputs table.
The first cell in a signature column is the signature name. The second cell is a human-readable label for the signature. These are shown in both the signature column in the input table and the corresponding first column of the signature in the output table. Editing the name or label in one table automatically updates the other.
In the inputs table, the rows of a signature column (after the name and label rows) contain the types of each input when that signature is active. (The user chooses the active signature from a pop-up menu at the top of the node’s parameter interface.) click a cell to choose the type from a pop-up menu.
In the outputs table, the rows of the first signature column (after the name and label rows) contain the type of the output.
To provide a default parameter to use for a particular signature, create a parameter with the same name as the input, followed by an underscore, then the name of the signature.
For example, suppose you have two inputs, color and multiplier, which have the data types vector4 and float. You would create two parameters, also called color and multiplier. The first would be a Color parameter, and the second a single float parameter. Now you want to allow multiplier to also be a vector4. Create a new signature, and name it v4. Change the data type of multiplier for that signature to vector4. The create a new parameter named multiplier_v4, which is 4 floats. Now when one of these operator is created, and the signature is set to v4, the VEX Builder will use the color and multiplier_v4 parameters to provide the default values..
Code tab
This tab lets you create and edit code used to implement Python surface nodes, VEX shaders, VOP operators, and other code-based operators.
Scripts tab
This tab lets you store scripts that are triggered by asset events (such as when an instance of the asset is created or deleted), as well as arbitrary scripts and Python modules needed by the asset. The interface is very similar to the Extra files tab, but includes a pop-up menu for specifying event scripts.
Do not create a script (on the Scripts tab) and an extra file (on the Extra files tab) with the same name. The two tabs share a single namespace, and unpredictable behavior may result.
See how to write asset event scripts in the Scripting chapter for information on how to write the Python event scripts.
See how to reference embedded files for how to refer to the embedded scripts anywhere Houdini expects a filename.
Adding and loading scripts
Interactive tab
This section contains several tabs for defining and editing the interactive content of the asset.
Viewer State
Use this tab to create, edit and store a python viewer state script associated to this asset. When the asset is loaded, Houdini registers the viewer state to make it available for use. Likewise, when the asset is unloaded, the viewer state is unregistered from Houdini and no longer available for use.
Viewer State Code Generator
The Viewer State Code Generator dialog lets you create a new viewer state script. The code generator provides pre-defined samples, ranging
from basic to more complete viewer state implementations. Each sample provides a class implementation and the mandatory
createViewerStateTemplate callback
function.
The resulting code should help you implement your viewer state in no time and help you understand better how the different API, bindings and event handlers involved in a python viewer state can fit together. Along with samples, the code generator lets you choose from several options to generate the skeleton code of specific event handlers.
Note
The code generator dialog is a tool for generating code, it’s not a tool to assist you in editing your python state code. Once you enter and accept the dialog options, the code is generated and copied into the python editor. You cannot go back to the code generator, change options and expect your code to update accordingly.
Tip
For HDA states, the asset node type's name is used as the state's name by default. This is clean and makes it easy to associate the state with the asset. The state's name is then used to fill in the Default state field on the Node tab. This means the contents of the Default state field would never be out-of-sync with the embedded state name.
The generated code uses the Default state field like this:
def createViewerStateTemplate(): state_typename = kwargs["type"].definition().sections()['DefaultState'].contents()
If you set a state name different than the asset node type's name, remember that it must be unique across all states and installed asset names.
(The contents of the Default state field are stored internally in an "extra files" section named
DefaultState, so you can read it or even change in a script using this method.)
Shelf Tools
This tab lets you create shelf tools associated with this asset. When the asset is loaded, the tools you define on this tab will be available for the user to add to the shelf, and will show up in the viewer tab menu.
Note
Any tools you define on this tab will not automatically show up on the shelf whenever the asset is available. The user has to add the tools to the shelf, by right-clicking the shelf and choosing Edit Shelf Tab, then choosing the tools from a list of all available tools.
When you create an asset, Houdini automatically adds a tool to this tab, that invokes a generic script to create an instance of the asset. You can edit the script of this tool, or add additional shelf tools to provide alternate ways of instantiating the asset. Click Create New and choose Tool to start a new tool.
See how to create shelf tools.
Handles tab
The controls on this tab let you create handles (3D user interface elements that appear in the 3D view) and bind the editable parts of the handles to parameters on your asset. This lets the users of your asset control it interactive in the view. The handles appear in the Handles tool when an instance of this asset is current.
The controls in this pane are the same as for the Persistent handle editor.
Selectors tab
Note
This interface is leftover from old versions of Houdini. It only works for object-level assets, and only supports using HScript commands. The modern way to ask for selections is to incorporate selection in the Python tool script of a shelf tool.
This tab will probably disappear in a future version of Houdini.
This tab lets you set up a (possibly multi-step) selection process to allow the user to select what (objects/geometry) the node applies to when you create it. For example, you have the node prompt the user to select an object your object-level asset will attach to.
The Type field is not editable and reflects the basic type of the
selector. The Name field is the english name which should uniquely
define this selector with respect to the operator type. The Prompt
field displays the string during the selection process. The
Multi-selection checkbox indicates whether or not multiple object
selections are allowed for the current selector. The editable text
field allows for a user-defined script to be executed when object
selections are finished. The input objects are accessed by the
variables
$argc, and
$arg0, $arg1,..., $arg($argc-1), where
$argc is
the number of inputs and the remaining variables represent each of
the input objects.
There is no variable which holds a path to your current node; however, you can retrieve the current node using the
pwd HScript command.
For example, you can wire in the first selected input into your current node by doing the following:
set curNode = `run("pwd")` opwire -n $arg0 -1 $curNode
Extra Files tab
Any "unsaved" files (either by changing them in the editor, or because they're newly added) will have an asterisk in the section list.
Save tab
Save information from node
This shows the path of the specific node instance Houdini will use to update the asset contents if you click Apply or Accept in this window. (This is the node you right-clicked and chose Type properties for to open this window.)
Save Contents and Parameters
When this is off, when you click Apply or Accept in this window, changes you made in this window will be saved to the asset definition, but changes to the current node (its parameter values/defaults and contents) are not saved as part of the asset definition.
You should not turn this off unless you have a good reason.
Save Defaults as Initial Parameters
When this is on and you save the node type definition, the current node’s defaults are saved as the initial values for new instances. When this is off and you save the node type definition, the current node’s current parameter values are saved as the initial values for new instances.
Save Spare Parameters
If this is on and you save the node type definition, any spare parameters on the current node are saved as part of the node type, so any new instances would have the same spare parameters added.
Save Contents as Locked
Never turn this off. See Unlock new nodes on creation instead.
Unlock New Nodes on Creation
When Houdini creates new instances of this node type, they are automatically unlocked (that is, editable). This was added for example files. When you put down an example asset, you don’t have to unlock it before you can go inside it and play with the nodes inside.
This should always be off for assets you will give to users for use in production.
Compress Contents
Gzip is faster, Blosc gives better compression but may be slightly slower. The decompression speed of Gzip is practically unnoticeable on modern hardware, so there’s usually no point to using No Compression.
Check for External Node References
Show a warning if there references in the asset to nodes outside the asset when you save.
Save Cached Code
When this checkbox is turned on, Houdini saves compiled VEX code inside the HDA and uses it instead of generating that code from the node network.
Currently, it applies mainly to the Shader Builder SHOPs, which contain VOP nodes. Traditionally Houdini would use nodes to generate .vfl source code and then compile it to vex. By using the cached vex code, Houdini saves time, which can be quite substantial for complex shaders. Also, the synched HDA nodes don’t need to create child nodes to build the VOP network inside them (since they are not needed to generate code), so time is saved by skipping the creation of node network when loading hip files. | https://www.sidefx.com/docs/houdini/ref/windows/optype.html | CC-MAIN-2020-05 | refinedweb | 7,736 | 62.38 |
Read, then Write CSV with "Non-ISO extended-ASCII" text Encoding
My csv has strings like:
TîezÑnmidnan
I'm trying to use the following below to set up a reader/writer
import csv # File that will be written to csv_output_file = open(file, 'w', encoding='utf-8') # File that will be read in csv_file = open(filename, encoding='utf-8', errors='ignore') # Define reader csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"') # Define writer csv_writer = csv.writer(csv_output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
Then iterating over the information read in
# Iterate over the rows in the csv for idx, row in enumerate(csv_reader): csv_writer.writerow(row[0:30])
Problem is in my output file I can't get it to show up with that same string. According to my mac, the csv file type has the encoding "Non-ISO extended-ASCII"
I tried various encodings and some would just remove the special characters while others just wouldn't work.
It's weird because I can hard code that string above into a variable and use it without problems, so I assume it's something to do with how I'm reading in the file. If I breakpoint before it writes it shows up as the following in the debugger.
T�ez�nmidnan
I can't convert the file before running it, so the python code has to handle any conversions itself.
The expected output I want would be for it to remain in the output file looking like
TîezÑnmidnan
Edit: chardetect gave me "utf-8 with confidence 0.99" | http://quabr.com/52725539/read-then-write-csv-with-non-iso-extended-ascii-text-encoding | CC-MAIN-2019-09 | refinedweb | 255 | 57.5 |
Implementation status: to be implemented
Synopsis
#include <grp.h>
void endgrent(void);
struct group *getgrent(void);
void setgrent(void);
Description
The functions operate on the group database, which contains for each users' group:
The
group structure is defined in <
grp.h> as follows:
struct group { char *gr_name; /* group name */ char *gr_passwd; /* group password */ gid_t gr_gid; /* group ID */ char **gr_mem; /* NULL-terminated array of pointers to names of group members */ };
Arguments:
None.
The
getgrent() function returns a pointer to a structure containing the broken-out fields of an entry in the group database. If the group database is not already open,
getgrent() opens it and returns a pointer to a group structure containing the first entry in the database. Thereafter, it returns a pointer to a group structure containing the next group structure in the group database, so successive calls may be used to search the entire database.
The
setgrent() function rewinds the group database so that the next
getgrent() call returns the first entry, allowing repeated searches.
The
endgrent() function closes the group database.
On error, the
setgrent() and
endgrent() functions set
errno to indicate the error.
If you want to check for error situations, you should set
errno to
0, then call the function, then check
errno.
These functions are not thread-safe.
Return value
On success the
getgrent() function returns a pointer to a
group structure. On end-of-file,
getgrent() returns a null pointer and does not change the setting of
errno. On error,
getgrent() returns a null pointer and
errno is set to indicate the error.
The application doesgrgid(),
getgrnam(), or
getgrent(). The returned pointer, and pointers within the structure, are invalidated if the calling thread is terminated.
Errors
[
EINTR] - A signal was caught during the operation.
[
EIO] - An I/O error has occurred.
[
EMFILE] - All file descriptors available to the process are currently open.
[
ENFILE] - The maximum allowable number of files is currently open in the system.
Implementation tasks
- Implement the
getgrent()function.
- Implement the
endgrent()function.
- Implement the
setgrent()function. | http://phoenix-rtos.com/documentation/libphoenix/posix/endgrent | CC-MAIN-2020-34 | refinedweb | 336 | 57.27 |
To begin, in a Flight.fxfile, define a JavaFX class that corresponds to the structure of the flight element:
public class Flight{
public var number: String;
public var time: String;
public var direction: String;
public var carrier: String;
public var destination: String;
public var origin: String;
}
In a main JavaFX application (Main.fx) or in a location of your design, invoke a RESTful web service from a function loadFlightsSchedules using the JavaFX object HttpRequest (see Listing 1). All the pertinent properties and functions are declared within the declarative scope of HttpRequest.).
In the function onInput: function(input: java.io.InputStream), Listing 1 handled the XML results from a web service by invoking the FlightsParser, which is a custom extension of the JavaFX object javafx.data.pull.PullParser. PullParsers supports direct query- and event-based XML parsing (similar to the SAX parser).
To load the elements from the parsed XML into a Flight object, you can use the (abbreviated) code in Listing 2.
This quick 10-Minute Solution has demonstrated how to use the GETmethod to invoke a RESTful web service and how to parse its results into a JavaFX object with minimal error handling.
For more details on web services processing and parsing of other data types, review the JavaFX objects javafx.io.http, javafx.data.pull, and javafx.data.xml.
Advertiser Disclosure: | https://www.devx.com/Java/Article/40659/0/page/2 | CC-MAIN-2021-43 | refinedweb | 223 | 52.39 |
As a long-time Core Audio programmer, Apple’s introduction of Swift left me both excited and confused. I was excited by the prospect of a modern language built with performance in mind, but I wasn’t entirely sure how functional programming could apply to “my world.” Fortunately for me, many have explored and conquered this problem set already, so I decided to apply some of what I learned from those projects to the Swift programming language.
Signals
The basic unit of signal processing is, of course, a signal. In Swift, I would declare a signal as follows:
public typealias Signal = Int -> SampleType
You can think of the
Signal type as a discrete function in time that returns the value of the signal at that instant in time. In most signal processing texts, this is often denoted as
x[t], so it fits my world view.
Let’s define a sine wave at a given frequency:
public func sineWave(sampleRate: Int, frequency: ParameterType) -> Signal { let phi = frequency / ParameterType(sampleRate) return { i in return SampleType(sin(2.0 * ParameterType(i) * phi * ParameterType(M_PI))) } }
The
sineWave function returns a
Signal, which itself is a function that converts sample indices into output samples. I refer to these “inputless” signals as generators, since they generate signals out of nothing.
But I thought we were talking about signal processing? How do we modify a signal?
No high-level discussion about signal processing would be complete without demonstrating the application of gain (or a volume control):
public func scale(s: Signal, amplitude: ParameterType) -> Signal { return { i in return SampleType(s(i) * SampleType(amplitude)) } }
The
scale function takes an input
Signal called
s, and returns a new
Signal with the scalar applied. Every call to the
scaled signal would return the same output of
s(i), scaled by the supplied
amplitude. Pretty straightforward stuff, right? Well, you can only go so far with this construct before it starts to get messy. Consider the following:
public func mix(s1: Signal, s2: Signal) -> Signal { return { i in return s1(i) + s2(i) } }
This allows us to compose two signals down to a single signal. We can even compose arbitrary signals:
public func mix(signals: [Signal]) -> Signal { return { i in return signals.reduce(SampleType(0)) { $0 + $1(i) } } }
This can get us pretty far; however, a
Signal is limited to a single “channel” of audio, and certain audio effects require much more complex combinations of operations to happen at once.
Processing Blocks
What if we were able to make connections between signals and processors in a more flexible way, matching up more closely with the way we think about signal processing? There are popular environments, such as Max and PureData, which compose signal processing “blocks” to create powerful sound effects and performance tools.
Faust is a functional programming language that was designed with this idea in mind, and it is an incredibly powerful tool for building highly complex (and performant!) signal processing code. Faust defines a set of operators that allows you to compose blocks (or processors) together in a way that mimics signal flow diagrams.
Similarly, I have created an environment that effectively works the same way.
Using our earlier definition of
Signal, we can expand on this concept:
public protocol BlockType { typealias SignalType var inputCount: Int { get } var outputCount: Int { get } var process: [SignalType] -> [SignalType] { get } init(inputCount: Int, outputCount: Int, process: [SignalType] -> [SignalType]) }
A
Block has a number of inputs, a number of outputs, and a
process function that transforms the
Signals on its inputs to a set of
Signals on its outputs. Blocks can have zero or more inputs, and zero or more outputs.
To compose blocks serially, you could do the following:
public func serial<B: BlockType>(lhs: B, rhs: B) -> B { return B(inputCount: lhs.inputCount, outputCount: rhs.outputCount, process: { inputs in return rhs.process(lhs.process(inputs)) }) }
This function effectively takes the output of the
lhs block as the input to the
rhs block and returns the result. It’s like connecting a wire between two blocks. Things get a little more interesting when you run blocks in parallel:
public func parallel<B: BlockType>(lhs: B, rhs: B) -> B { let totalInputs = lhs.inputCount + rhs.inputCount let totalOutputs = lhs.outputCount + rhs.outputCount return B(inputCount: totalInputs, outputCount: totalOutputs, process: { inputs in var outputs: [B.SignalType] = [] outputs += lhs.process(Array(inputs[0..<lhs.inputCount])) outputs += rhs.process(Array(inputs[lhs.inputCount..<lhs.inputCount+rhs.inputCount])) return outputs }) }
A pair of blocks running in parallel combines inputs and outputs to create a larger block. Consider a pair of
Blocks that produces sine waves together to create a DTMF tone, or a stereo delay
Block that is a composition of two single-channel delay
Blocks. This concept can be quite powerful in practice.
But what about a mixer? How would we achieve a single-channel result from multiple inputs? We can merge blocks together using the following function:
public func merge<B: BlockType where B.SignalType == Signal>(lhs: B, rhs: B) -> B { return B(inputCount: lhs.inputCount, outputCount: rhs.outputCount, process: { inputs in let leftOutputs = lhs.process(inputs) var rightInputs: [B.SignalType] = [] let k = lhs.outputCount / rhs.inputCount for i in 0..<rhs.inputCount { var inputsToSum: [B.SignalType] = [] for j in 0..<k { inputsToSum.append(leftOutputs[i+(rhs.inputCount*j)]) } let summed = inputsToSum.reduce(NullSignal) { mix($0, $1) } rightInputs.append(summed) } return rhs.process(rightInputs) }) }
To borrow convention from Faust, inputs are multiplexed such that the inputs of the right-hand side block come from outputs on the left-hand side modulo the number of inputs. For instance, three stereo tracks with a total of six channels would go into a stereo output block such that output channels 0, 2, and 4 are mixed (i.e. added) into input channel 0, and 1, 3, and 5 are mixed into input channel 1.
Similarly, you can do the opposite and split the outputs of a block:
public func split<B: BlockType>(lhs: B, rhs: B) -> B { return B(inputCount: lhs.inputCount, outputCount: rhs.outputCount, process: { inputs in let leftOutputs = lhs.process(inputs) var rightInputs: [B.SignalType] = [] // Replicate the channels from the lhs to each of the inputs let k = lhs.outputCount for i in 0..<rhs.inputCount { rightInputs.append(leftOutputs[i%k]) } return rhs.process(rightInputs) }) }
Again, a similar convention is used with the outputs such that one stereo block being fed into three stereo blocks (accepting six total channels) would result in channel 0 going into the inputs 0, 2, and 4, with channel 1 going into inputs 1, 3, and 5.
Of course, we don’t want to get stuck with having to write all of this with long-hand functions, so I came up with this collection of operators:
// Parallel public func |-<B: BlockType>(lhs: B, rhs: B) -> B // Serial public func --<B: BlockType>(lhs: B, rhs: B) -> B // Split public func -<<B: BlockType>(lhs: B, rhs: B) -> B // Merge public func >-<B: BlockType where B.SignalType == Signal>(lhs: B, rhs: B) -> B
(I’m not quite happy with the “Parallel” operator definition, as it looks an awful lot like the symbol for “Perpendicular” in geometry, but I digress. Feedback is obviously welcome.)
Now, with these operators, you can build some interesting “graphs” of blocks and compose them together. For instance, consider this DTMF tone generator:
let dtmfFrequencies = [ ( 941.0, 1336.0 ), ( 697.0, 1209.0 ), ( 697.0, 1336.0 ), ( 697.0, 1477.0 ), ( 770.0, 1209.0 ), ( 770.0, 1336.0 ), ( 770.0, 1477.0 ), ( 852.0, 1209.0 ), ( 852.0, 1336.0 ), ( 852.0, 1477.0 ), ] func dtmfTone(digit: Int, sampleRate: Int) -> Block { assert( digit < dtmfFrequencies.count ) let (f1, f2) = dtmfFrequencies[digit] let f1Block = Block(inputCount: 0, outputCount: 1, process: { _ in [sineWave(sampleRate, f1)] }) let f2Block = Block(inputCount: 0, outputCount: 1, process: { _ in [sineWave(sampleRate, f2)] }) return ( f1Block |- f2Block ) >- Block(inputCount: 1, outputCount: 1, process: { return $0 }) }
The
dtmfTone function runs two parallel sine generators and merges them into an “identity block,” which just copies its input to its output. Remember, the return value of this function is itself a block, so you could now reference this block as part of a larger system.
As you can see, there is a lot of potential in this idea. By creating an environment in which we can build and describe increasingly complex systems with a more compact and understandable DSL (domain specific language), we can spend less time worrying about the details of each individual block and how everything fits together.
Practicality
If I were starting a project today that required the best possible performance and most rich set of functionality, I would run straight to Faust to get going. I highly recommend that you spend some time with Faust if you are interested in pursuing this idea of functional audio programming.
With that said, the practicality of my ideas above rests heavily on Apple’s ability to advance its compiler such that it can identify patterns in the blocks we define and turn them into smarter output code. Effectively, Apple needs to get Swift compiling more like Haskell does, where functional programming patterns can be collapsed down into vectorized operations on a given target CPU.
Frankly, I feel that Swift is in the right hands at Apple and we will see the powerful kinds of ideas I presented above become commonplace and performant in the future.
Future Work
I will keep this “Functional DSP” project up at GitHub if you would like to follow along or contribute ideas as I play around with the concepts. I plan to investigate more complex blocks, such as those that require FFTs to calculate their output, or blocks that require “memory” in order to operate (such as FIR filters, etc.)
Bibliography
While writing this article, I stumbled upon the following papers that I recommend you delve further into if you are interested in this area of research. There are many more out there, but in the limited time I had, these seemed like really good starting points.
- Thielemann, H. (2004). Audio Processing using Haskell.
- Cheng, E., & Hudak, P. (2009). Audio Processing and Sound Synthesis in Haskell. | https://www.objc.io/issues/24-audio/functional-signal-processing/ | CC-MAIN-2017-30 | refinedweb | 1,690 | 53 |
Generalized set operations and comparisons in the style of Haskell
Subset provides basic and generalized set operations for JavaScript. They are inspired by a subset of the interface to Haskell's Data.List, but optimized for JavaScript semantics.
The new ES6
Set class is not particularly helpful for doing set operations on general objects (as their only version of equality is
===), and this module provides a general alternative for people who want to do the same-ish things on arrays.
Use it with qualified imports with the yet unfinished module
import syntax or attach it to the short variable of choice. For selling points, here's how it will look with ES7 modules.
; // [ 2, 4 ]; // [ 1, 3, 5, 4, 6 ];// [ { a: 1 }, { a: 3 }, { a: 2 } ]; // [ 1, 3, 2, 4 ]var > 1;var primes = ; // [ 2, 3, 5, 7, 11 ]; // [ [1], [2,2], [3], [5,5], [2] ]; // [ 1, 2, 3, 3, 4 ]delete12323 2; // [ 1, 3, 2, 3 ]
Note that it is often useful to get it with the larger utility library interlude for which it was made.
MIT-Licensed. See LICENSE file for details. | https://www.npmjs.com/package/subset | CC-MAIN-2017-09 | refinedweb | 184 | 66.07 |
A template-less manager for OperationCaller calls. More...
#include <rtt/internal/OperationCallerC.hpp>
A template-less manager for OperationCaller calls.
Definition at line 55 of file OperationCallerC.hpp.
The default constructor.
Make a copy from another OperationCallerC object in order to make it usable.
Add a datasource argument to the OperationCaller.
Add an argument by reference to the OperationCaller.
Definition at line 118 of file OperationCallerC.hpp.
Add a constant argument to the OperationCaller.
Definition at line 106 of file OperationCallerC.hpp.
Checks if this method is ready for calling, will throw if not so.
Otherwise, does nothing.
Store the result of the method in a task's attribute.
Store the result of the method in a DataSource.
Store the result of the method in variable.
Definition at line 140 of file OperationCallerC.hpp.
Send the contained method.
The returned SendHandleC is properly constructed, but still requires the .arg() arguments. The arguments to provide are the ones that collect requires for the sent operation. Once they have been added to the SendHandleC, you can collect() on that object. | http://www.orocos.org/stable/documentation/rtt/v2.x/api/html/classRTT_1_1internal_1_1OperationCallerC.html | CC-MAIN-2016-18 | refinedweb | 178 | 54.49 |
By Andrej Budja
By today’s network standards, DNS has been around for a long, long time. You’d think it would have been replaced by now. However, DNS is alive and kicking. In fact, it’s become an essential part of every Windows 2000 network. Before you can effectively use DNS and take advantages of its many features, you have to know why Microsoft uses it.
Why do I need DNS?
Look no further than Active Directory (AD) for your reason to know DNS. Every AD domain (and any host computer in the domain) must have a name. When we have to name something, we have to agree on a standard naming system. For example, we have to agree on how many characters we can use and which characters are allowed. For Windows 2000, Microsoft decided to use DNS as its naming standard.
“Understanding DNS in Windows NT 4.0”“What's in a name? Creating a DNS server”“Getting ready for Windows 2000”
Namespace definition
All names adhere to the DNS standard. The standard states that a single name (for example, mycomputer) can be up to 63 bytes and that a fully qualified domain name (FQDN), such as mycomputer.techrepublic.com, can be up to 255 bytes. The only exception regarding the size of the name is that an FQDN for a domain controller is limited to 64 bytes. We use bytes instead of characters because Windows 2000 also supports Unicode characters that can take up to 3 bytes.
If you remember from Windows NT 4, NetBIOS names are limited to 15 characters. The 16th character is reserved for the NetBIOS suffix. We still have NetBIOS names in Windows 2000, but only for compatibility with lower-level clients (Windows NT 4, Windows 9x, and so on). Another advantage over NetBIOS is that DNS is a hierarchical system, while NetBIOS is essentially flat. This means that a NetBIOS name can be used only once in the whole network, which poses a problem in very large networks with many hosts. Because DNS is hierarchical, we can use one name many times, but only once in a given domain. For example, we can't have two computers named www in the techrepublic.com domain, but we can have one computer named www in the techrepublic.com domain and another named www in the netadmin.techrepublic.com domain.
Name resolution
Another reason for using DNS in Windows 2000 is name resolution. If we have a computer name, such as mycomputer, and we want to communicate with that machine, there must be a way to resolve this name to an IP address. Since computers use numbers to resolve addresses, and we’re already using DNS as a namespace definition, it's logical to use DNS servers for name resolution.
Service resource records
In old non-Windows 2000 networks, we have to know the name of a host if we want to use its resources. For example, if you want to download files from an FTP server, you have to know the name of that server. If we have one or two servers, we can remember their names—but imagine having thousands of servers to choose from. Not only would it be hard to remember all the names, we would also have problems remembering which servers run FTP, which are mail servers, and so on.
DNS solves this problem with special service resource records (SRV RR). These records allow us to query a server by type of service it performs. For example, we could just issue a query for an FTP server and DNS would return all servers that had FTP server software installed.
Active Directory uses SRV RR extensively. Actually, you can’t run AD without a DNS server that supports these records. So the moment a user types a username and password, his or her Windows 2000 client will use DNS and SRV RR to locate the closest domain controller. When the closest domain controller is found, the computer will validate against this controller. This is a great solution if your users travel a lot and use a notebook. There will be no unnecessary traffic over slow WAN links when you have domain controllers on your local network.
DNS is apparently here to stay. Universally accepted and now an integral part of the Windows 2000 network, this naming standard is not going to be replaced anytime soon. So if you aren’t familiar with it, I hope this article has given you some background on why DNS is so important to networks around the globe.
Like DNS, Andrej Budja, MCSE+I, MS MVP, has been around computers for a long time. He likes to learn new technologies and is known as a guy who’s always ready to help. He does this every day in the Microsoft Windows 2000 newsgroups.If you'd like to share your opinion, please post a comment below or send the editor an e-mail. | https://www.techrepublic.com/article/build-your-skills-the-role-of-dns-in-windows-2000/ | CC-MAIN-2018-05 | refinedweb | 828 | 72.16 |
I recently attended elm-conf (videos of the elm-conf presentations), which was hosted at Strange Loop on its preconference day. I’d been meaning to play around with Elm for years and was finally sparked to do so to prepare for the conference.
As I often do when trying to learn a new language, I came up with a little side project that I could implement in Elm. The project is a very basic reporting app that would pull data from a REST API.
I ran into trouble when I wanted to make a request to the API. This was immediately followed by another request that makes use of the data returned from the first. There are plenty of examples out there showing how to make a single HTTP request in Elm—but I couldn’t find anything that showed how to chain multiple requests together.
It turns out, it’s really easy to do! To help the next developer who wants to chain HTTP requests together in Elm, I’m going to walk through an example here.
(Note: The code snippets might say they’re Haskell, but they’re really Elm. Our snippet highlighter doesn’t recognize Elm yet, and the Haskell highlighter does a pretty good job.)
HTTP.get
The README for the
evancz/elm-http package has a good example of making a single HTTP request:
import Http import Json.Decode as Json exposing ((:=)) import Task exposing (..) lookupZipCode : String -> Task Http.Error (List String) lookupZipCode query = Http.get places ("" ++ query) places : Json.Decoder (List String) places = let place = Json.object2 (\city state -> city ++ ", " ++ state) ("place name" := Json.string) ("state" := Json.string) in "places" := Json.list place
Elm Architecture Cmd
In order to make an HTTP request within The Elm Architecture, you need to use
Task.perform. The Tasks section of the Elm Tutorial provides the following example:
module Main exposing (..) import Html exposing (Html, div, button, text) import Html.Events exposing (onClick) import Html.App import Http import Task exposing (Task) import Json.Decode as Decode -- MODEL type alias Model = String init : ( Model, Cmd Msg ) init = ( "", Cmd.none ) -- MESSAGES type Msg = Fetch | FetchSuccess String | FetchError Http.Error -- VIEW view : Model -> Html Msg view model = div [] [ button [ onClick Fetch ] [ text "Fetch" ] , text model ] decode : Decode.Decoder String decode = Decode.at [ "name" ] Decode.string url : String url = "" fetchTask : Task Http.Error String fetchTask = Http.get decode url fetchCmd : Cmd Msg fetchCmd = Task.perform FetchError FetchSuccess fetchTask -- UPDATE update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of Fetch -> ( model, fetchCmd ) FetchSuccess name -> ( name, Cmd.none ) FetchError error -> ( toString error, Cmd.none ) -- MAIN main : Program Never main = Html.App.program { init = init , view = view , update = update , subscriptions = (always Sub.none) }
In short, you call
Task.perform, passing it a constructor for the failure message, a constructor for the success message, and the task to run. Cutting out everything else, here’s (a slightly modified version of) the
Task.perform on a single line:
Task.perform FetchError FetchSuccess (Http.get decode "")
Chaining Tasks with `andThen`
The documentation for andThen states:
This is useful for chaining tasks together. Maybe you need to get a user from your servers and then lookup their picture once you know their name.
Exactly what I wanted to do!
Once I came across
andThen, I still struggled a bit thinking that I was supposed to be chaining two
Task.perform results together. It wasn’t until I finally understood that an
Http.get call returns a Task, and so does an
andThen call, that I realized I wanted to
andThen the two
Http.get calls together and pass that result to the
Task.perform.
So here it is. A very simple (once I finally understood what to do) example of chaining two HTTP requests together in a single command.
decodePlanet : Decode.Decoder String decodePlanet = Decode.at [ "name" ] Decode.string decodePerson : Decode.Decoder String decodePerson = Decode.at [ "homeworld" ] Decode.string fetchPlanet : String -> Task Http.Error String fetchPlanet url = Http.get decodePlanet url fetchPerson : Task Http.Error String fetchPerson = Http.get decodePerson "" fetchCmd : Cmd Msg fetchCmd = Task.perform FetchError FetchSuccess (fetchPerson `andThen` fetchPlanet)
The trick is to call
Task.perform once, passing a
Task to it that’s a sequence of the first
Http.get (
fetchPerson) followed by the second
Http.get (
fetchPlanet). It’s worth noting that the
fetchPlanet function takes a String argument, which is the URL parsed from the first request.
Hopefully, this will help someone stuck on the same problem I was having. | https://spin.atomicobject.com/2016/10/11/elm-chain-http-requests/ | CC-MAIN-2018-13 | refinedweb | 751 | 69.48 |
A Complete guide to Google Colab for Deep Learning
Google Colab is a widely popular cloud service for machine learning that features free access to GPU and TPU computing. Follow this detailed guide to help you get up and running fast to develop your next deep learning algorithms with Colab.
Google Colab is one of the most famous cloud services for seasoned data scientists, researchers, and software engineers. While Google Colab seems easy to start, some things are difficult to use. In this guide, you will learn:
- Why Colab
- Creating a new notebook
- Import Notebooks from GitHub/local machine
- Google Drive with Colab
- Keyboard shortcuts for Colab
- Change Language (Python 3 -> Python 2)
- Select GPU or TPU
- Load Data from Drive
- Load Data from Github Repository
- Importing External Datasets such as from Kaggle
- Download Packages
- Bash commands in Colab
Why Colab
There are several benefits of using Colab over using your own local machines. Some of the benefits of Colab are
- You do not require to do an environment setup. It comes with important packages pre-installed and ready to use.
- Provides browser-based Jupyter Notebooks.
- Free GPU
- Store Notebooks on Google Drive
- Importing Notebooks from Github
- Document code with Markdown
- Load Data from Drive
- and much more
Creating a new notebook
To create a new Notebook on Colab, open, and it will automatically show your previous notebooks and give an option to create a new notebook.
Here you can click on NEW NOTEBOOK to start a new notebook and start running your code in it. By default, it is a Python 3 notebook. I will show you later how to make a new Python 2 notebook.
Alternatively, if for some reason you do not see this prompt, or you canceled it, You can make a new notebook from “File > New Notebook”.
Import Notebooks from GitHub/local machine
Here you can see these 2 boxes which show GitHub and Upload option.
For Github, at first, you need to authorize with Colab with your GitHub, and then it will show you all available repositories from which you can create a new notebook.
GitHub with Colab.
For uploading from your local machine, you will be prompted to upload a file from your local machine to run it in Colab.
Upload from your local machine.
Google Drive with Colab
All the notebooks you create in Google Colab, are by default stored in your Google Drive. There is a folder in your drive named “Colab Notebooks” where you can find all your notebooks created from Google Colab.
To open a notebook from Drive in Colab, right-click on the desired notebook and “Open With > Google Colaboratory”.
Similarly, if you are in a notebook in Colab, and want to see it in the drive, you can do it using “File > Locate to Drive”, which will redirect you to the notebook position in your Drive.
Locate Notebook in Google Drive from Colab.
Keyboard Shortcuts for Colab
Most of the keyboard shortcuts of Colab are similar to those of the Jupyter Notebook. Let's look at some important ones.
- Shortcut to show all the shortcut keys.
- You can see all the shortcut keys with ctrl + M + H the key. When looking for any specific shortcut, you can search here.
Shortcut key menu.
- New Code Block
- You can add a new code block by Ctrl + M + B.
- Convert Cell to Markdown
- You can convert a cell to Markdown by using Ctrl + M + M shortcut key.
- Convert from Markdown to Code
- To convert from Markdown to Code, you can use Ctrl + M then quickly press Y. I can say it as Ctrl + M followed by Y. Remember not to press them altogether but follow the order.
There are many other great shortcut keys that you can search using Ctrl + M + H key.
Change Language from Python 3 to Python 2
Now with the official end of support of Python 2, Python 2 is no longer available at Colab. Now for some reason, someone sends you a python 2 code, or you have to check something in Python 2 quickly, all you can do is to go to these links
which will eventually redirect you to this link from where you can test your Python 2 code.
Hardware Selection (GPU or TPU)
Colab’s biggest advantage is that it provides free support to GPU and TPU. You can easily select GPU or TPU for your program by Runtime > Change runtime type.
Change runtime type.
After clicking on the Change runtime type, you will be prompted to select GPU or TPU.
You can also use your local GPU with Colab Interface. In order to do that, do the following steps.
- Start a Jupyter notebook instance at your local machine.
- Copy its URL with Token
- Click on the arrow here(It may be written ‘connect’ in some cases)
- Click on connect to local runtime
- After clicking, you will see this prompt
- Paste the link here, and connect it.
Load Data from Drive
You can easily load data from Google Drive by mounting it to the notebook. To do this, type the following code in your notebook.
from google.colab import drive
drive.mount('gdrive')
It will give you a link to open,
- Go to the link
- Login to your Google Account
- Copy the code
- Paste it in notebook
Now if you see in your “Files” section, you will find your ‘gdrive’.
Let's say you have uploaded is under the Untitled folder.
You can get it by
myfile = open('gdrive/My Drive/Untitled folder/dataset1.csv)
And you get your file.
Load data from Github
Let’s say your data set is in Github, and you want to load it. You can do it simply by downloading it as you download it normally in your machine
!git clone REPOLINK
%cd REPONAME
If it is in zip format, you can unzip it by
!unzip GPR_radargrams.zip
%cd GPR_radargrams
And now you have access to data. Later in this tutorial, I will show you how to use bash commands, after that this part will make more sense and easy to use for you.
Import Dataset from Kaggle
- Step 1 is to get a Kaggle API Token. Go to My account > API > Create New API Token.
- Go to API and click on Create New API token. You will receive a JSON file which you can save it.
- Install Kaggle Library and Import Google Colab Files in your notebook.
from google.colab import files
!pip install -q kaggle
- Upload your Kaggle API JSON file to Colab.
uploaded = files.upload()
- Go to Dataset you want to download, and click on copy API command, under 3 dots.
- Copy the command and put a ‘!’ before it and run it on Colab, i.e.,
!kaggle datasets download -d ruchi798/malnutrition-across-the-globe
and it will download the dataset for you.
Download Packages
Although all important packages such as Tensorflow, PyTorch, Numpy, Pandas, etc are installed, you can install further packages or upgrade current ones.
To download the packages, you can simply use the command through which you download datasets in your local machine with ‘!’ in the start.
Let's say you want to download the pillow package in your Colab (though it will be downloaded by default), just type the following code and run the cell.
!pip install pillow
If it is already downloaded, it will show
otherwise, it will download it for you.
To update a package, let's say TensorFlow, use following
!pip install tensorflow --upgrade
which will upgrade your package, and you might need to restart runtime.
Bash Commands on Colab
To run any bash command on Colab, you can add ‘!’ before the command, and it will run. For example, to see items in your directory, you can use
!dir
or to check your CUDA and CUDNN, you can use
!nvcc --version
which will output
This brings us to the end of this article. I hope you have learned how to set up your Google Colab for deep learning and its important usage.
Related: | https://www.kdnuggets.com/2020/06/google-colab-deep-learning.html | CC-MAIN-2021-21 | refinedweb | 1,338 | 71.95 |
.
Keys and Certificates Profiles.
Enabling the GlassFish v2 Application Server as an SSL Server
The steps to enable the GlassFish v2 as an SSL server depend on the profile used for the application server. Let's first examine the process if the developer profile is used. Then let's examine the process when the enterprise profile is used.
When the Developer Profile is Used
Recall that a GlassFish v2 profile presets configuration
parameters for a particular type of use. One of those
parameters is Security Store, which identifies how security and
trust-related artifacts such as certificates and keys are
stored. For the developer profile, the Security Store value is
set to JKS. In this case, certificates and keys for the server
are stored in a Java keystore file (
keystore.jks) and
certificates issued by trusted CAs are stored in a certificates
file (
cacerts.jks).
When you install GlassFish v2, it creates a default self-signed certificate as the server certificate. However, if authentication is important in your site, you need to replace the self-signed certificate with a digitally-signed certificate from a CA. This section describes how to replace the self-signed certificate, how to obtain a server certificate from a CA, and how to import the server certificate into the keystore.
The steps described below use
keytool, a key and certificate
management tool.
Keytool is available in various versions of the
Java Platform, Standard Edition (Java SE) Development Kit (jdk).
However Java SE 6 added some required functions to
keytool. The
instructions below are based on the jdk 6 version of
keytool.
For detailed information about
keytool, see JDK Tools and
Utilities. CA such as VeriSign. In response, you should receive a signed server certificate. Make sure to import into your browser the CA certificate of the CA. Refer to your
browser documentation on how to import the CA and
intermediate CA certificates into the browser. The CA may
provide information on how to import the CA certificates
into various browsers such as Mozilla and Internet Explorer.
s1as.cert). You can use
keytoolto do this, as follows:.
After running the program, you should see that the certificate
s1as in the GlassFish keystore is no longer the original
self-signed certificate, but is now the response certificate
from the CA. Here is an example that compares an original
s1as
certificate with a new
s1as certificate obtained from VeriSign:
Original
s1as(self-signed):
Owner: CN=KUMAR,=KUMAR,
After performing these steps, you can restart GlassFish v2 and use the signed server certificate issued by the CA.
When the Cluster Profile is Used
You perform the same steps to enable GlassFish v2 as an SSL server when the application server is configured with the cluster profile as you do for a developer profile. However, in this case you need to ensure that the same server key in replicated in all the application server instances in the cluster.
When the Enterprise Profile is Used
The Security Store parameter value for the enterprise profile is NSS, which stands for Network Security Services. In an NSS security infrastructure there is no JKS keystore and so there is no default GlassFish keystore.
For the most part, the steps to enable the GlassFish v2
application server as an SSL server are the same when the
enterprise profile is used as when the developer profile is used.
However there are two differences. The first difference pertains
to the first step of the process. Because there is no JKS
keystore, you start the process with an empty keystore
(
keystore.jks). The second difference pertains to the last step
of the process. Instead of importing the resulting signed
certificate into the JKS keystore, you import it into the NSS
store. In other words, to enable the GlassFish v2 application
server as an SSL server, you perform the same steps as in the
When the Developer Profile is Used section, but you start with
an empty keystore, and you replace step 6 in that section with
the following steps:
Export the private key for the server certificate from the keystore in Privacy Enhanced Mail (PEM) format by issuing the following command:
keyexport.bat -keyfile serverkey.pem
-keystore keystore.jks -storepass changeit -alias s1as
The command invokes the
keyexport utility. You can find the
keyexport in the
keyexport package, which you can download
from the XWSS downloads page in Project Metro
In response you will be prompted for the keystore password. The keystore password is the same as the key password, so you can reply by simply pressing the return key.
This creates a
serverkey.pem file which contains the server
private key under the markers -----BEGIN PRIVATE KEY-----
and -----END PRIVATE KEY-----.
Append the signed certificate reply from the CA, including
the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----
markers, to the
servercert.pem file. Append the reply just
below the END PRIVATE KEY marker.
Convert the
serverkey.pem file into a PKCS#12 file (a file
with a
.pfx extension). "PKCS" refers to a group of public
key cryptography standards devised and published by RSA
Security. PKCS#12 defines a file format commonly used to
store private keys with accompanying public key
certificates, protected with a password-based symmetric key.
There are various tools you can use to convert the
serverkey.pem file into a PKCS#12 file. One of them is the
openssl tool. Here is the command to convert the file using
openss1:
openssl pkcs12 -export -in serverkey.pem -out s1as.pfx
In response, you will be prompted for the export password. Enter a password such as "changeit" or the GlassFish master password.
The
s1as.pfx file will now contain the required signed
server certificate and the private key.
Delete the original
s1as self-signed entry, if it exists, by
issuing the following command:
certutil -D -n s1as -d $AS_NSS_DB
Use the
pk12util utility to import the new
s1as.pfx file into
the NSS store by issuing the following command:
pk12util -i s1as.pfx -d $AS_NSS_DB
pk12util is an NSS utility available inside the GlassFish
installation template directory for the Enterprise Profile.
The utility is used to import or export a PCKS#12 file to and
from an NSS store.
In response to the command, you will be prompted for the passwords for the NSS soft token and PKCS#12 file. Supply the appropriate passwords. You should then see the following message indicating that the import was successful:
pk12util: PKCS12 IMPORT SUCCESSFUL
There are two other cases to consider:
The application server profile is the enterprise profile and
the server key pair is already in a PKCS#12 file. If there is
already an entry in the store with alias
s1as, all you have to
do is perform step 4 as described in "When the Enterprise
Profile is Used" to delete the original entry:
certutil -D -n s1as -d $AS_NSS_DB
Then perform step 5 to import the new
s1as.pfx file into the
NSS store:
pk12util -i s1as.pfx -d $AS_NSS_DB
If there is no entry in the store with alias
s1as, simply
perform step 5.
The application server profile is the developer profile and
the server key pair is already in a PKCS#12 file. In this
case, all you need to do is perform step 5 as described in
When the Enterprise Profile is Used to delete the original
s1as entry. Then use the
pkcs12import utility to import the
PCKS#12 file into the GlassFish keystore:
pkcs12import.sh -file s1as.pfx -alias s1as
-keystore keystore.jks -storepass changeit
-pass <exp_password>
where
<exp_password> is the password that was used when the
PKCS#12 file was exported, for example, changeit.
You can find the
pkcs12import utility in the
pkcs12import
package, which you can download from the XWSS downloads page
in Project Metro
For More Information
To learn more about SSL with GlassFish see SSL and CRL Checking with GlassFish v2.
Also see the following resources:
Kumar Jayanti is a staff engineer at Sun Microsystems and works in the Web Technologies and Standards team. In his current role, Kumar is the lead for the XML and Web Services Security implementation and has also recently taken over responsibility for the GlassFish security module. He has been involved with the web services security effort at Sun since early 2004. Kumar holds an M.Tech degree in Computer Science from IIT Mumbai, India. His areas of interest include distributed computing, CORBA, XML, web services, and security.
The Java Code to replace the original self-signed cert seems to ignore the possibility of a Cert-Chain being present in the Issued Cert. The modified code below might solve that issue.
--------------------------------------------
import java.io.*;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Collection;
public class Main {
public static void main(String[] args) throws Exception {
//args[] error checking logic omitted
//file containing signed cert reply from CA
String csrReplyFromCA = args[0];
//Path to GlassFish keystore.jks
String keystoreLocation = args[1];
//Password for GlassFish keystore.jks
String keystorePassword = args[2];
//The keyalias to be replaced : s1as in our example
String selfSignedKeyEntry = args[3];
//create the signed Cert
//Certificate cert = null;
Collection<? extends Certificate> certs = null;
FileInputStream fis =
new FileInputStream(csrReplyFromCA);
CertificateFactory cf =
CertificateFactory.getInstance("X.509");
//cert = cf.generateCertificate(fis);
certs = cf.generateCertificates(fis);
//now replace the original entry
char[] passwordChars =
keystorePassword.toCharArray();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream(keystoreLocation),
passwordChars);
Key key = keystore.getKey(selfSignedKeyEntry,
passwordChars);
Certificate[] certchain = certs.toArray(new Certificate[0]);
keystore.setKeyEntry(selfSignedKeyEntry, key,
//passwordChars, (new Certificate[]{cert}));
passwordChars,certchain);
keystore.store(new FileOutputStream(
keystoreLocation), passwordChars);
}
}
---------------------------------------
Posted by Kumar Jayanti on January 15, 2008 at 11:20 PM PST #
Great article. Thanks!
GlassFish has multiple profiles. The default ones are the ones that you mention.
Posted by Kedar Mhaswade on March 21, 2008 at 06:38 AM PDT #
I'm having some problems with the pkcs12import utility. It doesn't seem to be able to find my keystore file. See the trace below (running form the domain config directory):
#: ./pkcs12import.sh -file <CA file> -alias s1as -keystore keystore.jks
does not existt location keystore.jks
Any ideas?
Posted by JoeG on July 25, 2008 at 07:29 AM PDT #
Can you please run it as follows and see if it helps :
java -classpath <location of >/pkcs12import.jar com.sun.xml.wss.tools.PKCS12Import -file <CA file> -alias s1as -keystore keystore.jks
Thanks
Posted by kumar jayanti on July 28, 2008 at 12:03 AM PDT #
That seems to have done the trick. Thanks
Posted by JoeG on July 31, 2008 at 02:57 AM PDT #
The first step should be "Make a backup copy of keystore.jks before doing anything." After following all the steps under the Developer Profile, attempting to restart Glassfish resulted in a nasty:
java.security.UnrecoverableKeyExceptionCannot recover key
No clue what that means, but all of the steps I followed completed successfully with no warnings or errors. We have a local CA here that we trust, maybe it didn't like our local CA signing the cert?
Posted by Jason on September 24, 2008 at 06:04 AM PDT #
For, java.security.UnrecoverableKeyExceptionCannot recover key
Can you send me the complete stack trace.
Yes backing up the original keystore.jks is definitely a good idea.
But did you change the keystore password by any chance to be different from the GF master password ?.
Posted by kumar on October 06, 2008 at 10:12 AM PDT #
Well, I bought a Thawte certificate recently to suport payment on my site and I would say that this article really helped me.
But, keytool -import -v -alias s1as -file s1as.cert
-keystore keystore.jks -storepass <store_passwd>
is probably not the right command... I would suggest using
keytool -import -trustcacerts -alias s1as -keystore keystore.jks -file s1as.cert
Which in my case was the only one working...
Posted by Stéphane on October 27, 2008 at 10:09 AM PDT #
yes the option -trustcacerts is required. Thanks for the correction.
Posted by 192.18.43.225 on February 10, 2009 at 11:35 PM PST # | http://blogs.sun.com/enterprisetechtips/entry/using_ssl_with_glassfish_v2 | crawl-002 | refinedweb | 2,017 | 56.86 |
In a functional programming style modification of variables is not allowed. The big question that comes to a programmer is what type of data structures can be used with such restrictions. It is important to understand how such data structures are defined and the manner in which they are operated on. It is the objective of this tutorial to demonstrate how we operate on data structures without modifying them.
The first key point to note when using functional data structures is that only pure functions operate on them. Pure functions are not allowed to modify any of their input. For example consider an expression like x + y. This expression results in a new value without modifying anything. By considering the addition expression one may think programming functionally requires copying of variables. However this is not the case. In the following sections we are going to look at available data structures that support a functional programming style.
The singly linked list is one of the functional data structures used widely and easy to understand. When doing linear traversal the data structure offers excellent performance but random access does not give similar performance. For a good understanding of linked lists we need to discuss the basics first. If our list contains type T elements then Nil defines an empty list. Consider a case where we have a l T-list with e as an element, the definition Cons(e,l) refers to a T-list containing a first element e with l as the other members of the list. To make this clear let us give some examples of defining singly linked lists of type Int
- Cons (1,Nil) is a list containing only element 1
- Cons (1, Cons(3, Cons(5, Nil))) is a list with elements [1, 3, 5].
To define a string list we would do it as shown below
Cons(“one”, Cons(“two” Cons(“three”, Nil)))
The generalization that we can make from the examples above is that in a T-list Cons (e,l) e is known as the head and l is the tail. An empty list lacks a head and a tail. For example in the string list created previously the element one is the head and the element three is the tail.
Armed with the basics we are now ready to look at implementation of linked lists. Consider the code shown below.
package fpinscala.datastructures sealed trait List[+A] case object Nil extends List[Nothing] case class Cons[+A](head: A, tail: List[A]) extends List[A] object List { def addition(ints: List[Int]): Int = ints match { case Nil => 0 case Cons(h,t) => h + addition(t) } def multiplication(ds: List[Double]): Double = ds match { case Nil => 1.0 case Cons(0.0, _) => 0.0 case Cons(h,t) => x * product(xs) } def apply[A](as: A*): List[A] = if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*)) val cons1 = Cons(1, Cons(2, Cons(3, Nil))) val cons2 = List(1,2,3) val bothCons = sum(cons1) }
In the code above we have declared a sealed trait. A trait is similar to a class but the two have their differences. For a review of traits please refer to the Scala overview tutorial. By adding sealed keyword before trait we signal that the trait code file contains all implementations of trait. In the addition function we have an empty list and another list that contains two elements. Earlier on we noted that when programming we do not need to copy data when we need to perform an operation. Consider the definition val cons1 = Cons(1, Cons(2, Cons(3, Nil))), if we need to add an element to cons1 we return a new list consNew = (8, cons1). When we return the new list it contains elements in the previous list but the previous list was copied or accessed. This kind of referencing is referred to as data sharing.
Another data structure that fits well with functional programming style is banker’s queue. Scala offers the mutable and immutable queue but in this tutorial our interest is in immutable. The queue relies on a list pair [L, R] where L represents the first queue portion while R is the rear portion. In the L list the first element corresponds to the head of the tail while in the R list the first element corresponds to last element of the queue. This design gives an efficient lookup usually O(1). Items are added into R and removed from L. the queue provides the enqueue method to add items into the queue and the dequeue method to remove items.
Consider the queue implemented below that is used to dequeue and print elements. This is a simple implementation that does an ordered traversal.
import scala.collection.immutable.Queue def printNumbers[A](p:Queue[A]) { if(!p.isEmpty) { p.dequeue match { case (x,xs) => println(x.toString) printNumbers(xs) case _ => println("End") } } }
Another data structure that is of benefit to a functional programmer is a binary search tree (BST). Scala offers the mutable and immutable BST but our interest is immutable. In a BST for every node the values in the left sub tree are less than the node and the values in the right sub tree are greater than the node. Every node in the tree is required to have a unique value. From the previous two points observe traversing a BST is like using a sorting algorithm.
In this tutorial we began by noting that functional data structures restrict changes in place. We set out to discuss some of the data structures available. We discussed the singly linked list and demonstrated how it is used without making copies of data. We also looked at a banker’s queue and discussed how to add and remove items. Lastly we briefly looked at binary search trees but we did not demonstrate their use due to space limitation.
The post Learn How To Use Functional Data Structures In Scala appeared first on Eduonix.com | Blog. | https://laptrinhx.com/2033005/ | CC-MAIN-2021-39 | refinedweb | 1,009 | 63.49 |
Nintendo President Satoru Iwata let it slipped that Nintendo’s next generation gaming console, the Revolution, would cost less than $300 USD. What would be an ideal price for that console? I say that around $199 USD ($235 CAD), I wouldn’t think twice about it a just get it.
Ideal Nintendo Revolution priceDecember 30, 2005
More on DVD’sDecember 29, 2005
This article was linked on Digg.
Disney is one of the worst offenders, so much so that I have actually returned a Disney disc after finding out that there was no way my kids could watch the movie until seven, SEVEN ads played first.
And the MPAA wonders why people get their movies on BitTorrent in DivX format? Let me explain: you double click on the file and the movie immediatly starts. That’s it! The people who rip DVD’s and put them online, even though they are breaking the law, have more respect for me than the movie industry does!
Can we go back to VHS now?December 27, 2005
For Christmas, I recieved season 4 of 24. Can anyone explain why I can’t fast forward the Interpol and FBI messages? Or the “this does not reflect the views of Fox” screen? And why do I have to listen to an animation before I can select what I want to do with the DVD? Why do they block the very useful Menu button?
Technology is supposed to make things faster and more enjoyable for us, not force us to watch what the MPAA decides we need to watch.
Update: I found this nice quote on a website:
“True greatness is measured by how much freedom you give to others, not by how much you can coerce others to do what you want.” –Larry Wall, Creator of Perl
I think it’s perfect for the DVD situation.
Google doesn’t work anymore hereDecember 25, 2005
I wonder if it’s related to me previous post, but for the last 12 hours, maybe even more, I haven’t been able to access Google or Gmail. I asked a few people on IRC, and they have no problem. What’s going on? Is Videotron broken on Christmas?
In the mean time, if you want to send me an email, post a comment below until this situation is fixed.
Update: seems fixed. Must’ve been a DNS issue.
Gmail’s spam filter is broken?December 22, 2005
Is Gmail’s spam filter broken or downgraded? Before this week, one or maybe two spam got into my inbox per week, the rest was correctly classified as spam, with no false positives. However, this week I’ve had 5-6 spam per day in my inbox. What’s up with that?
Rubygems installationDecember 22, 2005
Just a quick tip to people installing RubyGems: make sure you don’t have a .gemrc nor $GEM_PATH or $GEM_HOME defined. I was trying to install it on my new Ubuntu installation last night, and I kept having problems. Finally, I renamed .gemrc to gemrc and unset $GEM_PATH and the installation worked flawlessly afterwards. I don’t know if it’s a know issue, but that’s how I fixed the problem.
Building a Digg clone in 100 lines of Common LispDecember 21, 2005
When Reddit, a Digg-like social news site, announced that it was migrating from Common Lisp to Python, there was a bit of an uproar on comp.lang.lisp. People did not understand why they were moving away from a better language (I won’t cite the reasons here, you can find that yourself.) Creating a Reddit-like site has since become a hobby for Common Lispers who are convinced of the superiority of their language.
Here is a screencast of a guy writing a Reddit clone in about 20 minutes and 100 lines of code. Very interesting. It would’ve been even more interesting if he’d used an actual database, but that could easily be the subject of a subsequent screencast. Lispers often talk about CLSQL, this might be a chance to see what that project is about.
Also, it seems a lot of Lisp developers are Mac coders: all the Lisp screencasts I’ve seen have been on Macs, and two of them are using LispWorks.
color or colour in Ruby? Both!December 21, 2005
My friend Theo has a small rant regarding methods with the word “color” in them: because he is so used to writing colour, he needs to backspace to correct himself:
Every time I’m forced to type “color” I wince. It’s spelled “colour”. Just because it isn’t explicitly pronounced does not make it right to drop it. Sadly though color will probably eventually kill out colour and posts like these will be laughed at for looking ridiculous. Maybe I am. But at least I’m not ridiculos or ridiculis.
Well, fear not Theo, for Ruby is an extremely reflective and introspective language! Here is a method to alias instance and class methods so that you can use either “color” or “colour”:
def alias_color_to_colour classes = [] ObjectSpace.each_object { |o| classes << o if o.class == Class } classes.each { |c| c.instance_methods(false).each { |im| c.class_eval("alias #{im.gsub("color", "colour")} #{im}") if im =~ /color/i } c.methods(false).each { |cm| c.instance_eval("alias #{cm.gsub("color", "colour")} #{cm}") if cm =~ /color/i } } end
Si if you have a class with a random_color method, you can now use random_colour. Not entirely tested, so the code may have bugs and I wouldn’t recommend using it in production code, but how cool is it that you can do that? Ask a Java programmer to accomplish the same thing just for fun!
Quick comment by the way: why does ObjectSpace only support each_object? Why aren’t #select, #collect, #reject, #detect implemented too?
Weak vs strong typingDecember 20, 2005
Read this nice article for a nice comparaison of weak and strong typing. He seems to freely interchange static and strong typing and dynamic and weak typing, but I can forgive that, because the article is pretty good.
Summary: dynamic typing makes most tasks faster and easier to code, but being able to optionally declare types for variables and/or functions would be a nice addition. He mentions that Common Lisp does it, and Perl 6 will too.
Why RoR instead of ASP.Net?December 20, 2005
One question, though. Have you checked out the latest ASP.NET and Visual Studio 2005? If so, what about it turns you to Rails?
I can’t answer for Phil, but my reasons would be: cost, productivity, open source and fun. | http://gnuvince.wordpress.com/2005/12/ | crawl-002 | refinedweb | 1,109 | 73.68 |
Congratulations to the WiX team on hitting the Beta milestone for WiX 3.0! Now that code and schema changes are on the ramp down on the project, I thought it was the time to update my Paraffin tool to offer full support for WiX 3.0. If you didn’t see the original set of blog posts I wrote about Paraffin (Part 1, Part 2, and Part 3.) the quick answer is that manually creating and hand maintaining your WiX fragments is enough to make any developer cry. I wrote Paraffin with the idea that it would do the hard work of creating and maintaining those fragments easier. With any tool of this sort, I have to caution you that you can completely break Windows Installer’s component rules if you are not paying attention. This is especially true if you remove files from your install.
The 3.0 release of Paraffin creates WiX 3.0 compatible fragments only. I bumped the version number up to match the version of WiX it supports. (If you are still using WiX 2.0, keep using the 1.04 version.) However, if you have WiX 2.0 files you created with Paraffin 1.04, Paraffin 3.0 will properly update those files to WiX 3.0. If you haven’t guessed, I’m just now upgrading my installations to WiX 3.0 so had a ton of files to convert. It took a little extra effort since the WiX XML namespace changed between 2.0 and 3.0, but it was definitely worth it to make the transition easy for me. All the fragments that Paraffin 3.0 creates are fully WiXCop compliant except for the whitespace checks.
I love the idea of the automated analysis that WiXCop does and really thank the team for the tool. The problem is that the whitespace analysis errors are so voluminous on every file you check you can’t see the real errors it’s reporting. To turn off those errors, here’s my settings file, NoSpaceErrors.xml.
<Settings>
<IgnoreErrors>
<Test Id=”WhitespacePrecedingNodeWrong” />
<Test Id=”WhitespacePrecedingEndElementWrong” />
</IgnoreErrors>
<ErrorsAsWarnings/>
<ExemptFiles/>
</Settings>
When you run WiXCop, add the –set1NoSpaceErrors.xml to the command line and you won’t be bothered by those errors ever again.
In addition to creating new WiX 3.0 files and updating WiX 2.0 Paraffin file to WiX 3.0, I also check all File elements and if the file is a .DLL, .EXE, or .OCX, I add the Checksum=’yes’ element. To see an example installer using Paraffin, the .\ParaffinInstaller directory in the ZIP file is a WiX 3.0 project for installing Paraffin. I’ve created fragments for the source, installer, and binary directories.
Grab Paraffin 3.0 here and as always, let me know if you have any feature requests or find any bugs! | http://www.wintellect.com/devcenter/jrobbins/paraffin-3-0-now-with-full-wix-3-0-support | CC-MAIN-2015-18 | refinedweb | 475 | 76.93 |
*
to Dave Lander,Marilyn de Queiroz
mike hengst
Ranch Hand
Joined: Oct 19, 2002
Posts: 43
posted
Oct 26, 2002 10:39:00
0
I wanted to show you two the code you helped me build. There is only one problem left. I have to increment the student number for use on the displayGrades() method. I thought what I had in the constructor and get,set methods would work, but it is just not working. Anyways here is all the code so you can(maybe) see what I have going on. Thanks for all the help!
import java.text.*; /** * This class is to be used in the GradePoint class * *@author Michael Hengst *@created October 25, 2002 */ public class Student { private static char[] letterGrades = {'F', 'D', 'C', 'B', 'A'}; private static int[] points = {0, 1, 2, 3, 4}; private static int studentNumber = 100; char[] studentGrades = new char[5]; int[] gradePoints = new int[5]; int stuNo; /** * Constructor for the Student object * sets the student number for the class */ public Student() { getStudentNumber(); } /** * Sets the grade attribute of the Student object * *@param index The index of the new grade value *@param letterGrade The new grade value */ public void setGrade(int index, char letterGrade) { for(int i = 0; i < studentGrades.length; ++i) { if(letterGrade == letterGrades[i]) { studentGrades[index] = letterGrades[i]; gradePoints[index] = points[i]; break; } } } /** * Sets the studentNumber attribute of the Student object */ public void setStudentNumber(int studentNumber) { stuNo = studentNumber + 1; } /** * Gets the studentNumber attribute of the Student object * *@return The studentNumber value */ public int getStudentNumber() { return stuNo; } /** * This method formats the data to be displayed * *@return the return is the appended String sb */ public String toString() { System.out.println(" "); DecimalFormat df = new DecimalFormat("0.00"); StringBuffer sb = new StringBuffer("Student " + stuNo); sb.append("\n Grades "); sb.append("\n Course 1: " + studentGrades[0] + " points " + df.format(gradePoints[0])); sb.append("\n Course 2: " + studentGrades[1] + " points " + df.format(gradePoints[1])); sb.append("\n Course 3: " + studentGrades[2] + " points " + df.format(gradePoints[2])); sb.append("\n Course 4: " + studentGrades[3] + " points " + df.format(gradePoints[3])); sb.append("\n Course 5: " + studentGrades[4] + " points " + df.format(gradePoints[4])); sb.append("\n GPA = " + df.format(calcGPA())); return sb.toString(); } /** * This method calculates the GPA based on the array values * *@return The unformatted GPA */ public double calcGPA() { double total = 0; int z = 0; for(int i = 0; i < 5; ++i) { z = gradePoints[i]; total = total + z; } return (total / 5); } } /** * Description of the Class * *@author Michael Hengst *@created October 25, 2002 */ public class GradePoint { private final static char[] VALIDGRADES = {'F', 'D', 'C', 'B', 'A'}; private final static int[] POINTS = {0, 1, 2, 3, 4}; Student[] students = new Student[2]; private boolean valid; /** * Gets the studentData attribute of the GradePoint object * *@return The studentData value *@exception Exception Description of Exception */ public char getStudentData() throws Exception { char grade = ' '; double points = 0; int index = 0; valid = false; for(int i = 0; i < 2; ++i) { for(int x = 0; x < 5; ++x) { System.out.println("Please enter grade for student " + (i + 1)); grade = (char)System.in.read(); System.in.read(); System.in.read(); System.out.println("You entered " + grade); for(int y = 0; y < 5; ++y) { valid = false; if(grade == VALIDGRADES[y]) { valid = true; index = x; break; } } if(valid) { students[i].setGrade(index, grade); } else { --x; System.out.println("Invalid grade entered"); } } } return grade; } /** * This method place the grade entered into the array * and is called from main in TestGradePoint *@exception Exception Description of Exception */ public void assignGrades() throws Exception { // for(int x = 0;x < 2;++x) // { instantiateStudents(); getStudentData(); // } displayGrades(); } /** * Instantiating the student */ public void instantiateStudents() { for(int i = 0; i < 2; ++i) { students[i] = new Student(); } } /** * Method to display the grades and GPA * *@return Description of the Returned Value */ public String displayGrades() { String x = new String(); for(int i = 0; i < 2; ++i) { System.out.println(students[i].toString()); } return x; } }
The GradePoint class is called from a class named TestGradePoint which is not included.
Thank you Oh Lord<br />For the white blind light<br />A city rises from the sea<br />I had a splitting headache<br />from which the future's made<br />--morrisson
Ron Newman
Ranch Hand
Joined: Jun 06, 2002
Posts: 1056
posted
Oct 26, 2002 11:01:00
0
The static variable studentNumber is never incremented or otherwise changed after you initialize it to 100.
Also, one of your methods has a parameter named studentNumber, which will hide the static variable of the same name. This is legal but is bad practice.
Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Bill Liteplo
Ranch Hand
Joined: Oct 16, 2002
Posts: 88
posted
Oct 26, 2002 11:10:00
0
Mike,
This code looks [BOLD]a lot[/BOLD] better than your last post. Way to go!
I notice that your included code doesn't ever set the studentNumber, even though your comments for the constructor mention it.
I think the constructor is a fine place for it.
However, I would avoid having an argument named studentNumber in the method setStudentNumber and also a static variable studentNumber (same name).
I'm guessing you want the student number to start at 100 (maybe 101?), and go up statically from there. Fine.
Then redo setStudentNumber to read
private void setStudentNumber() { stuNo = studentNumber; studentNumber++; }
or reverse the two lines in the method to start at 101.
Then just invoke setStudentNumber() in your constructor, and never again. (Notice I made the method private.) If you want the student Number to be determined by something other than a static incrementing variable, then you may need to change this.
Bill
mike hengst
Ranch Hand
Joined: Oct 19, 2002
Posts: 43
posted
Oct 26, 2002 11:17:00
0
Eureka!!!It works. Thanks for the pointer
stuNo = studentNumber;
studentNumber++;
I got it to work with
stuNo = studentNumber++;
after I realized that I had to call setStudentNumber from the constructor. Once I realized my error it worked. Then I come back to javaranch to find out that was correct. This is beautiful. I spent
alot
of time on this and learned quite a bit. Although I am happy to be done with this I am still way behind on other things. So before I ramble too long. Thanks for all the help everybody. I am sure I will be back later on, maybe I can even answer questions one day.
[ October 26, 2002: Message edited by: mike hengst ]
It is sorta covered in the
JavaRanch Style Guide
.
subject: to Dave Lander,Marilyn de Queiroz
Similar Threads
Why can student[x] be resolved?
not a statement
array variables out of scope-why?
arrays
Error in calculation
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/392717/java/java/Dave-Lander-Marilyn-de-Queiroz | CC-MAIN-2014-52 | refinedweb | 1,115 | 60.95 |
C++ File Input/Output
Binary I/O
Binary I/O is accomplished through two member functions: read and write. The syntax for read is:
in_file.read(data_ptr, size);
- data_ptr
- Pointer to a place to put the data.
- size
- Number of bytes to be read.
struct {
int width;
int height;
} rectangle;
in_file.read(static_cast<char *>(&rectangle), sizeof(rectangle));
if (in_file.bad( )) {
cerr << "Unable to read rectangle\n";
exit (8);
}
if (in_file.gcount( ) != sizeof(rectangle)) {
cerr << "Error: Unable to read full rectangle\n";
cerr << "I/O error of EOF encountered\n";
}
In this example you are reading in the structure rectangle. The
& operator makes
rectangle into a pointer. The cast static_cast<char *> is needed since read wants a character array. The sizeof operator is used to determine how many bytes to read as well as to check that
read was successful.
The member function write has a calling sequence similar to read:
out_file.write(data_ptr, size);
Buffering Problems
Buffered I/O does not write immediately to the file. Instead, the data is kept in a buffer until there is enough for a big write, or until the buffer is flushed. The following program is designed to print a progress message as each section is finished.
std::cout << "Starting";
do_step_1( );
std::cout << "Step 1 complete";
do_step_2( );
std::cout << "Step 2 complete";
do_step_3( );
std::cout << "Step 3 complete\n";
Instead of writing the messages as each step completes, std::cout puts them in a buffer. Only after the program is finished does the buffer get flushed, and all the messages come spilling out at once.
The I/O manipulator std::flush forces the flushing of the buffers. Properly written, the above example should be:
std::cout << "Starting" << std::flush;
do_step_1( );
std::cout << "Step 1 complete" << std::flush;
do_step_2( );
std::cout << "Step 2 complete" << std::flush;
do_step_3( );
std::cout << "Step 3 complete\n" << std::flush;
Because each output statement ends with a std::flush, the output is displayed immediately. This means that our progress messages come out on time.
TIP: The C++ I/O classes buffer all output. Output to std::cout and std::cerr is line buffered. In other words, each newline forces a buffer flush. Also, C++ is smart enough to know that std::cout and std::cerr are related to std::cin and will automatically flush these two output streams just before reading std::cin. This makes it possible to write prompts without having to worry about buffering:
NOTE: std::cout << "Enter a value: "; // Note: No flush std::cin >> value;
Unbuffered I/O
In buffered I/O, data is buffered and then sent to the file. In unbuffered I/O, the data is immediately sent to the file.
If you drop a number of paperclips on the floor, you can pick them up in buffered or unbuffered mode. In buffered mode, you use your right hand to pick up a paper clip and transfer it to your left hand. The process is repeated until your left hand is full, then you dump a handful of paperclips into the box on your desk.
In unbuffered mode, you pick up a paperclip and dump it.
Back to the paperclip example--if you were picking up small items like paperclips, you would probably use a left-hand buffer. But if you were picking up cannon balls (which are much larger), no buffer would be used.
The open system call is used for opening an unbuffered file. The macro definitions used by this call differ from system to system. Since the examples have to work for both Unix and MS-DOS/Windows, conditional compilation
(
#ifdef
/
#endif
) is used to bring in the correct files:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef _ _MSDOS_ _ // If we are MS-DOS
#include <io.h> // Get the MS-DOS include file for raw I/O
#else /* _ _MSDOS_ _ */
#include <unistd.h> // Get the Unix include file for raw I/O
#endif /* _ _MSDOS_ _ */
The syntax for an
open call is:
int file_descriptor = open(name, flags); // Existing file
file_descriptor = open(name, flags, mode);//New file
- file_descriptor
- An integer that is used to identify the file for the read, write, and close calls. If
file_descriptoris less than 0, an error occurred.
- name
- Name of the file.
- flags
- Defined in the fcntl.h header file. Open flags are described in Table 16-6.
- mode
- Protection mode for the file. Normally this is 0644.
For example, to open the existing file data.txt in text mode for reading, you use the following:
data_fd = open("data.txt", O_RDONLY);
The next example shows how to create a file called output.dat for writing only:
out_fd = open("output.dat", O_CREAT|O_WRONLY, 0666);
Notice that you combined flags using the OR (|) operator. This is a quick and easy way of merging multiple flags.
When any program is initially run, three files are already opened. These are described in Table 16-7.
The format of the read call is:
read_size = read(file_descriptor, buffer, size);
- read_size
- The actual number of bytes read. A 0 indicates end-of-file, and a negative number indicates an error.
- file_descriptor
- File descriptor of an open file.
- buffer
- Pointer to a place to put the data that is read from the file.
- size
- Size of the data to be read. This is the size of the request. The actual number of bytes read may be less than this. (For example, you may run out of data.)
The format of a write call is:
write_size = write(file_descriptor, buffer, size);
- write_size
- Actual number of bytes written. A negative number indicates an error.
- file_descriptor
- File descriptor of an open file.
- buffer
- Pointer to the data to be written.
- size
- Size of the data to be written. The system will try to write this many bytes, but if the device is full or there is some other problem, a smaller number of bytes may be written.
Finally, the close call closes the file:
flag = close(file_descriptor)
- flag
- 0 for success, negative for error.
- file_descriptor
- File descriptor of an open file.
Example 16-5 copies a file. Unbuffered I/O is used because of the large buffer size. It makes no sense to use buffered I/O to read 1K of data into a buffer (using an std::ifstream) and then transfer it into a 16K buffer.
Example 16-5: copy2/copy2.cpp
/****************************************
* copy -- copy one file to another. *
* *
* Usage *
* copy <from> <to> *
* *
* <from> -- the file to copy from *
* <to> -- the file to copy into *
****************************************/
#include <iostream>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef _ _WIN32_ _ // if we are Windows32
#include <io.h> // Get the Windows32 include file for raw i/o
#else /* _ _WIN32_ _ */
#include <unistd.h> // Get the Unix include file for raw i/o
#endif /* _ _WIN32_ _ */
const int BUFFER_SIZE = (16 * 1024); // use 16k buffers
int main(int argc, char *argv[])
{
char buffer[BUFFER_SIZE]; // buffer for data
int in_file; // input file descriptor
int out_file; // output file descriptor
int read_size; // number of bytes on last read
if (argc != 3) {
std::cerr << "Error:Wrong number of arguments\n";
std::cerr << "Usage is: copy <from> <to>\n";
exit(8);
}
in_file = open(argv[1], O_RDONLY);
if (in_file < 0) {
std::cerr << "Error:Unable to open " << argv[1] << '\n';
exit(8);
}
out_file = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0666);
if (out_file < 0) {
std::cerr << "Error:Unable to open " << argv[2] << '\n';
exit(8);
}
while (true) {
read_size = read(in_file, buffer, sizeof(buffer));
if (read_size == 0)
break; // end of file
if (read_size < 0) {
std::cerr << "Error:Read error\n";
exit(8);
}
write(out_file, buffer, (unsigned int) read_size);
}
close(in_file);
close(out_file);
return (0);
}
Several things should be noted about this program. First of all, the buffer size is defined as a constant, so it is easily modified. Rather than have to remember that 16K is 16,384, the programmer used the expression
(16 * 1024). This form of the constant is obviously 16K.
If the user improperly uses the program, an error message results. To help the user get it right, the message tells how to use the program.
You may not read a full buffer for the last read. That is why read_size is used to determine the number of bytes to write.
Page 5 of<< | https://www.developer.com/net/cplus/article.php/10919_2119781_5/C-File-InputOutput.htm | CC-MAIN-2018-22 | refinedweb | 1,379 | 66.03 |
Is there any additional libraries or flags that have to put in the make file or whatever else needed to make this very basic C functionality to work?
I tried both
#include "stdio.h"
#include <stdio.h>
But always got:
D:\WICED-Studio-6.2\SDK\20719-B1_Bluetooth\WICED/../apps/w191/spp1/spp.c:517: undefined reference to `sprintf'
Tracking it back to declaration in stdio.h I've got:
int _EXFUN(sprintf, (char *__restrict, const char *__restrict, ...)
_ATTRIBUTE ((__format__ (__printf__, 2, 3))));
Thanks
P.S. Same story is and with stdlib.h and malloc() and free():
D:\WICED-Studio-6.2\SDK\20719-B1_Bluetooth\WICED/../apps/w191/spp1/spp.c:520: undefined reference to `malloc'
D:\WICED-Studio-6.2\SDK\20719-B1_Bluetooth\WICED/../apps/w191/spp1/spp.c:521: undefined reference to `free'
Hi StN._1917156,
The sprintf, malloc and free functions are not implemented in CYW20719B1 firmware.
However, instead of sprintf, you can use snprintf in following way:
char name[20];
int a=1;
snprintf(name, sizeof(name), "Try-%d", a);
WICED_BT_TRACE ("%s", name);
For malloc, free operations, you can use WICED APIs. Please refer wiced_memory.h for more details. | https://community.cypress.com/thread/48514 | CC-MAIN-2020-45 | refinedweb | 193 | 53.78 |
The Top 5 IPython Commands to Boost your Productivity in Python
The IPython shell is a powerful expansion pack to Python, the world’s most popular programming language. It accelerates developer productivity by adding a slew of features to Python’s standard execution environment, including auto-completion, command history, file writes, and more.
One of IPython’s most celebrated features is magic commands, which are small Python scripts that perform various utility operations. In this article, we’ll dive into the five magic commands you need to know to get up and running with IPython. Your productivity will thank you!
Last Updated July 2022
Analyze data quickly and easily with Python’s powerful pandas library! All datasets included — beginners welcome! | By Boris PaskhaverExplore Course
What is IPython?
Let’s review the basics.
The code that we write is called source code. Source code exists for the programmer’s benefit—our computer’s hardware does not recognize its constructs. The Python interpreter is the software that translates our source code into a language that the computer can understand.
A shell is a program that allows a user to interact with an operating system or an application. It consists of a prompt (often called the command line) in which we enter and execute text instructions, also known as shell commands.
If you have Python installed on your computer, you can search for the IDLE program in your installation directory.
Figure 1: The IDLE program in a Python 3.9 installation directory
IDLE is a shell built specifically for the Python language. Inside the application, we can execute lines of Python code. The interpreter immediately translates the code and outputs the result.
Figure 2: Example of the IDLE Shell running on macOS
IPython (Interactive Python) is an expanded version of the IDLE shell. Fernando Pérez, a physicist, developed IPython and released the program in 2001. IPython should not be confused with different versions of Python. It’s more of an expansion pack that increases our productivity with the core language.
In our previous article, we introduced the Jupyter Notebook development environment, a fantastic option for both practicing and writing Python code. A Jupyter Notebook consists of code cells. When we execute a cell, we immediately see its output directly below the code. You’d be surprised how quickly you can pick up a new technology by simply typing commands and seeing their results.
A Jupyter Notebook uses the IPython shell under its hood. That means we get all the enhancements of IPython inside a beautiful graphical interface. Let’s spin up a fresh Jupyter Notebook and see it in action.
Magic commands
An IPython magic command is a code shortcut. It’s a small chunk of code we add to our program that uses one of IPython’s special features.
Magic commands begin with a % prefix or a %% prefix. When we use a single percentage sign, IPython applies the command to the line of code that follows it. When we use two percentage signs, IPython applies the command to the entire Jupyter Notebook cell.
Let’s dive into five important commands to enhance your productivity in IPython.
1. The %run magic command
Say we have a Python script file with some business logic. Let’s call our file multiply.py.
def multiply(a, b): return a * b
Instead of copying and pasting the file’s contents into a cell, we could use the %run magic command to open the Python file and run its code directly in Jupyter Notebook.
In [1] %run multiply.py
IPython executes the file and imports the Python program’s names (variables, functions, classes, etc.) into the Notebook. We can now invoke the multiply function inside a cell.
In [2] calculation = multiply(3, 5) calculation Out [2] 15
2. The %timeit magic Command
The %timeit magic command calculates the average execution speed of an expression. To filter out abnormalities, it takes the measurements over many different executions.
The following example times the execution of a factorial function. IPython executes the line of code one million times!
In [3] def factorial(number): if number <= 1: return 1 return number * factorial(number - 1) In [4] %timeit factorial(10) 1.46 µs ± 49.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
3. The %who_ls magic command
Do you ever forget whether a name exists in your Python program? Or maybe you imported a library or a module from the Python standard library but forgot the alias you assigned to it? The %who_ls magic command lists all names defined in the Jupyter Notebook: variables, modules, functions, classes, and more. It’s a great tool to use after you restart a Notebook and need to verify which cells to re-execute.
In [5] import datetime as dt import pandas as pd In [6] %who_ls ['calculation', 'dt', 'factorial', 'multiply', 'pd']
4. The %writefile magic command
Jupyter Notebook is a fantastic tool for experimentation, but you’ll likely need to save your code to a plain .py file if you need to run Python manually, such as on a server.
The %%write magic command writes a Notebook cell’s contents to a file. Write the file name right after the command.
In [7] %%writefile business_logic.py def my_business_idea(): for i in range(10): print("Make money") my_business_idea() Out [7] Writing business_logic.py
Be careful with this magic command. If you execute the cell again, IPython will overwrite the existing business_logic.py file.
To append content to the end of an existing file, add the -a (append) flag.
In [8] %%writefile -a business_logic.py def another_business_idea(): for i in range(10): print("Make even more money") another_business_idea() Out [8] Appending to business_logic.py
5. The %quickref Magic Command
Curious about what else IPython can do? Execute %quickref to reveal a cheat sheet with a complete list of magic commands and their descriptions.
In [9] %quickref
Figure 3: A sample of magic commands from the %quickref modal
Summary
We’ve only scratched the surface of what the IPython shell is capable of. The latest version has more than 100 magic commands for you to explore. For a more extensive IPython introduction, head to its official website. I hope it helps you be more productive in your day-to-day Python activities!
Recommended Articles
What is the Best Python IDE?
How to Become a Data Scientist from Scratch
R vs Python – Which is best?
Top courses in Python
Python students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.
Courses by Boris Paskhaver
Courses by Boris Paskhaver | https://blog.udemy.com/python-commands/ | CC-MAIN-2022-33 | refinedweb | 1,112 | 66.44 |
No, I didn't see this message, but I think we arrived at the same conclusion. I think the solution is just to calculate the width and height in the same way in both places (copy_to_bbox and the Qt blitting code in Python). We can't change bbox.bounds, since many other parts of the code rely on that calculation being in pure floating point. But there's only two places (in Qt and Qt4) that rely on the rounding behavior of copy_to_bbox, and IMHO, the way it does the rounding is the sanest way given that the edges must be integer-aligned.
I've committed these changes in r4995.
Cheers,
Mike
Darren Dale wrote:
···
Hi Mike,
On Monday 10 March 2008 08:24:27 am you wrote:
Sorry, I didn't see this latest e-mail before I replied before. I see
the shearing now that I've adjusted window size. Maybe it could be
related to the fact that width != span? Anyway, I'll investigated
further and get back.
Thanks for having a look. But before you dig to deep, did you see my last post to this thread?:
-----
I think this problem is due to a loss of precision in _backend_agg's copy_from_bbox. That method takes a bbox with double precision as input, and constructs a rect with ints as input:
agg::rect_i rect((int)l, height - (int)t, (int)r, height - (int)b);
A rendering buffer is created with a width based on that rect. Half of the time, the width of that buffer disagrees with the width reported by the original bbox. For example, I can kludge the bbox width so it agrees with the output of copy_from_bbox:
l, b, w, h = bbox.bounds
r = int(l+w)
w_mod = r-int(l)
I can use w_mod instead of w as a workaround for the blitting issue I reported, but I wonder if there might be a better solution?
------
Darren Dale wrote:
On Friday 07 March 2008 4:58:03 pm Darren Dale wrote:
I am having some trouble with the Cursor widget with the qt4agg backend.
Here is a short script which works with the gtkagg backend with useblit
either true or false:
----------
from matplotlib import rcParams
rcParams['backend']='gtkagg'
from pylab import *
from matplotlib.widgets import Cursor
t = arange(0.0, 1.0, 0.01)
s = sin(2*2*pi*t)
ax = subplot(111)
cursor = Cursor(ax, useblit=True)
ax.plot(t, s, 'o')
axis([0,1,-1,1])
show()
------------
If I use the qt4agg backend, with useblit False, the cursor lines do not
render. If useblit is True, the lines render but the pixmap inside the
axes is sheared. I've been looking at the backend_qt4agg code, the
widgets.Cursor code, and the working animation_blit_qt4 example, but I'm
stuck. Does anyone have any ideas?
Here is an additional wrinkle, sometimes the pixmap is sheared, and
sometimes it is not. The behavior seems to shift back and forth when I
change the horizontal size of the figure window, bu I don't see a pattern
emerging that would explain why: 556-559 pixels wide is sheared, 560-564
looks ok, 565-567 is sheared, 568 is normal, 569 and 570 are sheared,
etc. The
animation_blit_qt4 demo also has the same problem, depending on the
horizontal size. So confusing.
--
Michael Droettboom
Science Software Branch
Operations and Engineering Division
Space Telescope Science Institute
Operated by AURA for NASA | https://discourse.matplotlib.org/t/question-about-transforms/8730 | CC-MAIN-2022-21 | refinedweb | 573 | 70.84 |
I want the string start with "shivam " (without quote).my regular expression is :
(?=shivam\s)\w+
shivam gupta
gupta
shivam gupta
If you want to learn a bit of a regex use
import re s = "shivam gupta" m = re.match(r"shivam\s+(\w+)$", s) if m: # Check if the pattern matches the string print(m.group(1)) # print only Group 1 contents
See the Python demo
The
re.match method only searches at the start of string, so
shivam is looked for at the start. Then
\s+ matches one or more whitespaces, and finally,
(\w+)$ matches and captures into Group 1 one or more word chars and then the end of string
$.
The Group 1 contents are accessed via
.group(1) of the match object (here,
m).
However, you can use string methods and a split operation here:
s = "shivam gupta" if s.startswith("shivam "): print(s.split()[1]) # or even print(s[s.find(" "):]) | https://codedump.io/share/SjiYIUIAVKGM/1/need-help-in-the-regular-expression-start-with-string-with-space | CC-MAIN-2016-50 | refinedweb | 156 | 75.91 |
What's A Tuple?
First we have to look at a core data type in F# called a tuple. Tuples are a way of grouping other data types. Tuples are immutable data structures that can have any number of items. (By immutable, I mean that it can't be "mutated" or that there are no property setters, only property getters, like a C# String object.)
The number of items we declare in a tuple probably should be kept to a manageable number (more than seven items starts to get really confusing, at least for my human brain, and I would probably consider a different data structure if I needed more than 7 or so type "slots").
Tuples are declared by surrounding a comma separated list of values in parenthesis. The data type that results are the types separated by the '*' character. Here is a tuple of an int and a string:
> (4, "Hello World");;val it : int * string = (4, "Hello World")
If we look at it from a C# perspective this is the type of structure we have with a two-member tuple:
public class Tuple<T, U>{ public Tuple(T pValue1, U pValue2) { m_value1 = pValue1; m_value2 = pValue2; } private T m_value1; private U m_value2; public T Value1 { get { return m_value1; } } public U Value2 { get { return m_value2; } }}
And we would declare an instance in C# (.NET 3.5) as follows:
Tuple<Int32, String> value = new Tuple<int, string>( 4, "Hello World");
Of course we could have a structure with many more items
> (4, '4', "4", (fun x->x+4), 4.0, (fun x->x+ 4.0));;val it : int * char * string * (int -> int) * float * (float -> float)= (4, '4', "4", <fun:it@5>, 4.0, <fun:it@5_1>)
Which would be a pretty messy generic data type in C#:
public class Tuple<T, U, V, W, X, Y>{ public Tuple(T pValue1, U pValue2, V pValue3, W pValue4, X pValue5, Y pValue6) { m_value1 = pValue1; m_value2 = pValue2; m_value3 = pValue3; m_value4 = pValue4; m_value5 = pValue5; m_value6 = pValue6; } private T m_value1; private U m_value2; private V m_value3; private W m_value4; private X m_value5; private Y m_value6; public T Value1 { get { return m_value1; } } public U Value2 { get { return m_value2; } } public V Value3 { get { return m_value3; } } public W Value4 { get { return m_value4; } } public X Value5 { get { return m_value5; } } public Y Value6 { get { return m_value6; } }}
And the declaration alone would be almost unmanagable in C#:
Tuple<Int32, Char, String, Func<Int32, Int32>, Double, Func<Double, Double>> value2 = new Tuple<int, char, string, Func<int, int>, double, Func<double, double>>( 4, '4', "4", x => x + 4, 4.0, x => x + 4.0);
One of the really nice things about F# is how concise the code is because everything is generic by default and we only declare the type if we want to (which we'll get to in a bit).
Binding Part 1.
In F# we can assign a value to a placeholder through binding. The syntax for binding is first using the "let" keyword, followed by the placeholder name followed by an equal sign and then the value.
Here we are binding the value 4 to the placeholder x. Notice the response telling us that the type of x is an integer.
> let x = 4;;val x : int
This will look very familiar to C# programmers. (Note: If we use the F# interactive window, the placeholders will last until we close our Studio process or type "#quit" to reset our F# interactive session)
Now, wherever we want to use the integer "4", we can substitute our placeholder "x" as in the following example:
> x + 1;;val it : int = 5
We can also bind to functions as in the following example:
> let f = (fun x -> x + 1);;val f : int -> int> f;;val it : (int -> int) = <fun:clo@0>> f x;;val it : int = 5
Binding Part II.
Ok, now is where we depart from what we know in C# and can see why we don't consider F# binding the equivalent of assigning a variable some value in C#.
Remember tuples? Well, we can bind to multiple placeholders using a tuple as follows:
> let (m,n) = (4, "Hello World");;val m : intval n : string
Notice that the placeholders "m" and "n" did not have to be declared before our functions but we have bound the value "4" to our placeholder "m" and the value "Hello World" to our placeholder "n" anyways.
> m;;val it : int = 4> n;;val it : string = "Hello World"
Because functions are first class citizens of F#, we also have a more concise way to bind to F# function placeholders. This is how we can declare a function with one input parameter "x"
> f x = x + 1;;val it : bool = true
Notice how the type is inferred for us and we don't have to explicitly declare it as we would have had to do in C#:
> f;;val it : (int -> int) = <fun:clo@0_1>
In an earlier article I mentioned that sometimes we have to help F# figure out the type. Let's say we wanted to build a function that added something to the end of a string:
> f x = x + " World";; f x = x + " World";; ----------^^^^^^^^^stdin(25,10): error: FS0001: This expression has type stringbut is here used with type intstopped due to error
Right now I can already hear you thinking "Dude! I meant for you to use a string…"
Here, we get an error because the F# compiler sees a type conflict between our operation '+' which is an "int -> int" and the string " World". Remember the syntax we saw earlier when we saw the type of the placeholder?
We can use the same syntax to constrain our type so our new string appending function will work by placing a colon after our input parameter followed by the type we want:
> let f x:string = x + " World";;val f : string -> string
And now we can happily continue on our way with our new append function working as expected:
> f "Hello";;val it : string = "Hello World"
We can also either pass tuples to functions as well as using a list of parameters. For example, we can declare a function with two inputs as follows:
> let f (x:string) y = x + " " + y;;val f : string -> string -> string
Notice how if we give the compiler a little bit of a hint with "x", it can figure out what type "y" is supposed to be.
And we can call our function as follows:
> f "Hello" "World";;val it : string = "Hello World"
Similarly, we can pass a tuple as input to a function:
let f ((x:string), y) = x + " " + y;;val f : string * string -> string
Notice how our function type is now "string * string -> string" which has a tuple ("string * string") instead of our previous "string -> string -> string" signature. The function with a tupled argument ("string * string -> string") would be considered a function in non-curried form, while the function with no tuples ("string -> string -> string") would be considered to be curried. In a future article I'll discuss how to move back and forth between the curried and non-curried formats and the reasons and drawbacks for doing this.
This should give you a bit of an idea of how F# binding is a bit different from C# variable assignments.
We can get values out of a tuple by defining a simple function:
> let first (x,y) = x;;val first : 'a * 'b -> 'a
Our function type ('a * 'b -> 'a) says that if we have a tuple with something of type a in the first slot and something of type b in the second slot, we'll get something of type a as an output.
> first ("Hello", "World");;val it : string = "Hello"
And you can see it works as expected.
Binding Part III
We can also have nested "let"s, but first let's turn on the light syntax option by typing "#light;;" in F# Interactive. This will allow us to use an even more concise syntax where whitespace matters and makes for easier readin' code.
> #light;;
Here's another feature of the "let" binding keyword. We can "nest" lets to build more complex functions as in the following example.
> let f x:int = let square m = m * m x |> square |> square;;val f : int -> int> f 2;;val it : int = 16
(If the forward pipe operator "|>" is throwing you for a loop, check out my earlier article on the operator.)
Let's walk through what we have.
We have obviously built a function that takes and int and returns an int (we know that from the signature displayed which is "int -> int"). This function has an internal function we bound to "square" that multiplies and integer with itself. Notice how the compiler figures out the type of "square" from our single constraint on "x".
let f x:float = let square m = m * x |> square |> square;;
As an aside.. . we could have done the same thing and constrained the type to float and the compiler figures out what we mean:
> let f x:float = let square m = m * m x |> square |> square;;val f : float -> float
But I digress.
Our inner function is scoped to the outer. Meaning that all the inner "lets" are only available to the outer "let", so "square" will not be defined outside the context of our function "f" and can't bee seen by F# interactive:
> square;; square;; ^^^^^^^stdin(67,0): error: FS0039: The value or constructor 'square' is not defined.stopped due to error
The last line of our function defines the output where we specify to take the input value "x" and push the result through our "square" function and take the result of that and push it through our "square" function again:
let f x:float = let square m = m * m x |> square |> square;;
And, as always, we terminate our instructions with the double semi-colon:
If we look at a similar function in C# it would look like this:
public Int32 f(Int32 x){ Func<Int32, Int32> square = m => m * m; return square(square(x));}
If you are having problems with the lambda syntax, check out my earlier article on anonymous delegates and lambda syntax in C#. This is a good illustration of how C# is becoming more "functional" and (to me) another good reason to wrap my mind around F# in order to take full advantage of all the opportunities available with the new C# functional language features.
We can have nested lets that go as many levels deep as we want. If you want do drive yourself a little crazier, here's a little F# puzzle… see if you can figure out what this function will do:
let f x:int = let g y = let h z = z * z (h y) * (h y) g x;;
I'll leave this up to you (if you are really curious maybe it will get you to download F# and give it a shot). After you figure it out, you'll see how flexible and expressive F# is which give us as developers many ways to solve problems (some more convoluted than others).
That's about it for this F# binding and tuple tour, I hope you enjoyed it. I'll be back soon to look at more F# language features.
Until next time,Happy coding | http://www.c-sharpcorner.com/UploadFile/rmcochran/fsharp-tuples-and-binding-and-more-binding/ | CC-MAIN-2014-15 | refinedweb | 1,886 | 57.03 |
You might be wondering why should I do this when Sharepoint can do this already though User Profile Synchronization, well that is partly true because in Sharepoint Foundation 2013 and even on 2010 it is not available. Having said that there will always be a way and that’s what are trying to achieve on this article, to synchronize Active Directory Information with Sharepoint User Profile by doing some coding. This can be achieved in multiple ways, you can do Powershell, you can create a Sharepoint feature or develop a standalone application, we will do the latter as for me its more flexible and manageable.
Now lets start but before doing so lets lay out some ground work and give some explanation on how to we go about on this one.
Did you know that Sharpoint stores user profiles in a list as well? It’s sort of hidden but in case you did not know you can locate it at:
http://{YourSharepointUrl}/_catalogs/users/simple.aspx
And it will look like this
But something is different, unlike normal lists it does not give you the tabs to manipulate the list or its view but that does not stop us in doing so as it is just a web part in a page, having said that you can still edit the page.
and edit the web part
then edit the current view
and there you are
free to change how your view looks like.
That does not end there, you can also edit the list by adding column of your choice. It’s not straightforward though as you need to know your List Id by checking it in the URL while you in the view property page.
Now copy that and combine it with the URL below to view your List Properties
http://{YourSharepointURL}/_layouts/listedit.aspx?List={YourListIdHere}
And whoalla! you can now edit your list.
So now lets say we add Description, Office and Company which is not there by default.
Once saved you can now see it on the view.
Although it shows the proper name on the view the field names might not be the same, so if you run the codes below and investigate what the field names are it would look like this.
So make sure you map it to the correct Sharepoint and Active Directory fields/columns, for our example it will be like this.
Now lets start coding. What we will do first is a simple listing of all Site Users, to do that copy and paste the codes below.
private static void GetAllSiteUsers() { // Starting with ClientContext, the constructor requires a URL to the server running SharePoint. var sharepointContext = new ClientContext(""); //Get Web Context var sharepointList = sharepointContext.Web.SiteUserInfoList; var camlQuery = new CamlQuery(); var userList = sharepointList.GetItems(camlQuery); sharepointContext.Load(userList); sharepointContext.ExecuteQuery(); foreach (ListItem user in userList) { } }
Run it and lets see your first data, the first user that will appear is the one who set up your Sharepoint Instance, which means you are safe to assume that it is a real user.
Place a breakpoint and investigate your results. If you notice when you run the code it will give you all the List Items and in our example we have 2399 items, we need to filter it further because the whole list contains Users, Active Directory Groups and Sharepoint Groups. What we need to sync only are the Users so we need to identify which are the users somehow.
After looking at my example I have two Field values that I can use, first is the ContentTypeId which if you further investigate is common for all Users other entities have a different ContentTypeId. Another is the Name where all users will have a Claims Authentication Code and Domain Prefix ie i:0#.w|YourDomainUserName other entities such as group is prefixed as c:0+.w| followed by and SID.
Now we know how to filter lets apply that to the CAML Query and further filter our results.
private static void GetAllSiteUsersFilteredByType() { // Starting with ClientContext, the constructor requires a URL to the server running SharePoint. var sharepointContext = new ClientContext(""); //Get Web Context var sharepointList = sharepointContext.Web.SiteUserInfoList; //Prefix for all users string userType = "i:0#.w|"; var camlQuery = new CamlQuery(); camlQuery.ViewXml = @"<FieldRef Name='Name' />" + userType + "</Value></Contains></Where></Query></View>"; var userList = sharepointList.GetItems(camlQuery); sharepointContext.Load(userList); sharepointContext.ExecuteQuery(); foreach (ListItem user in userList) { } }
Now you will see we have lesser result count as we only get the real users.
Let’s do the synchronization Part!
By now you know how to get all that users now we need to search for the same user in Active Directory get its information and overwrite the ones in Sharepoint. The codes below is complete but I just created them in one class as a console application, it’s up to you how you want to use them.
The codes also takes into consideration that service user you will be using have full rights on Active Directory and is in the Site Collection Administrators Group on Sharepoint.
using Microsoft.SharePoint.Client; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; namespace Sharepoint_User_and_Active_Directory_Sync { static class Program { //If you're using claims authentication, this defines a user on a domain const stringThe username to get</param> /// <returns>Returns the UserPrincipal Object</returns> private static UserPrincipal GetUser(string userName) { try { var principalContext = GetPrincipalContext(); var userPrincipal = UserPrincipal.FindByIdentity(principalContext, userName); return userPrincipal; } catch { return null; } } /// <summary> /// Gets the AD Attributes not represented in UserPrincipal /// </summary> /// <param name="principal">The User Principal Object</param> /// <param name="property">The property name you want to retrieve</param> /// <returns></returns> private static string GetProperty(this UserPrincipal principal, string property) { var directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry; if (directoryEntry.Properties.Contains(property)) { return directoryEntry.Properties[property].Value.ToString(); } else { //Property not exisiting return empty strung return string.Empty; } } } }
That’s it, now you can sync your Active Directory User Information to your Sharepoint Foundation 2013 regularly.
Hi please suggest do i need below line if i create a timer service?
sharepointContext.Credentials = new System.Net.NetworkCredential(adUserName, adPassword, adDomain);
And anything else i need to change to work it in a timer service?
Kind regards
Atiq zia
You can remove that but you need to make sure the service account have access to the list mentioned above
Thank you so much for the reply and its solve my issue. Now i need your suggestion does your Getuser code will work if there are multiple OU and also an OU further can have sub level OU. I actually need code which should work in finding user regardless how much OU and sub level OU are created in AD.
Best regards
Atiq zia
That OU there is the root meaning anything below it will be searched, so I suggest in your case use the topmost one.
Can you send me source files please, if possible.
I’m new to SharePoint, and not understanding how to write the code and where?
Which project type should I use in visual studio?
You can choose whatever you want depending on how you would run it, for me I just created a console application that is called by Task Scheduler on predefined schedule.
Thanks Raymund…
Nice tutorial hovewer I am not sure where and how to code. What application are you using?. What programing language and program are you using?
Other that that it is very good and simple to follow article.
I am using Visual Studio and the language is C#
Hi man, nice post about this. I was trying to search some informations about the sync using Sharepoint 2013 at a server stand alone.
Would you tell me if as possible, sync the AD to the Sharepoint Foundations 2013 in this kind of server? Or using your post methods looks more safety?
Thanks in advance,
Best regards,
I used the code on Sharepoint Foundation 2013 as the full version you dont need to do this
All right, thanks for you reply. So can I import all my Farm to the AD, to do this sync?
Thanks again,
Best regards,
This is for AD to Sharepoint Sync
Thanks mann !!!
Hi, i’m new in SP.
It’s not clear for me, how you connected VS(Console C#) with SP2013, can you explain your steps with VS? advance thanks!
Thanks you for posting this article. I am going to work on it today and I am sure it will prove very useful.
I have a quick question about one of the screen captures though. I don’t know where to go to generate the screen of Attribute-Syntax-Count that listed the active directory properties. It’s the right portion of the screen shot under the caption:
.”
[Path: CN=Raymund Macaaaly]
I have dug around in Microsoft’s “Active Directory Users and Computers” and can’t find this sort of attribute breakdown.
Its called ADExplorer, you can download them free at Technet.
Here is the link
Nice post. Helped me to add additional columns in the User Information List
Thanks a lot, Raymund
Hi, Raymund. I see that this will allow me to sync profile data on sharepoint foundation from AD, which is one of the things I wanted to do, so thanks a lot. One thing I don’t know how to do is to display the user profile to the user. If I click “my settings”, nothing happnes. Is it possible to call the data from sharepoint foundation’s user profile for the specific logged user?
I’m completely new to coding, but I slogged through to running the first code (as a .cs file) I’d substituted our sharepoint foundation 2013 URL. The error I got was: SiteUsers.cs(1,21): error CS0116: A namespace cannot directly contain members such as fields or methods. The build failed.
Obviously, the .cs doesn’t contain namespaces. I’m confused! | http://www.macaalay.com/2014/03/27/synchronize-active-directory-information-with-sharepoint-foundation-2013-user-profiles/ | CC-MAIN-2021-04 | refinedweb | 1,651 | 62.78 |
27 September 2012 05:00 [Source: ICIS news]
Correction: Removes reference to conflicting crude movement in naphtha, benzene and toluene snapshots. A corrected version follows with recasts.
SINGAPORE (ICIS)--Here is Thursday’s midday ?xml:namespace>
CRUDE: WTI Nov $90.05/bbl, up 7 cents; BRENT Nov $109.97/bbl, down 7 cents
Crude futures were range-bound in the morning, because downside pressure from concerns over the eurozone debt and the weak global economy was offset by an unexpected fall in
NAPHTHA: $953.50-956.50/tonne CFR
Open-spec prices for the first-half November contracts rose in the morning on active spot buying from South Korean and Taiwanese cracker operators.
BENZENE: $1,215-1,230/tonne FOB
A deal was concluded for a December-loading lot at $1,190/tonne FOB
TOLUENE: $1,165-1,180/tonne FOB
First-half November-loading lots were offered at $1,178-1,180/tonne FOB
ETHYLENE: $1,300-1,350/tonne CFR NE Asia, stable
Selling notions for selected northeast Asia-origin cargoes for November loading were heard at $1,270/tonne FOB NE Asia, which is equivalent to $1,340-1,370/tonne CFR NE Asia, because of a supplier’s reduced output. Discussions remained subdued.
PROPYLENE: $1,380-1,390/tonne CFR NE Asia, stable
Selling ideas for second-half October/early November cargoes were at around $1,390/tonne CFR NE Asia against buying ideas capped at $1,360-1,380 | http://www.icis.com/Articles/2012/09/27/9598982/corrected-noon-snapshot-asia-markets-summary.html | CC-MAIN-2015-11 | refinedweb | 244 | 52.29 |
OkHttp 3.x Change Log¶
Version 3.14.9.14.8¶
2020-04-28
- Fix: Don’t crash on Java 8u252 which introduces an API previously found only on Java 9 and above. See Jetty’s overview of the API change and its consequences.
Version 3.14.7¶
2020-02-24
- Fix: Don’t crash on Android 11 due to use of restricted methods. This prevents a crash with the exception, “Expected Android API level 21+ but was 29”.
Version 3.14.6¶
2020-01-11
- Fix: Don’t crash if the connection is closed when sending a degraded ping. This fixes a regression that was introduced in OkHttp 3.14.5.
Version 3.14.14.14.
Fix: Recover gracefully when a coalesced connection immediately goes unhealthy.
Version 3.14.2¶
2019-05-19
Fix: Lock in a route when recovering from an HTTP/2 connection error. We had a bug where two calls that failed at the same time could cause OkHttp to crash with a
NoSuchElementExceptioninstead of the expected
IOException.
Fix: Don’t crash with a
NullPointerExceptionwhen formatting an error message describing a truncated response from an HTTPS proxy.
Version 3.14.1¶
2019-04-10
Fix: Don’t crash when an interceptor retries when there are no more routes. This was an edge-case regression introduced with the events cleanup in 3.14.0.
Fix: Provide actionable advice when the exchange is non-null. Prior to 3.14, OkHttp would silently leak connections when an interceptor retries without closing the response body. With 3.14 we detect this problem but the exception was not helpful.
Version 3.14.0¶
2019-03-14
This release deletes the long-deprecated
OkUrlFactoryand
OkApacheClientAPIs. These facades hide OkHttp’s implementation behind another client’s API. If you still need this please copy and paste ObsoleteUrlFactory.java or ObsoleteApacheClient.java into your project.
OkHttp now supports duplex calls over HTTP/2. With normal HTTP calls the request must finish before the response starts. With duplex, request and response bodies are transmitted simultaneously. This can be used to implement interactive conversations within a single HTTP call.
Create duplex calls by overriding the new
RequestBody.isDuplex()method to return true. This simple option dramatically changes the behavior of the request body and of the entire call.
The
RequestBody.writeTo()method may now retain a reference to the provided sink and hand it off to another thread to write to it after
writeToreturns.
The
EventListenermay now see requests and responses interleaved in ways not previously permitted. For example, a listener may receive
responseHeadersStart()followed by
requestBodyEnd(), both on the same call. Such events may be triggered by different threads even for a single call.
Interceptors that rewrite or replace the request body may now inadvertently interfere with duplex request bodies. Such interceptors should check
RequestBody.isDuplex()and avoid accessing the request body when it is.
Duplex calls require HTTP/2. If HTTP/1 is established instead the duplex call will fail. The most common use of duplex calls is gRPC.
New: Prevent OkHttp from retransmitting a request body by overriding
RequestBody.isOneShot(). This is most useful when writing the request body is destructive.
New: We’ve added
requestFailed()and
responseFailed()methods to
EventListener. These are called instead of
requestBodyEnd()and
responseBodyEnd()in some failure situations. They may also be fired in cases where no event was published previously. In this release we did an internal rewrite of our event code to fix problems where events were lost or unbalanced.
Fix: Don’t leak a connection when a call is canceled immediately preceding the
onFailure()callback.
Fix: Apply call timeouts when connecting duplex calls, web sockets, and server-sent events. Once the streams are established no further timeout is enforced.
Fix: Retain the
Routewhen a connection is reused on a redirect or other follow-up. This was causing some
Authenticatorcalls to see a null route when non-null was expected.
Fix: Use the correct key size in the name of
TLS_AES_128_CCM_8_SHA256which is a TLS 1.3 cipher suite. We accidentally specified a key size of 256, preventing that cipher suite from being selected for any TLS handshakes. We didn’t notice because this cipher suite isn’t supported on Android, Java, or Conscrypt.
We removed this cipher suite and
TLS_AES_128_CCM_SHA256from the restricted, modern, and compatible sets of cipher suites. These two cipher suites aren’t enabled by default in either Firefox or Chrome.
See our TLS Configuration History tracker for a log of all changes to OkHttp’s default TLS options.
New: Upgrade to Conscrypt 2.0.0. OkHttp works with other versions of Conscrypt but this is the version we’re testing against.
implementation("org.conscrypt:conscrypt-openjdk-uber:2.0.0")
New: Update the embedded public suffixes list.
Version 3.13.1¶
2019-02-05
- Fix: Don’t crash when using a custom
X509TrustManageror
SSLSocketon Android. When we removed obsolete code for Android 4.4 we inadvertently also removed support for custom subclasses. We’ve restored that support!
Version 3.13.0¶
2019-02-04
This release bumps our minimum requirements to Java 8+ or Android 5+. Cutting off old devices is a serious change and we don’t do it lightly! This post explains why we’re doing this and how to upgrade.
The OkHttp 3.12.x branch will be our long-term branch for Android 2.3+ (API level 9+) and Java 7+. These platforms lack support for TLS 1.2 and should not be used. But because upgrading is difficult we will backport critical fixes to the 3.12.x branch through December 31, 2021. (This commitment was originally through December 31, 2020; we have since extended it.)
TLSv1 and TLSv1.1 are no longer enabled by default. Major web browsers are working towards removing these versions altogether in early 2020. If your servers aren’t ready yet you can configure OkHttp 3.13 to allow TLSv1 and TLSv1.1 connections:
OkHttpClient client = new OkHttpClient.Builder() .connectionSpecs(Arrays.asList(ConnectionSpec.COMPATIBLE_TLS)) .build();
New: You can now access HTTP trailers with
Response.trailers(). This method may only be called after the entire HTTP response body has been read.
New: Upgrade to Okio 1.17.3. If you’re on Kotlin-friendly Okio 2.x this release requires 2.2.2 or newer.
implementation("com.squareup.okio:okio:1.17.3")
Fix: Don’t miss cancels when sending HTTP/2 request headers.
- Fix: Don’t miss whole operation timeouts when calls redirect.
- Fix: Don’t leak connections if web sockets have malformed responses or if
onOpen()throws.
- Fix: Don’t retry when request bodies fail due to
FileNotFoundException.
- Fix: Don’t crash when URLs have IPv4-mapped IPv6 addresses.
- Fix: Don’t crash when building
HandshakeCertificateson Android API 28.
- Fix: Permit multipart file names to contain non-ASCII characters.
- New: API to get MockWebServer’s dispatcher.
- New: API to access headers as
java.time.Instant.
- New: Fail fast if a
SSLSocketFactoryis used as a
SocketFactory.
- New: Log the TLS handshake in
LoggingEventListener.
Version 3.12.12.12.11¶
2020-04-28
- Fix: Don’t crash on Java 8u252 which introduces an API previously found only on Java 9 and above. See Jetty’s overview of the API change and its consequences.
Version 3.12.10¶
2020-02-29
- Fix: Don’t crash on Android 4.1 when detecting methods that became restricted in Android 11. Supporting a full decade of Android releases on our 3.12.x branch is tricky!
Version 3.12.9¶
2020-02-24
- Fix: Don’t crash on Android 11 due to use of restricted methods. This prevents a crash with the exception, “Expected Android API level 21+ but was 29”.
Version 3.12.8¶
2020-01-11
- Fix: Don’t crash if the connection is closed when sending a degraded ping. This fixes a regression that was introduced in OkHttp 3.12.7.
Version 3.12.12.12 3.12.4¶
2019-09-04
- Fix: Don’t crash looking up an absent class on certain buggy Android 4.x devices.
Version 3.12.3¶
2019-05-07
- Fix: Permit multipart file names to contain non-ASCII characters.
- Fix: Retain the
Routewhen a connection is reused on a redirect or other follow-up. This was causing some
Authenticatorcalls to see a null route when non-null was expected.
Version 3.12.2¶
2019-03-14
- Fix: Don’t crash if the HTTPS server returns no certificates in the TLS handshake.
- Fix: Don’t leak a connection when a call is canceled immediately preceding the
onFailure()callback.
Version 3.12.1¶
2018-12-23
- Fix: Remove overlapping
package-info.java. This caused issues with some build tools.
Version 3.12.0¶
2018-11-16
OkHttp now supports TLS 1.3. This requires either Conscrypt or Java 11+.
Proxy authenticators are now asked for preemptive authentication. OkHttp will now request authentication credentials before creating TLS tunnels through HTTP proxies (HTTP
CONNECT). Authenticators should identify preemptive authentications by the presence of a challenge whose scheme is “OkHttp-Preemptive”.
OkHttp now offers full-operation timeouts. This sets a limit on how long the entire call may take and covers resolving DNS, connecting, writing the request body, server processing, and reading the full response body. If a call requires redirects or retries all must complete within one timeout period.
Use
OkHttpClient.Builder.callTimeout()to specify the default duration and
Call.timeout()to specify the timeout of an individual call.
New: Return values and fields are now non-null unless otherwise annotated.
- New:
LoggingEventListenermakes it easy to get basic visibility into a call’s performance. This class is in the
logging-interceptorartifact.
- New:
Headers.Builder.addUnsafeNonAscii()allows non-ASCII values to be added without an immediate exception.
- New: Headers can be redacted in
HttpLoggingInterceptor.
- New:
Headers.Buildernow accepts dates.
- New: OkHttp now accepts
java.time.Durationfor timeouts on Java 8+ and Android 26+.
- New:
Challengeincludes all authentication parameters.
New: Upgrade to BouncyCastle 1.60, Conscrypt 1.4.0, and Okio 1.15.0. We don’t yet require Kotlin-friendly Okio 2.x but OkHttp works fine with that series.
implementation("org.bouncycastle:bcprov-jdk15on:1.60") implementation("org.conscrypt:conscrypt-openjdk-uber:1.4.0") implementation("com.squareup.okio:okio:1.15.0")
Fix: Handle dispatcher executor shutdowns gracefully. When there aren’t any threads to carry a call its callback now gets a
RejectedExecutionException.
- Fix: Don’t permanently cache responses with
Cache-Control: immutable. We misunderstood the original
immutableproposal!
- Fix: Change
Authenticator‘s
Routeparameter to be nullable. This was marked as non-null but could be called with null in some cases.
- Fix: Don’t create malformed URLs when
MockWebServeris reached via an IPv6 address.
- Fix: Don’t crash if the system default authenticator is null.
- Fix: Don’t crash generating elliptic curve certificates on Android.
- Fix: Don’t crash doing platform detection on RoboVM.
- Fix: Don’t leak socket connections when web socket upgrades fail.
Version 3.11.0¶
2018-07-12
OkHttp’s new okhttp-tls submodule tames HTTPS and TLS.
HeldCertificateis a TLS certificate and its private key. Generate a certificate with its builder then use it to sign another certificate or perform a TLS handshake. The
certificatePem()method encodes the certificate in the familiar PEM format (
--- BEGIN CERTIFICATE ---); the
privateKeyPkcs8Pem()does likewise for the private key.
HandshakeCertificatesholds the TLS certificates required for a TLS handshake. On the server it keeps your
HeldCertificateand its chain. On the client it keeps the root certificates that are trusted to sign a server’s certificate chain.
HandshakeCertificatesalso works with mutual TLS where these roles are reversed.
These classes make it possible to enable HTTPS in MockWebServer in just a few lines of code.
OkHttp now supports prior knowledge cleartext HTTP/2. Enable this by setting
Protocol.H2_PRIOR_KNOWLEDGEas the lone protocol on an
OkHttpClient.Builder. This mode only supports
http:URLs and is best suited in closed environments where HTTPS is inappropriate.
New:
HttpUrl.get(String)is an alternative to
HttpUrl.parse(String)that throws an exception when the URL is malformed instead of returning null. Use this to avoid checking for null in situations where the input is known to be well-formed. We’ve also added
MediaType.get(String)which is an exception-throwing alternative to
MediaType.parse(String).
- New: The
EventListenerAPI previewed in OkHttp 3.9 has graduated to a stable API. Use this interface to track metrics and monitor HTTP requests’ size and duration.
- New:
okhttp-dnsoverhttpsis an experimental API for doing DNS queries over HTTPS. Using HTTPS for DNS offers better security and potentially better performance. This feature is a preview: the API is subject to change.
- New:
okhttp-sseis an early preview of Server-Sent Events (SSE). This feature is incomplete and is only suitable for experimental use.
- New: MockWebServer now supports client authentication (mutual TLS). Call
requestClientAuth()to permit an optional client certificate or
requireClientAuth()to require one.
- New:
RecordedRequest.getHandshake()returns the HTTPS handshake of a request sent to
MockWebServer.
- Fix: Honor the
MockResponseheader delay in MockWebServer.
- Fix: Don’t release HTTP/2 connections that have multiple canceled calls. We had a bug where canceling calls would cause the shared HTTP/2 connection to be unnecessarily released. This harmed connection reuse.
- Fix: Ensure canceled and discarded HTTP/2 data is not permanently counted against the limited flow control window. We had a few bugs where window size accounting was broken when streams were canceled or reset.
- Fix: Recover gracefully if the TLS session returns an unexpected version (
NONE) or cipher suite (
SSL_NULL_WITH_NULL_NULL).
- Fix: Don’t change Conscrypt configuration globally. We migrated from a process-wide setting to configuring only OkHttp’s TLS sockets.
- Fix: Prefer TLSv1.2 where it is available. On certain older platforms it is necessary to opt-in to TLSv1.2.
- New:
Request.tag()permits multiple tags. Use a
Class<?>as a key to identify tags. Note that
tag()now returns null if the request has no tag. Previously this would return the request itself.
- New:
Headers.Builder.addAll(Headers).
- New:
ResponseBody.create(MediaType, ByteString).
- New: Embed R8/ProGuard rules in the jar. These will be applied automatically by R8.
- Fix: Release the connection if
Authenticatorthrows an exception.
- Fix: Change the declaration of
OkHttpClient.cache()to return a
@Nullable Cache. The return value has always been nullable but it wasn’t declared properly.
- Fix: Reverse suppression of connect exceptions. When both a call and its retry fail, we now throw the initial exception which is most likely to be actionable.
- Fix: Retain interrupted state when throwing
InterruptedIOException. A single interrupt should now be sufficient to break out an in-flight OkHttp call.
- Fix: Don’t drop a call to
EventListener.callEnd()when the response body is consumed inside an interceptor.
Version 3.10.0¶
2018-02-24
The pingInterval() feature now aggressively checks connectivity for web sockets and HTTP/2 connections.
Previously if you configured a ping interval that would cause OkHttp to send pings, but it did not track whether the reply pongs were received. With this update OkHttp requires that every ping receive a response: if it does not the connection will be closed and the listener’s
onFailure()method will be called.
Web sockets have always been had pings, but pings on HTTP/2 connections is new in this release. Pings are used for connections that are busy carrying calls and for idle connections in the connection pool. (Pings do not impact when pooled connections are evicted).
If you have a configured ping interval, you should confirm that it is long enough for a roundtrip from client to server. If your ping interval is too short, slow connections may be misinterpreted as failed connections. A ping interval of 30 seconds is reasonable for most use cases.
OkHttp now supports Conscrypt. Conscrypt is a Java Security Provider that integrates BoringSSL into the Java platform. Conscrypt supports more cipher suites than the JVM’s default provider and may also execute more efficiently.
To use it, first register a Conscrypt dependency in your build system.
OkHttp will use Conscrypt if you set the
okhttp.platformsystem property to
conscrypt.
Alternatively, OkHttp will also use Conscrypt if you install it as your preferred security provider. To do so, add the following code to execute before you create your
OkHttpClient.
Security.insertProviderAt( new org.conscrypt.OpenSSLProvider(), 1);
Conscrypt is the bundled security provider on Android so it is not necessary to configure it on that platform.
New:
HttpUrl.addQueryParameter()percent-escapes more characters. Previously several ASCII punctuation characters were not percent-escaped when used with this method. This does not impact already-encoded query parameters in APIs like
HttpUrl.parse()and
HttpUrl.Builder.addEncodedQueryParameter().
- New: CBC-mode ECDSA cipher suites have been removed from OkHttp’s default configuration:
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAand
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA. This tracks a Chromium change to remove these cipher suites because they are fragile and rarely-used.
- New: Don’t fall back to common name (CN) verification for hostnames. This behavior was deprecated with RFC 2818 in May 2000 and was recently dropped from major web browsers.
- New: Honor the
Retry-Afterresponse header. HTTP 503 (Unavailable) responses are retried automatically if this header is present and its delay is 0 seconds. HTTP 408 (Client Timeout) responses are retried automatically if the header is absent or its delay is 0 seconds.
- New: Allow request bodies for all HTTP methods except GET and HEAD.
- New: Automatic module name of
okhttp3for use with the Java Platform Module System.
- New: Log gzipped bodies when
HttpLoggingInterceptoris used as a network interceptor.
- New:
Protocol.QUICconstant. This protocol is not supported but this constant is included for completeness.
New: Upgrade to Okio 1.14.0.
<dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>1.14.0</version> </dependency> com.squareup.okio:okio:1.14.0
Fix: Handle
HTTP/1.1 100 Continuestatus lines, even on requests that did not send the
Expect: continuerequest header.
- Fix: Do not count web sockets toward the dispatcher’s per-host connection limit.
- Fix: Avoid using invalid HTTPS sessions. This prevents OkHttp from crashing with the error,
Unexpected TLS version: NONE.
- Fix: Don’t corrupt the response cache when a 304 (Not Modified) response overrides the stored “Content-Encoding” header.
- Fix: Gracefully shut down the HTTP/2 connection before it exhausts the namespace of stream IDs (~536 million streams).
- Fix: Never pass a null
Routeto
Authenticator. There was a bug where routes were omitted for eagerly-closed connections.
Version 3.9.1¶
2017-11-18
- New: Recover gracefully when Android’s DNS crashes with an unexpected
NullPointerException.
- New: Recover gracefully when Android’s socket connections crash with an unexpected
ClassCastException.
- Fix: Don’t include the URL’s fragment in
encodedQuery()when the query itself is empty.
Version 3.9.0¶
2017-09-03
Interceptors are more capable. The
Chaininterface now offers access to the call and can adjust all call timeouts. Note that this change is source-incompatible for code that implements the
Chaininterface. We don’t expect this to be a problem in practice!
OkHttp has an experimental new API for tracking metrics. The new
EventListenerAPI is designed to help developers monitor HTTP requests’ size and duration. This feature is an unstable preview: the API is subject to change, and the implementation is incomplete. This is a big new API we are eager for feedback.
New: Support ALPN via Google Play Services’ Dynamic Security Provider. This expands HTTP/2 support to older Android devices that have Google Play Services.
- New: Consider all routes when looking for candidate coalesced connections. This increases the likelihood that HTTP/2 connections will be shared.
- New: Authentication challenges and credentials now use a charset. Use this in your authenticator to support user names and passwords with non-ASCII characters.
- New: Accept a charset in
FormBody.Builder. Previously form bodies were always UTF-8.
- New: Support the
immutablecache-control directive.
- Fix: Don’t crash when an HTTP/2 call is redirected while the connection is being shut down.
- Fix: Don’t drop headers of healthy streams that raced with
GOAWAYframes. This bug would cause HTTP/2 streams to occasional hang when the connection was shutting down.
- Fix: Honor
OkHttpClient.retryOnConnectionFailure()when the response is a HTTP 408 Request Timeout. If retries are enabled, OkHttp will retry exactly once in response to a 408.
- Fix: Don’t crash when reading the empty
HEADresponse body if it specifies a
Content-Length.
- Fix: Don’t crash if the thread is interrupted while reading the public suffix database.
- Fix: Use relative resource path when loading the public suffix database. Loading the resource using a path relative to the class prevents conflicts when the OkHttp classes are relocated (shaded) by allowing multiple private copies of the database.
- Fix: Accept cookies for URLs that have an IPv6 address for a host.
- Fix: Don’t log the protocol (HTTP/1.1, h2) in HttpLoggingInterceptor if the protocol isn’t negotiated yet! Previously we’d log HTTP/1.1 by default, and this was confusing.
- Fix: Omit the message from MockWebServer’s HTTP/2
:statusheader.
- Fix: Handle ‘Expect: 100 Continue’ properly in MockWebServer.
Version 3.8.1¶
2017-06-18
- Fix: Recover gracefully from stale coalesced connections. We had a bug where connection coalescing (introduced in OkHttp 3.7.0) and stale connection recovery could interact to cause a
NoSuchElementExceptioncrash in the
RouteSelector.
Version 3.8.0¶
2017-05-13
OkHttp now uses
@Nullableto annotate all possibly-null values. We’ve added a compile-time dependency on the JSR 305 annotations. This is a: The response message is now non-null. This is the “Not Found” in the status line “HTTP 404 Not Found”. If you are building responses programmatically (with
new Response.Builder()) you must now always supply a message. An empty string
""is permitted. This value was never null on responses returned by OkHttp itself, and it was an old mistake to permit application code to omit a message.
The challenge’s scheme and realm are now non-null. If you are calling
new Challenge(scheme, realm)you must provide non-null values. These were never null in challenges created by OkHttp, but could have been null in application code that creates challenges.
New: The
TlsVersionof a
Handshakeis now non-null. If you are calling
Handshake.get()with a null TLS version, you must instead now provide a non-null
TlsVersion. Cache responses persisted prior to OkHttp 3.0 did not store a TLS version; for these unknown values the handshake is defaulted to
TlsVersion.SSL_3_0.
New: Upgrade to Okio 1.13.0.
<dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>1.13.0</version> </dependency> com.squareup.okio:okio:1.13.0
Fix: gracefully recover when Android 7.0’s sockets throw an unexpected
NullPointerException.
Version 3.7.0¶
2017-04-15
- OkHttp no longer recovers from TLS handshake failures by attempting a TLSv1 connection. The fallback was necessary for servers that implemented version negotiation incorrectly. Now that 99.99% of servers do it right this fallback is obsolete.
- Fix: Do not honor cookies set on a public domain. Previously a malicious site could inject cookies on top-level domains like
co.ukbecause our cookie parser didn’t honor the public suffix list. Alongside this fix is a new API,
HttpUrl.topPrivateDomain(), which returns the privately domain name if the URL has one.
- Fix: Change
MediaType.charset()to return null for unexpected charsets.
- Fix: Don’t skip cache invalidation if the invalidating response has no body.
- Fix: Don’t use a cryptographic random number generator for web sockets. Some Android devices implement
SecureRandomincorrectly!
- Fix: Correctly canonicalize IPv6 addresses in
HttpUrl. This prevented OkHttp from trusting HTTPS certificates issued to certain IPv6 addresses.
- Fix: Don’t reuse connections after an unsuccessful
Expect: 100-continue.
- Fix: Handle either
TLS_or
SSL_prefixes for cipher suite names. This is necessary for IBM JVMs that use the
SSL_prefix exclusively.
- Fix: Reject HTTP/2 data frames if the stream ID is 0.
New: Upgrade to Okio 1.12.0.
<dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>1.12.0</version> </dependency> com.squareup.okio:okio:1.12.0
New: Connection coalescing. OkHttp may reuse HTTP/2 connections across calls that share an IP address and HTTPS certificate, even if their domain names are different.
- New: MockWebServer’s
RecordedRequestexposes the requested
HttpUrlwith
getRequestUrl().
Version 3.6.0¶
2017-01-29
- Fix: Don’t crash with a “cache is closed” error when there is an error initializing the cache.
- Fix: Calling
disconnect()on a connecting
HttpUrlConnectioncould cause it to retry in an infinite loop! This regression was introduced in OkHttp 2.7.0.
- Fix: Drop cookies that contain ASCII NULL and other bad characters. Previously such cookies would cause OkHttp to crash when they were included in a request.
- Fix: Release duplicated multiplexed connections. If we concurrently establish connections to an HTTP/2 server, close all but the first connection.
- Fix: Fail the HTTP/2 connection if first frame isn’t
SETTINGS.
- Fix: Forbid spaces in header names.
- Fix: Don’t offer to do gzip if the request is partial.
- Fix: MockWebServer is now usable with JUnit 5. That update broke the rules.
- New: Support
Expect: 100-continueas a request header. Callers can use this header to pessimistically hold off on transmitting a request body until a server gives the go-ahead.
- New: Permit network interceptors to rewrite the host header for HTTP/2. This makes it possible to do domain fronting.
- New: charset support for
Credentials.basic().
Version 3.5.0¶
2016-11-30
Web Sockets are now a stable feature of OkHttp. Since being introduced as a beta feature in OkHttp 2.3 our web socket client has matured. Connect to a server’s web socket with
OkHttpClient.newWebSocket(), send messages with
send(), and receive messages with the
WebSocketListener.
The
okhttp-wssubmodule is no longer available and
okhttp-wsartifacts from previous releases of OkHttp are not compatible with OkHttp 3.5. When upgrading to the new package please note that the
WebSocketand
WebSocketCallclasses have been merged. Sending messages is now asynchronous and they may be enqueued before the web socket is connected.
OkHttp no longer attempts a direct connection if the system’s HTTP proxy fails. This behavior was surprising because OkHttp was disregarding the user’s specified configuration. If you need to customize proxy fallback behavior, implement your own
java.net.ProxySelector.
Fix: Support TLSv1.3 on devices that support it.
Fix: Share pooled connections across equivalent
OkHttpClientinstances. Previous releases had a bug where a shared connection pool did not guarantee shared connections in some cases.
- Fix: Prefer the server’s response body on all conditional cache misses. Previously we would return the cached response’s body if it had a newer
Last-Modifieddate.
- Fix: Update the stored timestamp on conditional cache hits.
- New: Optimized HTTP/2 request header encoding. More headers are HPACK-encoded and string literals are now Huffman-encoded.
- New: Expose
Partheaders and body in
Multipart.
New: Make
ResponseBody.string()and
ResponseBody.charStream()BOM-aware. If your HTTP response body begins with a byte order mark it will be consumed and used to select a charset for the remaining bytes. Most applications should not need a byte order mark.
New: Upgrade to Okio 1.11.0.
<dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>1.11.0</version> </dependency> com.squareup.okio:okio:1.11.0
Fix: Avoid sending empty HTTP/2 data frames when there is no request body.
- Fix: Add a leading
.for better domain matching in
JavaNetCookieJar.
- Fix: Gracefully recover from HTTP/2 connection shutdowns at start of request.
- Fix: Be lenient if a
MediaType‘s character set is
'single-quoted'.
- Fix: Allow horizontal tab characters in header values.
- Fix: When parsing HTTP authentication headers permit challenge parameters in any order.
Version 3.4.2¶
2016-11-03
- Fix: Recover gracefully when an HTTP/2 connection is shutdown. We had a bug where shutdown HTTP/2 connections were considered usable. This caused infinite loops when calls attempted to recover.
Version 3.4.1¶
2016-07-10
- Fix a major bug in encoding HTTP headers. In 3.4.0 and 3.4.0-RC1 OkHttp had an off-by-one bug in our HPACK encoder. This bug could have caused the wrong headers to be emitted after a sequence of HTTP/2 requests! Everyone who is using OkHttp 3.4.0 or 3.4.0-RC1 should upgrade for this bug fix.
Version 3.4.0¶
2016-07-08
- New: Support dynamic table size changes to HPACK Encoder.
- Fix: Use
TreeMapin
Headers.toMultimap(). This makes string lookups on the returned map case-insensitive.
- Fix: Don’t share the OkHttpClient’s
Dispatcherin
HttpURLConnection.
Version 3.4.0-RC1¶
2016-07-02
We’ve rewritten HttpURLConnection and HttpsURLConnection. Previously we shared a single HTTP engine between two frontend APIs:
HttpURLConnectionand
Call. With this release we’ve rearranged things so that the
HttpURLConnectionfrontend now delegates to the
CallAPIs internally. This has enabled substantial simplifications and optimizations in the OkHttp core for both frontends.
For most HTTP requests the consequences of this change will be negligible. If your application uses
HttpURLConnection.connect(),
setFixedLengthStreamingMode(), or
setChunkedStreamingMode(), OkHttp will now use a async dispatcher thread to establish the HTTP connection.
We don’t expect this change to have any behavior or performance consequences. Regardless, please exercise your
OkUrlFactoryand
HttpURLConnectioncode when applying this update.
Cipher suites may now have arbitrary names. Previously
CipherSuitewas a Java enum and it was impossible to define new cipher suites without first upgrading OkHttp. With this change it is now a regular Java class with enum-like constants. Application code that uses enum methods on cipher suites (
ordinal(),
name(), etc.) will break with this change.
Fix:
CertificatePinnernow matches canonicalized hostnames. Previously this was case sensitive. This change should also make it easier to configure certificate pinning for internationalized domain names.
- Fix: Don’t crash on non-ASCII
ETagheaders. Previously OkHttp would reject these headers when validating a cached response.
- Fix: Don’t allow remote peer to arbitrarily size the HPACK decoder dynamic table.
- Fix: Honor per-host configuration in Android’s network security config. Previously disabling cleartext for any host would disable cleartext for all hosts. Note that this setting is only available on Android 24+.
- New: HPACK compression is now dynamic. This should improve performance when transmitting request headers over HTTP/2.
- New:
Dispatcher.setIdleCallback()can be used to signal when there are no calls in flight. This is useful for testing with Espresso.
New: Upgrade to Okio 1.9.0.
<dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>1.9.0</version> </dependency>
Version 3.3.1¶
2016-05-28
- Fix: The plaintext check in HttpLoggingInterceptor incorrectly classified newline characters as control characters. This is fixed.
- Fix: Don’t crash reading non-ASCII characters in HTTP/2 headers or in cached HTTP headers.
- Fix: Retain the response body when an attempt to open a web socket returns a non-101 response code.
Version 3.3.0¶
2016-05-24
- New:
Response.sentRequestAtMillis()and
receivedResponseAtMillis()methods track the system’s local time when network calls are made. These replace the
OkHttp-Sent-Millisand
OkHttp-Received-Millisheaders that were present in earlier versions of OkHttp.
- New: Accept user-provided trust managers in
OkHttpClient.Builder. This allows OkHttp to satisfy its TLS requirements directly. Otherwise OkHttp will use reflection to extract the
TrustManagerfrom the
SSLSocketFactory.
- New: Support prerelease Java 9. This gets ALPN from the platform rather than relying on the alpn-boot bootclasspath override.
- New:
HttpLoggingInterceptornow logs connection failures.
New: Upgrade to Okio 1.8.0.
<dependency> <groupId>com.squareup.okio</groupId> <artifactId>okio</artifactId> <version>1.8.0</version> </dependency>
Fix: Gracefully recover from a failure to rebuild the cache journal.
- Fix: Don’t corrupt cache entries when a cache entry is evicted while it is being updated.
- Fix: Make logging more consistent throughout OkHttp.
- Fix: Log plaintext bodies only. This uses simple heuristics to differentiate text from other data.
- Fix: Recover from
REFUSED_STREAMerrors in HTTP/2. This should improve interoperability with Nginx 1.10.0, which refuses streams created before HTTP/2 settings have been acknowledged.
- Fix: Improve recovery from failed routes.
- Fix: Accommodate tunneling proxies that close the connection after an auth challenge.
- Fix: Use the proxy authenticator when authenticating HTTP proxies. This regression was introduced in OkHttp 3.0.
- Fix: Fail fast if network interceptors transform the response body such that closing it doesn’t also close the underlying stream. We had a bug where OkHttp would attempt to reuse a connection but couldn’t because it was still held by a prior request.
- Fix: Ensure network interceptors always have access to the underlying connection.
- Fix: Use
X509TrustManagerExtensionson Android 17+.
- Fix: Unblock waiting dispatchers on MockWebServer shutdown.
Version 3.2.0¶
2016-02-25
- Fix: Change the certificate pinner to always build full chains. This prevents a potential crash when using certificate pinning with the Google Play Services security provider.
- Fix: Make IPv6 request lines consistent with Firefox and Chrome.
- Fix: Recover gracefully when trimming the response cache fails.
- New: Add multiple path segments using a single string in
HttpUrl.Builder.
- New: Support SHA-256 pins in certificate pinner.
Version 3.1.2¶
2016-02-10
- Fix: Don’t crash when finding the trust manager on Robolectric. We attempted to detect the host platform and got confused because Robolectric looks like Android but isn’t!
- Fix: Change
CertificatePinnerto skip sanitizing the certificate chain when no certificates were pinned. This avoids an SSL failure in insecure “trust everyone” configurations, such as when talking to a development HTTPS server that has a self-signed certificate.
Version 3.1.1¶
2016-02-07
- Fix: Don’t crash when finding the trust manager if the Play Services (GMS) security provider is installed.
- Fix: The previous release introduced a performance regression on Android, caused by looking up CA certificates. This is now fixed.
Version 3.1.0¶
2016-02-06
- New: WebSockets now defer some writes. This should improve performance for some applications.
- New: Override
equals()and
hashCode()in our new cookie class. This class now defines equality by value rather than by reference.
- New: Handle 408 responses by retrying the request. This allows servers to direct clients to retry rather than failing permanently.
- New: Expose the framed protocol in
Connection. Previously this would return the application-layer protocol (HTTP/1.1 or HTTP/1.0); now it always returns the wire-layer protocol (HTTP/2, SPDY/3.1, or HTTP/1.1).
- Fix: Permit the trusted CA root to be pinned by
CertificatePinner.
- Fix: Silently ignore unknown HTTP/2 settings. Previously this would cause the entire connection to fail.
- Fix: Don’t crash on unexpected charsets in the logging interceptor.
- Fix:
OkHttpClientis now non-final for the benefit of mocking frameworks. Mocking sophisticated classes like
OkHttpClientis fragile and you shouldn’t do it. But if that’s how you want to live your life we won’t stand in your way!
Version 3.0.1¶
2016-01-14
- Rollback OSGi support. This was causing library jars to include more classes than expected, which interfered with Gradle builds.
Version 3.0.0¶
2016-01-13
This release commits to a stable 3.0 API. Read the 3.0.0-RC1 changes for advice on upgrading from 2.x to 3.x.
- The
Callbackinterface now takes a
Call. This makes it easier to check if the call was canceled from within the callback. When migrating async calls to this new API,
Callis now the first parameter for both
onResponse()and
onFailure().
- Fix: handle multiple cookies in
JavaNetCookieJaron Android.
- Fix: improve the default HTTP message in MockWebServer responses.
- Fix: don’t leak file handles when a conditional GET throws.
- Fix: Use charset specified by the request body content type in OkHttp’s logging interceptor.
- Fix: Don’t eagerly release pools on cache hits.
- New: Make OkHttp OSGi ready.
- New: Add already-implemented interfaces Closeable and Flushable to the cache.
Version 3.0.0-RC1¶
2016-01-02
OkHttp 3 is a major release focused on API simplicity and consistency. The API changes are numerous but most are cosmetic. Applications should be able to upgrade from the 2.x API to the 3.x API mechanically and without risk.
Because the release includes breaking API changes, we’re changing the project’s
package name from
com.squareup.okhttp to
okhttp3. This should make it
possible for large applications to migrate incrementally. The Maven group ID
is now
com.squareup.okhttp3. For an explanation of this strategy, see Jake
Wharton’s post, Java Interoperability Policy for Major Version
Updates.
This release obsoletes OkHttp 2.x, and all code that uses OkHttp’s
com.squareup.okhttp package should upgrade to the
okhttp3 package. Libraries
that depend on OkHttp should upgrade quickly to prevent applications from being
stuck on the old version.
There is no longer a global singleton connection pool. In OkHttp 2.x, all
OkHttpClientinstances shared a common connection pool by default. In OkHttp 3.x, each new
OkHttpClientgets its own private connection pool. Applications should avoid creating many connection pools as doing so prevents connection reuse. Each connection pool holds its own set of connections alive so applications that have many pools also risk exhausting memory!
The best practice in OkHttp 3 is to create a single OkHttpClient instance and share it throughout the application. Requests that needs a customized client should call
OkHttpClient.newBuilder()on that shared instance. This allows customization without the drawbacks of separate connection pools.
OkHttpClient is now stateless. In the 2.x API
OkHttpClienthad getters and setters. Internally each request was forced to make its own complete snapshot of the
OkHttpClientinstance to defend against racy configuration changes. In 3.x,
OkHttpClientis now stateless and has a builder. Note that this class is not strictly immutable as it has stateful members like the connection pool and cache.
Get and Set prefixes are now avoided. With ubiquitous builders throughout OkHttp these accessor prefixes aren’t necessary. Previously OkHttp used get and set prefixes sporadically which make the API inconsistent and awkward to explore.
OkHttpClient now implements the new
Call.Factoryinterface. This interface will make your code easier to test. When you test code that makes HTTP requests, you can use this interface to replace the real
OkHttpClientwith your own mocks or fakes.
The interface will also let you use OkHttp’s API with another HTTP client’s implementation. This is useful in sandboxed environments like Google App Engine.
OkHttp now does cookies. We’ve replaced
java.net.CookieHandlerwith a new interface,
CookieJarand added our own
Cookiemodel class. This new cookie follows the latest RFC and supports the same cookie attributes as modern web browsers.
Form and Multipart bodies are now modeled. We’ve replaced the opaque
FormEncodingBuilderwith the more powerful
FormBodyand
FormBody.Buildercombo. Similarly we’ve upgraded
MultipartBuilderinto
MultipartBody,
MultipartBody.Part, and
MultipartBody.Builder.
The Apache HTTP client and HttpURLConnection APIs are deprecated. They continue to work as they always have, but we’re moving everything to the new OkHttp 3 API. The
okhttp-apacheand
okhttp-urlconnectionmodules should be only be used to accelerate a transition to OkHttp’s request/response API. These deprecated modules will be dropped in an upcoming OkHttp 3.x release.
Canceling batches of calls is now the application’s responsibility. The API to cancel calls by tag has been removed and replaced with a more general mechanism. The dispatcher now exposes all in-flight calls via its
runningCalls()and
queuedCalls()methods. You can write code that selects calls by tag, host, or whatever, and invokes
Call.cancel()on the ones that are no longer necessary.
OkHttp no longer uses the global
java.net.Authenticatorby default. We’ve changed our
Authenticatorinterface to authenticate web and proxy authentication failures through a single method. An adapter for the old authenticator is available in the
okhttp-urlconnectionmodule.
Fix: Don’t throw
IOExceptionon
ResponseBody.contentLength()or
- Fix: Never throw converting an
HttpUrlto a
java.net.URI. This changes the
uri()method to handle malformed percent-escapes and characters forbidden by
URI.
- Fix: When a connect times out, attempt an alternate route. Previously route selection was less efficient when differentiating failures.
- New:
Response.peekBody()lets you access the response body without consuming it. This may be handy for interceptors!
- New:
HttpUrl.newBuilder()resolves a link to a builder.
- New: Add the TLS version to the
Handshake.
- New: Drop
Request.uri()and
Request#urlString(). Just use
Request.url().uri()and
Request.url().toString().
- New: Add URL to HTTP response logging.
- New: Make
HttpUrlthe blessed URL method of
Request. | https://square.github.io/okhttp/changelog_3x/ | CC-MAIN-2020-24 | refinedweb | 6,766 | 52.66 |
Introduction
Siri has been a core feature of iOS since it was introduced back in 2011. Now, iOS 10 brings new features to allow developers to interact with Siri. In particular, two new frameworks are now available: Speech and SiriKit.
Today, we are going to take a look at the Speech framework, which allows us to easily translate audio into text. You'll learn how to build a real-life app that uses the speech recognition API to check the status of a flight.
If you want to learn more about SiriKit, I covered it in my Create SiriKit Extensions in iOS 10 tutorial. For more on the other new features for developers in iOS 10, check out Markus Mühlberger's course, right here on Envato Tuts+.
Usage
Speech recognition is the process of translating live or pre-recorded audio to transcribed text. Since Siri was introduced in iOS 5, there has been a microphone button in the system keyboard that enables users to easily dictate. This feature can be used with any UIKit text input, and it doesn't require you to write additional code beyond what you would write to support a standard text input. It's really fast and easy to use, but it comes with a few limitations:
- The keyboard is always present when dictating.
- The language cannot be customized by the app itself.
- The app cannot be notified when dictation starts and finishes.
To allow developers to build more customizable and powerful applications with the same dictation technology as Siri, Apple created the Speech framework. It allows every device that runs iOS 10 to translate audio to text in over 50 languages and dialects.
This new API is much more powerful because it doesn't just provide a simple transcription service, but it also provides alternative interpretations of what the user may have said. You can control when to stop a dictation, you can show results as your user speaks, and the speech recognition engine will automatically adapt to the user preferences (language, vocabulary, names, etc.).
An interesting feature is support for transcribing pre-recorded audio. If you are building an instant messaging app, for example, you could use this functionality to transcribe the text of new audio messages.
Setup
First of all, you will need to ask the user for permission to transmit their voice to Apple for analysis.
Depending on the device and the language that is to be recognized, iOS may transparently decide to transcribe the audio on the device itself or, if local speech recognition is not available on the device, iOS will use Apple's servers to do the job.
This is why an active internet connection is usually required for speech recognition. I'll show you how to check the availability of the service very soon.
There are three steps to use speech recognition:
- Explain: tell your user why you want to access their voice.
- Authorize: explicitly ask authorization to access their voice.
- Request: load a pre-recorded audio from disk using
SFSpeechURLRecognitionRequest, or stream live audio using
SFSpeechAudioBufferRecognitionRequestand process the transcription.
If you want to know more about the Speech framework, watch WWDC 2016 Session 509. You can also read the official documentation.
Example
I will now show you how to build a real-life app that takes advantage of the speech recognition API. We are going to build a small flight-tracking app in which the user can simply say a flight number, and the app will show the current status of the flight. Yes, we're going to build a small assistant like Siri to check the status of any flight!
In the tutorial's GitHub repo, I've provided a skeleton project that contains a basic UI that will help us for this tutorial. Download and open the project in Xcode 8.2 or higher. Starting with an existing UI will let us focus on the speech recognition API.
Take a look at the classes in the project.
UIViewController+Style.swift contains most of the code responsible for updating the UI. The example datasource of the flights displayed in the table is declared in
FlightsDataSource.swift.
If you run the project, it should look like the following.
After the user presses the microphone button, we want to start the speech recognition to transcribe the flight number. So if the user says "LX40", we would like to show the information regarding the gate and current status of the flight. To do this, we will call a function to automatically look up the flight in a datasource and show the status of the flight.
We are first going to explore how to transcribe from pre-recorded audio. Later on, we'll learn how to implement the more interesting live speech recognition.
Let's start by setting up the project. Open the
Info.plist file and add a new row with the explanation that will be shown to the user when asked for permission to access their voice. The newly added row is highlighted in blue in the following image.
Once this is done, open
ViewController.swift. Don't mind the code that is already in this class; it is only taking care of updating the UI for us.
The first step with any new framework that you want to use is to import it at the top of the file.
import Speech
To show the permission dialog to the user, add this code in the
viewDidLoad(animated:) method:
switch SFSpeechRecognizer.authorizationStatus() { case .notDetermined: askSpeechPermission() case .authorized: self.status = .ready case .denied, .restricted: self.status = .unavailable }
The
status variable takes care of changing the UI to warn the user that speech recognition is not available in case something goes wrong. We are going to assign a new status to the same variable every time we would like to change the UI.
If the app hasn't asked the user for permission yet, the authorization status will be
notDetermined, and we call the
askSpeechPermission method to ask it as defined in the next step.
You should always fail gracefully if a specific feature is not available. It's also very important to always communicate to the user when you're recording their voice. Never try to recognize their voice without first updating the UI and making your user aware of it.
Here's the implementation of the function to ask the user for permission.
func askSpeechPermission() { SFSpeechRecognizer.requestAuthorization { status in OperationQueue.main.addOperation { switch status { case .authorized: self.status = .ready default: self.status = .unavailable } } } }
We invoke the
requestAuthorization method to display the speech recognition privacy request that we added to the
Info.plist. We then switch to the main thread in case the closure was invoked on a different thread—we want to update the UI only from the main thread. We assign the new
status to update the microphone button to signal to the user the availability (or not) of speech recognition.
Pre-Recorded Audio Recognition
Before writing the code to recognize pre-recorded audio, we need to find the URL of the audio file. In the project navigator, check that you have a file named
LX40.m4a. I recorded this file myself with the Voice Memos app on my iPhone by saying "LX40". We can easily check if we get a correct transcription of the audio.
Store the audio file URL in a property:
var preRecordedAudioURL: URL = { return Bundle.main.url(forResource: "LX40", withExtension: "m4a")! }()
It's time to finally see the power and simplicity of the Speech framework. This is the code that does all the speech recognition for us:
func recognizeFile(url: URL) { guard let recognizer = SFSpeechRecognizer(), recognizer.isAvailable else { return } let request = SFSpeechURLRecognitionRequest(url: url) recognizer.recognitionTask(with: request) { result, error in guard let recognizer = SFSpeechRecognizer(), recognizer.isAvailable else { return self.status = .unavailable } if let result = result { self.flightTextView.text = result.bestTranscription.formattedString if result.isFinal { self.searchFlight(number: result.bestTranscription.formattedString) } } else if let error = error { print(error) } } }
Here is what this method is doing:
- Initialize a
SFSpeechRecognizerinstance and check that the speech recognition is available with a guard statement. If it's not available, we simply set the status to
unavailableand return. (The default initializer uses the default user locale, but you can also use the
SFSpeechRecognizer(locale:)initializer to provide a different locale.)
- If speech recognition is available, create a
SFSpeechURLRecognitionRequestinstance by passing the pre-recorded audio URL.
- Start the speech recognition by invoking the
recognitionTask(with:)method with the previously created request.
The closure will be called multiple times with two parameters: a result and an error object.
The
recognizer is actually playing the file and trying to recognize the text incrementally. For this reason, the closure is called multiple times. Every time it recognizes a letter or word or it makes some corrections, the closure is invoked with up-to-date objects.
The
result object has the
isFinal property set to true when the audio file was completely analyzed. In this case, we start a search in our flight datasource to see if we can find a flight with the recognized flight number. The
searchFlight function will take care of displaying the result.
The last thing that we are missing is to invoke the
recognizeFile(url:) function when the microphone button is pressed:
@IBAction func microphonePressed(_ sender: Any) { recognizeFile(url: preRecordedAudioURL) }
Run the app on your device running iOS 10, press the microphone button, and you'll see the result. The audio "LX40" is incrementally recognized, and the flight status is displayed!
Tip: The flight number is displayed in a UITextView. As you may have noticed, if you enable the Flight Number data detector in the UITextView, you can press on it and the current status of the flight will actually be displayed!
The complete example code up to this point can be viewed in the pre-recorded-audio branch in GitHub.
Live Audio Recognition
Let's now see how to implement live speech recognition. It's going to be a little bit more complicated compared to what we just did. You can once again download the same skeleton project and follow along.
We need a new key in the
Info.plist file to explain to the user why we need access to the microphone. Add a new row to your
Info.plist as shown in the image.
We don't need to manually ask the user for permission because iOS will do that for us as soon as we try to access any microphone-related API.
We can reuse the same code that we used in the previous section (remember to
import Speech) to ask for the authorization. The
viewDidLoad(animated:) method is implemented exactly as before:
switch SFSpeechRecognizer.authorizationStatus() { case .notDetermined: askSpeechPermission() case .authorized: self.status = .ready case .denied, .restricted: self.status = .unavailable }
Also, the method to ask the user for permission is the same.
func askSpeechPermission() { SFSpeechRecognizer.requestAuthorization { status in OperationQueue.main.addOperation { switch status { case .authorized: self.status = .ready default: self.status = .unavailable } } } }
The implementation of
startRecording is going to be a little bit different. Let's first add a few new instance variables that will come in handy while managing the audio session and speech recognition task.
let audioEngine = AVAudioEngine() let speechRecognizer: SFSpeechRecognizer? = SFSpeechRecognizer() let request = SFSpeechAudioBufferRecognitionRequest() var recognitionTask: SFSpeechRecognitionTask?
Let's take a look at each variable separately:
AVAudioEngineis used to process an audio stream. We will create an audio node and attach it to this engine so that we can get updated when the microphone receives some audio signals.
SFSpeechRecognizeris the same class we have seen in the previous part of the tutorial, and it takes care of recognizing the speech. Given that the initializer can fail and return nil, we declare it as optional to avoid crashing at runtime.
SFSpeechAudioBufferRecognitionRequestis a buffer used to recognize the live speech. Given that we don't have the complete audio file as we did before, we need a buffer to allocate the speech as the user speaks.
SFSpeechRecognitionTaskmanages the current speech recognition task and can be used to stop or cancel it.
Once we have declared all the required variables, let's implement
startRecording.
func startRecording() { // Setup audio engine and speech recognizer guard let node = audioEngine.inputNode else { return } let recordingFormat = node.outputFormat(forBus: 0) node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in self.request.append(buffer) } // Prepare and start recording audioEngine.prepare() do { try audioEngine.start() self.status = .recognizing } catch { return print(error) } // Analyze the speech recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in if let result = result { self.flightTextView.text = result.bestTranscription.formattedString self.searchFlight(number: result.bestTranscription.formattedString) } else if let error = error { print(error) } }) }
This is the core code of our feature. I will explain it step by step:
- First we get the
inputNodeof the
audioEngine. A device can possibly have multiple audio inputs, and here we select the first one.
- We tell the input node that we want to monitor the audio stream. The block that we provide will be invoked upon every received audio stream of 1024 bytes. We immediately append the audio buffer to the
requestso that it can start the recognition process.
- We prepare the audio engine to start recording. If the recording starts successfully, set the status to
.recognizingso that we update the button icon to let the user know that their voice is being recorded.
- Let's assign the returned object from
speechRecognizer.recognitionTask(with:resultHandler:)to the
recognitionTaskvariable. If the recognition is successful, we search the flight in our datasource and update the UI.
The function to cancel the recording is as simple as stopping the audio engine, removing the tap from the input node, and cancelling the recognition task.
func cancelRecording() { audioEngine.stop() if let node = audioEngine.inputNode { node.removeTap(onBus: 0) } recognitionTask?.cancel() }
We now only need to start and stop the recording. Modify the
microphonePressed method as follows:
@IBAction func microphonePressed() { switch status { case .ready: startRecording() status = .recognizing case .recognizing: cancelRecording() status = .ready default: break } }
Depending on the current
status, we start or stop the speech recognition.
Build and run the app to see the result. Try to spell any of the listed flight numbers and you should see its status appear.
Once again, the example code can be viewed in the live-audio branch on GitHub.
Best Practices
Speech recognition is a very powerful API that Apple provided to iOS developers targeting iOS 10. It is completely free to use, but keep in mind that it's not unlimited in usage. It is limited to about one minute for each speech recognition task, and your app may also be throttled by Apple's servers if it requires too much computation. For these reasons, it has a high impact on network traffic and power usage.
Make sure that your users are properly instructed on how to use speech recognition, and be as transparent as possible when you are recording their voice.
Recap
In this tutorial, you have seen how to use fast, accurate and flexible speech recognition in iOS 10. Use it to your own advantage to give your users a new way of interacting with your app and improve its accessibility at the same time.
If you want to learn more about integrating Siri in your app, or if you want to find out about some of the other cool developer features of iOS 10, check out Markus Mühlberger's course.
Also, check out some of our other free tutorials on iOS 10 features.
- iOSUpgrade Your App to iOS 10
- iOS SDKiOS 10: Creating Custom Notification Interfaces
- iOS 10Haptic Feedback in iOS 10
- iOS SDKCreate SiriKit Extensions in iOS 10 | http://esolution-inc.com/blog/using-the-speech-recognition-api-in-ios-10--cms-28032.html | CC-MAIN-2018-09 | refinedweb | 2,606 | 56.45 |
Separating the Read Model
A typical architecture of a .NET web application is to use EF Code First for data access and MVC to render the web pages. The data model in the database is usually (and should be!) normalized. A normalized data model is also great for updates, but when displaying data it is not enough. E.g. in a table of cars I don’t want to display a numeric, database internal id of the car’s brand. I want to display the name of the brand. Creating a separate read model simplifies that.
Separating the read and write models are a key concept of the recently popular CQRS (Command Query Responsibility Separation architecture. I won’t go as far as the CQRS model does, but rather show a simple way to dress the write model’s car entity with the values required for displaying.
My key objective is to get a model where I can get everything needed for rendering a view to the user in one fetch from the database, with a minimum of extra coding and mapping code.The Read Model
For this example I have a cars table with a foreign key (giving a navigation property) to a brands table. When displaying a list of cars I of course want to display the name of the brand, not its internal database id that’s stored in the cars table. A simple way to handle that is to wrap the car entity class in a read model (which can be used as our view model in MVC).
public class CarReadModel { public Car Car { get; set; } public string BrandName { get; set; } }Querying for the Read Model
The purpose of the read model is to fetch everything needed to display the web page in one call to the database. That can be done with a LINQ query that projects the result into a CarReadModel object with select.
from c in ctx.Cars where c.CarId == id select new CarReadModel { Car = c, BrandName = c.Brand.Name }
The entire read model is fetched in one efficient call to the database. The read model contains everything needed for displaying.
In this case it’s perfectly fine to include the entire cars entity in the read model because the entity is so lightweight. If the entity contains any large fields (e.g. a scanned registration certificate) that is not to be displayed in all views it would be better to list the required fields explicitly in the read model instead.
Everything works fine with this code, but if the CarReadModel class is to be reused for different queries, the projection (the select part of the query) should be reusable. I’ll show a simple way to do that next week.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) | http://www.dzone.com/articles/separating-read-model | CC-MAIN-2013-48 | refinedweb | 481 | 70.13 |
EuroPython 2013
Moist
For each incoming element, if it is larger than our current maximum, it becomes the new maximum and requires no additional cost because it is already in the right location. Otherwise, we add one dollar to our running total cost.
import Jam main = jam $ do [n] <- getints (a:as) <- getsn n let f a [] acc = acc f a (b:bs) acc | b > a = f b bs acc | otherwise = f a bs (acc + 1) return $ show $ f a as 0
Captain Hammer
A little elementary physics shows the answer for each case is:
1/2 asin (9.8 D / V^2)
As asin returns its result in radians we multiply this by 180 / pi.
Some care is needed. Due to floating point rounding error, computing 9.8 * d then dividing by v^2 could lead to the wrong answer. Instead, we compute 98 * d / (10 * v^2), which postpones the rounding.
import Jam import Text.Printf main = jam $ do [v, d] <- getdbls return $ printf "%.7f" $ 180 / pi * asin (98 * d / (10 * v^2)) / 2
Bad Horse
If we strip away the cute setup, we see the problem is just asking whether the input is a bipartite graph.
Haskell has a Data.Graph module, but this seems to lack routines for bipartite graphs. This is just as well, as it means we get to practice graph algorithms in Haskell.
We use the standard depth-first search algorithm. Briefly, we alternately colour the nodes we encounter black and white. If we reach a visited node, then if its colour differs from the colour we would assign it if it were unvisited, then we know there is a cycle of odd length and hence the graph cannot be bipartite.
We use an array of type Maybe Int with inefficient updates to record the colours of the nodes: Nothing means the node is unvisited, otherwise the colour is 0 or 1.
Haskell provides components function, which we use for slightly simpler code.
import Jam import Data.Array import Data.List import Data.Maybe import Data.Graph import Data.Tree main = jam $ do [n] <- getints es <- map words <$> getsn n let names = nub $ concat es bnds = (0, length names - 1) toEdges [v, w] = [(v, w), (w, v)] g = buildG bnds $ concatMap (toEdges . map (fromJust . (`elemIndex` names))) es bi a c v = case a!v of Nothing -> foldl' (\(b, a) w -> let (b', a') = bi a (1 - c) w in (b && b', a')) (True, a // [(v, Just c)]) (g!v) Just x -> (x == c, a) blank = listArray bnds $ repeat Nothing return $ case all (fst . bi blank 0 . rootLabel) $ components g of True -> "Yes" False -> "No"
As usual, we should practice writing a brute-force solution for training purposes. For this, we simply iterate through all subsets of the league until we find a subset that contains exactly one vertex of each edge.
We use a mind-blowing Haskell trick to enumerate all subsets of a set (filterM (const [True, False])).
import Jam import Control.Monad import Data.List main = jam $ do [n] <- getints es <- map words <$> getsn n let names = nub $ concat es separates s = all (\[x, y] -> elem x s /= elem y s) es return $ case find separates (filterM (const [True, False]) names) of Nothing -> "No" _ -> "Yes"
For some reason, the practice page only provides small data sets so brute force is enough to achieve a full score.
Professor Normal
The inputs are far too large for a straightforward simulation of the game. We must think of something smarter.
Define the delta of a turn to be the MxN array that represents the change in the number of marbles each child possesses after that turn.
Suppose that after a turn, no child is eliminated. That is, each child still has at least 12 marbles. Then the next turn, each child will give and receive the same number of marbles they gave and received in the previous round, that is, the delta for the next turn is identical.
Thus until a child is eliminated, we can easily predict the number of marbles each child holds in dt turns: just add that child’s delta value multiplied by dt. By the same token, we can also easily determine which child, if any, is the next to be eliminated: for each negative delta value, a suitably crafted division tells us how many turns the child has left.
This suggests a simple algorithm:
Eliminate any children with less than 12 marbles or have no neighbours that have at least 12 marbles. If there are no children left, then print the number of elapsed turns.
Compute the delta array for the remaining children.
Examine the negative delta values to determine dt, the number of turns before a child must leave the game. If there are no negative delta values, then the remaining children play forever.
Adjust the marble counts by dt times delta, and go to step 1.
Because this is Haskell, we must take care with arrays. We use accumArray instead of updating an existing array one element at a time (which behind the scenes is equivalent to an array copy).
We also order the checks for the terminating conditions so we compute rem only when absolutely necessary.
import Jam import Data.Array import Data.List neighbours a (i, j) = [(x, y) | (di, dj) <- [(-1, 0), (1, 0), (0, -1), (0, 1)], let (x, y) = (i + di, j + dj), inRange (bounds a) (x, y), a!(x, y) >= 12] cull a = a // [(i, 0) | i <- indices a, a!i < 12 || null (neighbours a i)] play t a0 = let bnds = bounds a0 a1 = cull a0 delta = accumArray (+) 0 bnds $ concat [(i, -12) : let ns = neighbours a1 i in [(n, div 12 (length ns)) | n <- ns] | i <- range bnds, a1!i >= 12] rem = length $ filter (> 0) (elems a1) ttl = [1 + ((a1!i - 12) `div` (-delta!i)) | i <- range bnds, delta!i < 0] dt = foldl1' min ttl in if not $ null ttl then play (t + dt) $ array bnds [(i, a1!i + dt * delta!i) | i <- range bnds] else if rem == 0 then show t ++ " turns" else show rem ++ " children will play forever" main = jam $ do [m] <- getints [n] <- getints a <- listArray ((1, 1), (m, n)) . concat <$> getintsn m return $ play 0 a | http://crypto.stanford.edu/~blynn/haskell/2013-europython.html | CC-MAIN-2017-47 | refinedweb | 1,042 | 80.82 |
.
The simple model of the situation is that there is some number
, and every baby flips a biased coin, which says “be a boy” with probability
and “be a girl” with probability
. This model ignores correlations between twins, the biophysics of sperm, the existence of intersex babies, as well as many other things. All models are wrong, but some are simple examples.
Mathematically, if
denotes the number of live births, and
denotes the number of boys, the model says
You can think of this as a one parameter model. If I tell the model
, then for any
and
, the model can tell me the probability. Now, to answer a question like “is it possible that
?”, the Bayesians need some sort of prior distribution on
. Where does this prior come from? Maybe I should invoke the “principle of insufficient reason”, and say that, since I have no idea, I expect any value between 0 and 1 for
, which leads to a uniform distribution on [0,1]. But maybe that’s not an accurate representation of truth; even before I looked up the numbers quoted above, I would have been shocked to learn that
, much more shocked than if you told me that
. But I’ll hold on to that thought, and go with the uniform prior for now.
In PyMC, it’s 4 lines to set up this model:
from pymc import * p_b = Uniform('p_b', 0.0, 1.0) N_b = Binomial('N_b', n=4138349, p=p_b, value=2118982, observed=True) m = Model([p_b, N_b])
To see the posterior log-probability for a particular value of
, do this:
p_b.value = 0.5 print m.logp
Here is the plot:
First Bayesian Example
This simple example is so simple that you don’t need any MCMC. But it would be easy to do some if you did.
mc = MCMC(m) mc.sample(iter=50000,burn=10000) hist(p_b.trace())
To return to the thought that I’ve been holding, I know that
. How can I encode this? I could replace my definition of
p_b using something like
p_b = Uniform('p_b', 0.0, 0.95), but I’d also be surprised to learn that
, so maybe something like
p_b = Normal('p_b', 0.5, 0.2) is a good way to go. I don’t know what the pros would think of that; they seem to favor an exotic prior, like
p_b = Beta('p_b', 10, 10) which is “conjugate” in this case.
To turn the problem around (and put it in a context I’m familiar with from work), how concentrated does the prior have to be to model a doctor who believes that
despite the evidence?
For bonus points, with PyMC we can go beyond the work of Bayes, and model the uncertainty in the vital registration system. These numbers for the USA are probably very close to perfect. But I would be more skeptical of the accuracy for the 241,945 girls and 251,527 boys recorded during Laplace’s day. And how can I represent my skepticism? Maybe I’ll represent it as a normally distributed error with standard deviation 10000.
from pymc import * p_b = Uniform('p_b', 0.0, 1.0) e_N = Normal('e_N', 0.0, 1.0/(10000.0)**2) e_N_b = Normal('e_N_b', 0.0, 1.0/(10000.0)**2) @potential def likelihood(N_b=251527, e_N_b=e_N_b, N=241945+251527, e_N=e_N, p=p_b): return binomial_like(N_b + e_N_b, N + e_N, p) mc = MCMC([p_b, N, N_b, likelihood])
Easy, right? Well, easy to write. Can you get PyMC to draw believable samples from it? I can, but it takes a little longer. Remember to thin your samples!
8 responses to “MCMC in Python: PyMC for Bayesian Probability”
How did you make the plot of the posterior log-probability? Is there a function in PyMC to do that, or did you just plot the distribution by writing a separate function?
Erik: There is not a PyMC function to make that plot, and it took me a line or two more Python than it should, so I didn’t include it in the example. Here is what it takes to get started:
To get a zoomed-in view of the piece where the action is, use
p_vals = arange(0.51,0.515,0.00001)as line 1. Then it will even look nice with
plot(p_vals,exp(array(logpr_vals))).
I found the cool way to make that plot.
🙂
> so maybe something like p_b = Normal(‘p_b’, 0.5, 0.2) is a good way
> to go
The problem with allowing the parameter p_b to be distributed Normally
is that a Normal distribution would assign positive probability to
p_b>1.0 and p_b<0. Though you can make this probability vanishingly
small by choosing an appropritately small variance, it will always be
positive. This is why more "exotic" distributions are prefered for
distributions over parameters than have a constrained range.
@Josh, there is also the
Truncnormstoch in PyMC, which combines the familiarity of the normal distribution with the appropriate support of the beta distribution. Here is some PyMC documentation on it, together with an example of a custom step method that doesn’t waste time stepping over the edge: example-an-asymmetric-metropolis-step.
Pingback: 2010 in review | Healthy Algorithms
Thank you, that was a useful post. Going to use this tutorial for a completely different project.
Great, if there is something to show from your project please post a link here, I’d love to see how this lives on. | https://healthyalgorithms.com/2008/11/26/mcmc-in-python-pymc-for-bayesian-probability/ | CC-MAIN-2020-40 | refinedweb | 915 | 72.87 |
DNS Server Help Needed
There is a good resource on the web on Windows 2000 DNS the URL is:
I have had similar problems when I did not have a DNS server for the root namespace zone already running prior to doing a dcpromo.
I have had to remove DNS from the DC that I promoted and re-installed and recreated the zone.
The key to all of this is that DNS that supports SRV records mustbe running in order to install Active Directory. The link above is a complete DNS discussion and the requirements.
DNS Server Help Needed
Did you make sure that you set the zone to allow for Dynamic Updates, And Active-Directory Intergrated?
DNS Server Help Needed
However, we cannot get the DNS going.
NetDiag gives us the following error.
DNS Test...
[Warning] The DNS entries for this DC are not registered correctly on DNS server *192.x.x.x*
[Fatal] No DNS servers have the DNS records for this DC registered.
We have recreated the zone(s)and a tried a few other things.
Does anyone have any suggestions or can anyone recommend a good resource?
Thank you
This conversation is currently closed to new comments. | https://www.techrepublic.com/forums/discussions/dns-server-help-needed/ | CC-MAIN-2019-18 | refinedweb | 201 | 71.95 |
Sets the value of the given integer parameter.
Use this as a way to trigger transitions between Animator states. One way of using Integers instead of Floats or Booleans is to use it for something that has multiple states, for example directions (turn left, turn right etc.). Each direction could correspond to a number instead of having multiple Booleans that have to be reset each time.
See documentation on Animation for more information on setting up Animators.
Note: You can identify the parameter by name or by ID number, but the name or ID number must be the same as the parameter you want to change in the Animator.
//This script sends messages to an Animator component to tell it to make transitions based on an integer named “States”. You change and send this integer to the Animator by pressing the space and arrow keys.
//In order for this script to work, you have to set up your Animator Controller so the script can interact with it. //Create a new Animator Controller if you do not already have one you want to use. To do this, click on the GameObject you want to animate and go to its Inspector window. Click the Add Component button and go to Miscellaneous>Animator). //Double click the Animator to see the Animator Controller window. Open the Parameters tab and click the plus icon to add a new parameter. Choose Int from the dropdown. Name the new Integer (for this script, call it “States”). //Create a few animation states (right click the grid and choose Create State>Empty) and choose an Animation for each in the Motion field. //Next create transitions between each of the states (right click the state, choose Make Transition and click on the state you want it to transition to). //Finally, click on one of the arrows to bring up its Inspector. Click the + icon under the Conditions section and choose the parameter you made (“States”). Change Greater to Equals and choose a number that you want to represent this state. Do the same with any other states. //You may want to set up transitions back to the first animation state so that when the button is let go, it will return to the first state. You may also want to uncheck the Has Exit Time box for each transition. Otherwise transitions will wait for an animation to finish before proceeding.
using UnityEngine;
public class AnimatorSetIntExample : MonoBehaviour { Animator m_Animator;
void Start() { //Fetch the Animator from the GameObject you attached the script to m_Animator = GetComponent<Animator>(); }
void Update() { //Check if the horizontal buttons (A,D, left and right arrow keys) are being pressed if (Input.GetAxis("Horizontal") > 0 || Input.GetAxis("Horizontal") < 0) //Set the integer named "States" in your Animator to 1. If the Animator is set up properly, this should trigger an animation. m_Animator.SetInteger("States", 1); //Press the down arrow key to start another animation transition else if (Input.GetKey(KeyCode.DownArrow)) //Set the "States" integer to 2. This triggers the animation that should start when "States" is equal to 2 m_Animator.SetInteger("States", 2); //Press the space key to set the "States integer to 3 else if (Input.GetKey(KeyCode.Space)) m_Animator.SetInteger("States", 3); else //If all the other keys are let go, set the "States" integer to 0. m_Animator.SetInteger("States", 0); } } | https://docs.unity3d.com/ja/2020.1/ScriptReference/Animator.SetInteger.html | CC-MAIN-2021-04 | refinedweb | 555 | 55.54 |
There are abuses of the class system, and then there are those beautiful, snowflake- like cases of abuse, those moments where you see the code, you understand the code, and you wish that, somehow, you could throttle the invisible person responsible for that code. Alex found this example:
public class Record_Base { public DateTime RecordDateTime { get { return _recordDateTime; } set { if (this.GetType().Name == "Record_PartRegister") _recordDateTime = value; else throw new Exception("Cannot call set on RecordDateTime for table " + this.GetType().Name); } } }
This is special. You see,
RecordDateTime is a member of the class
Record_Base.
Record_PartRegister is a child class. This means that the parent can’t set a property it implements itself. For bonus points, the original culprit didn’t bother to document this method as being profoundly broken. Alex only discovered this when trying to diagnose a mysterious, uninformative, and untyped exception. | http://thedailywtf.com/articles/Making-Off-With-Your-Inheritance | CC-MAIN-2017-51 | refinedweb | 141 | 56.35 |
tag:blogger.com,1999:blog-388965192009-07-18T14:54:39.310-04:00To Love, Honor and VacuumMusings of a Christian author and mom who knows that God cares more about us than He does about the size of the dust bunnies under our bed!Sheila Wednesday: How He Brings Peace<a href=""><img id="BLOGGER_PHOTO_ID_5358665116256902322" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><div>Remember the book <a href="">Men are Like Waffles, Women are Like Spaghetti</a>? I wrote about that in my syndicated column last week, which I forgot to post (just realized that now, I'll put it up for tomorrow); but basically here's the issue: we women are multi-taskers. When we're doing the laundry, we're thinking about what we're making for dinner, we're talking on the phone, and we're trying to plan the route we'll take to drop kids off at various houses, pick them up for soccer, and get grocery shopping done, all without running out of gas.<br /><br />And that's just when we're trying to hold the household things in our head. We're also worried about our work, our church, and all kinds of other things that weigh on us. And through it all, our relationships remain at the forefront. If we're worried about a child, we're thinking about that when we're teaching Sunday School, when we're taking a bath, and even when we go to bed at night.<br /><br />Men, on the other hand, tend to be quite compartmentalized, which can be very annoying to us multitaskers. If you ask them what they're thinking about, chances are they're not thinking about anything at all. They're not trying to keep four balls in the air at any one time. When they're thinking about work, they're thinking about work. When they're thinking about family, they're thinking about family. So when we get upset when they're in a different sphere and we're not foremost on their minds, they don't get it. But they don't have ten things they're thinking about at any one time like we do.<br /><br />This obviously has the potential to be hurtful in a marriage, if we interpret it to mean that they don't love as much as we do. That's not true; it's just that they express things differently.<br /><br />But it can also be helpful to us as women, and that's the question I was <a href="">posing yesterday </a>on this blog: can he bring you peace?<br /><br />I don't mean perfect peace; that's a role that only Jesus can play. But I do think that when we stay plugged in to our husbands, they can take some of the weight off of our shoulders, or at least tell us what we can stop worrying about.<br /><br />So often when I feel myself overbooked or overworked, I just sit down with Keith and he tells me what to get rid of in my schedule. He's not ordering me around; he's just providing that second set of eyes that often isn't as emotionally invested in my life. And quite often I'll resist it. I remember him telling me at one point that I had to give up teaching Sunday School for a while. Boy was I mad. Didn't he understand what a ministry this was? I had to serve God, after all. But eventually I realized he was right.<br /><br />He told me something even bigger this year, which I can't go into in a public blog, but I resisted that one for months before realizing, again, that Keith was right. Too often I take on responsibilities that are too big for me to handle, and eventually I just have to say no.<br /><br />Often, though, it's not that Keith tells me I need to stop something. It's that he's learned how to listen without always solving problems, which is a wonderful gift for a man to have. I think because we women think so hard about all the people in our lives, we have a tendency to overanalyze. We did it when we were dating, analyzing everything he said or did. We did it when we were pregnant, analyzing every feeling. And now we do it with the kids, and with friends, and relatives, and teachers. We analyze and take offense and worry.<br /><br />Sometimes, when you just speak these things out loud to someone who is not as prone to analyzing, you realize that you're overreacting. Talking to a girlfriend doesn't always do it, because she can make it worse if she's an analyzer, too. But talking to a man helps you see that perhaps it isn't the big deal that you were making it out to be. It's not even anything Keith says, either; it's just in speaking it out loud to him, I start to see it through his point of view. And then it loses the ability to consume me.<br /><br />These are some ways that Keith brings me peace, and why I'm glad I'm married. But I know in the comments below, when I first raised the question, some women were talking about how their husbands are too preoccupied to do this. Good point. That is the case in many marriages, and in mine, when Keith was going through his medical training and was really busy, I did carry much more myself.<br /><br />But can I suggest something? No matter how busy your husband is, and how busy you are, you need to make time to connect and talk about life at least once a week. He may resist, but it is vital for the marriage. It comes before kids. It comes before work. It comes before church, school, or other family. If your marriage falls apart, you lose everything. And your marriage is the best tool you have for encouragement in the human realm.<br /><br />So once a week, eat dinner, just the two of you, even if you have to do it after the kids go to bed. Go for a walk after dinner. Retreat to your room and tell the kids not to bug you because you're talking. Hire a baby-sitter and go out for coffee (much cheaper than dinner) and talk. But do it, once a week, no ifs, ands or buts. Some of you may not have to schedule it because you have lots of time together. But if you don't, you need to make it a priority. Start talking again, and build that companionship, so that he can start bringing you peace.<br /><br /><strong><em><span style="font-size:85%;color:#663366;">Now, would you like to participate in Wifey Wednesday? We'd love to hear from you! Does your husband help you feel more peaceful? Does it bother you when he seems not to care the same way you do? Do you have creative ways to connect during the week? Tell us!</span></em></strong></div><br /><br /><div><strong><em><span style="font-size:85%;color:#663366;"></span></em></strong></div><div><strong><em><span style="font-size:85%;color:#663366;">Simply copy the picture at the top of this post and put it up on your own blog. Link to me, and then write your marriage post, and come back here and leave it in the Mr. Linky. We'd love to hear from you!<br /><br /><div><a href="" target="_blank"><img src="" border="0" /></a></div><br /><br /></span></em></strong><!--><p><?xml:namespace prefix = data /><data:post.body></data:post.body></p>: Go 3 for 3<a href=""><img id="BLOGGER_PHOTO_ID_5353471282627843394" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><div>I was browsing around the internet lately and found the best synopsis of marriage advice I've seen in a long time.<br /><br />Readers to this blog won't find any of it surprising. I talk on these themes all the time. But it's so pithy and wise, I have to reproduce it just as she said it over at <a href="">Garden of Holiness</a>:<br /><br /><blockquote>3 Things to Keep in Mind<br />1. You picked him.<br />2. You can't change him.<br />3. You didn't marry a girl. </blockquote></div><br /><br /><div>Aren't those brilliant? <a href="">we can focus on changing ourselves.<br /></a><br />And remember, <a href="">he's a guy</a>! And there's nothing wrong with that.<br /><br />I'm scheduling this post ahead of time because I'm away this Wifey Wednesday, so I'm going to send you over to <a href="">Garden of Holiness </a>for the rest of her post. And you can click through on the links I've highlighted there to other Wifey Wednesday posts I've loved!<br /><br /><strong><em><span style="color:#663366;">Now it's your turn! Go to your own blog and write a marriage post, and then come back here and leave your link in the Mr. Linky! (I'm assuming Mr. Linky will work, but I'm scheduling this ahead of time. If he doesn't, leave your link in the comments!). And copy my picture from the top of this post and use it in your post, too! Thanks so much, and I look forward to seeing what you all have to say!<br /></span></em></strong><br /><div><a href="" target="_blank"><img src="" border="0" /></a><><br /><br /><a href=""><img style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px" alt="To Love, Honor and Vacuum" src="" /></a> </div><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday: What Lens Do You See Your Husband Through?<a href=""><img id="BLOGGER_PHOTO_ID_5353455791778872402" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><br />Quite often we don't see people how they really are. We look at them with our own biases.<br /><br />For instance, before we get married we tend to see our husbands (then our fiances) through rose-coloured glasses. We may notice that they do annoying things, but we think of these as "cute quirks" that they will likely grow out of.<br /><img id="BLOGGER_PHOTO_ID_5353461368212193938" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 123px; CURSOR: hand; HEIGHT: 82px; TEXT-ALIGN: center" alt="" src="" border="0" /><br />Then, once we're married, those glasses often fall off and we start noticing all the things that are wrong with our husbands.<br /><br />But we have other lenses, too, and we need to be aware of them so that we can make sure we're not being unfair to our husbands.<br /><br /><strong><span style="color:#000066;">1. The Father Lens</span></strong>..<br />.<br /><br /.<br /><br /><strong><span style="color:#000066;">2. The Bad Relationship Lens.</span></strong>.<br /><br /><strong><span style="color:#000066;">3. The Pathetic Man Lens.</span></strong>.<br /><br /!<br /><br /><strong><span style="color:#000066;">4. The He's Always Right Lens.</span></strong>.<br />.<br /><br /><strong><span style="color:#000066;">5. My Kids Are My Main Concern Right Now.</span></strong>.<br /><br /><strong><span style="color:#000066;">6. The Men are Evil University Lens.</span></strong>.<br /><br /:<br /><br /><strong><em><span style="color:#663366;"><blockquote><strong><em><span style="color:#663366;">"Is he really doing something very wrong? Or am I assuming something about the situation?"</span></em></strong> </blockquote></span></em></strong><br /><br />That's a good practice to get into in marriage: start with yourself when there's a conflict. And you just might find that those conflicts magically disappear!<br /><br /><strong><em><span style="color:#663366;">Please share your thoughts with us! Go to your own blog and write a Wifey Wednesday post, and then come back here and enter it in the Mr. Linky. We'd love to hear what you have to share about marriage!</span></em></strong><br /><br /><div><a href="" target="_blank"><img src="" border="0" /></a></div><br /><br />And don't forget to Stumble this post, or share it on Facebook, if you liked it!><br /><!-- AddThis Button END -->< /><div><a href=""><img style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px" alt="To Love, Honor and Vacuum" src="" /></a></div><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday: When You Don't Speak Each Other's Language<a href=""><img id="BLOGGER_PHOTO_ID_5350874254551334226" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a> Sometimes husbands and wives just don't see eye to eye.<br /><br />I'm a little distracted today, and so it's hard to write a Wifey Wednesday post. But let me try and let you in on what's going on in my head today.<br /><br />To make a long story short, a woman from our homeschooling group has just been diagnosed with a very rare terminal condition. She likely doesn't have long to live, and she has a 10-year-old daughter for whom she has always been the primary caregiver. To make things worse, she's in hospital an hour away from here, so people aren't able to visit her or bring her daughter to her. So she's lying there, alone in the hospital, knowing she's dying. I just have a hard time even getting my head around how she must feel.<br /><br />And she and her husband really don't have any family, and not a lot of friends. So I suppose I feel responsible in some way, even though we're not close.<br /><br />I was talking to Keith about this last night, and the talk did not go well. He's a doctor, so I always figure that he can figure out how to talk to doctors and get things done in the system better than the rest of us plebes. But I think he felt it was an attack, "why haven't you done anything for this poor woman?" Needless to say we were each a little annoyed with each other.<br /><br />Now this shall pass. I know that once he gets home from work we'll talk and it will be fine. It really isn't a big deal. (Although I'm still quite sidetracked trying to figure out what I can do for this woman, other than going to visit her tomorrow). Often, though, our disagreements with our husbands happen not really because we see the issues differently; they happen because we have different approaches to life in general. So I thought today, for Wifey Wednesday, I'd make a chart of some of the primary ways that men and women think and act differently. And then you, when you participate, can make the list longer, either in the comments or on your blog!<br /><br />Here goes:<br /><br />1. <strong><span style="color:#000066;">Men think we're trying to get them to fix a problem</span></strong>, when really we want to brainstorm about a problem or just discuss a problem. That's why Keith got defensive. When we mention a problem, they figure we're angry that they haven't done something about it yet. They need to feel competent; if we say things the wrong way, we undermine this and set them off.<br /><br />2. <strong><span style="color:#000066;">Men tend to focus on one thing at a time</span></strong>, while women are always multi-tasking. Even when I'm working, I'm thinking about what my daughters are doing and how they're feeling. Men often seem oblivious to the reactions of family members to their actions, not because they don't care, but because they weren't thinking of that right now. Instead of attacking them in these cases, it's often better to ask a question to help them focus differently. ("What do you think we can do to help Rebecca out of her funk?" for instance).<br /><br />3. <strong><span style="color:#000066;">Men are quick to get in the mood</span></strong>; we need to be romanced. Thus, men often assume we don't want to make love, so they roll over and get grumpy. I keep telling my husband, "try to seduce me!" I'm not in the mood right now, but you could probably get me there. It's just not on the radar screen. If it's not on their radar screen, they know it can't happen. But they forget that we're not usually in the mood until we start. We don't work like them. So we could, potentially, be warmed up if they tried.<br /><br />4. <strong><span style="color:#000066;">Men tend to relate to others on a side-to-side basis</span></strong>. We relate on a face-to-face basis. Men do things with others, whether it's other guys, or their children. We like talking to others. One is not necessarily better than the other. If we want to get closer to our husbands, then, maybe the answer isn't to try to get them to talk and act like us; it's to find things that we can do, side by side.<br /><br />5. In the end, <strong><span style="color:#000066;">men need to feel like we think they're competent</span></strong> and can manage life. We need to feel like we are cherished. We have different primary needs. You may feel like you're meeting his if you're hugging him all the time and telling him you love him, but if you're simultaneously questioning him about his job, how he handles the kids, and the finances, he'll feel undermined.<br /><br />So there's my list. Anything jump out at you? Anything you'd like to add?<br /><br /><em><span style="color:#663366;"><strong>And don't forget: in terms of sex, if you feel like you're not relating to your husband because there are too many differences, I lay them out in my book </strong></span></em><a href=""><em><span style="color:#663366;"><strong>Honey, I Don't Have a Headache Tonight</strong></span></em></a><em><span style="color:#663366;"><strong>, which is on special this month. And you can pick up an </strong></span></em><a href=""><em><span style="color:#663366;"><strong>audio download </strong></span></em></a><em><span style="color:#663366;"><strong>of a hilarious talk I gave on the same subject here!<br /></strong></span></em><br />To participate in Wifey Wednesday, either leave a comment, or preferably write your own blog post, link it to here, and then come back here and enter your URL in the Mr. Linky.<br /><br />Thank you!<br /><br /><div><a href="" target="_blank"><img src="" border="0" /></a><br /></div><br /><br /><div>: Make Your Hubby Feel Appreciated<a href=""><img id="BLOGGER_PHOTO_ID_5348255078995622050" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><strong><em><span style="color:#330033;">(Announcement: To go with Wifey Wednesday, it's all marriage, all intimacy, all the time at my <a href="">Livestream channel</a>! I've posted all my marriage videos up there right now! Go on over and <a href="">have a peak</a>!)</span></em></strong><br /><br />I've written a lot in these pages about how to make your <a href="">husband feel appreciated</a>. We've talked about gratitude, about <a href="">encouragement</a>, and about, of course, <a href="">sex</a>.<br /><br />But with Father's Day coming up this weekend, I thought I'd let a guy speak for a change. So today, here's Mark Webb talking about how to say thank you to your hubby:<br /><br /><br /><p><strong><span style="color:#663366;">Make Your Man Feel Appreciated<br /></span></strong>By <a href="">Mark Webb</a></p><p>"God gave you a gift of 86,400 seconds today. Have you used one to say, "thank you."?"~ William A. Ward</p.<br /><br /.<br /><br /.<br /><br />Here are some ways to let your man know how much you appreciate him:<br /><br />1) <strong><span style="color:#000066;">Greet him with enthusiasm</span></strong>. Light your face and his with a smile. Be glad to see him.<br /><br />2) <strong><span style="color:#000066;">Build him up in front of others</span></strong>. Refuse to say anything negative about him to anyone else. Look for opportunities to sing his praises to his friends and relatives as well as yours.<br /><br />3) <strong><span style="color:#000066;">Tell him the things you admire and appreciate about him</span></strong>. Men love to hear how great they are. This also serves as positive reinforcement which in turn will promote an even better man.<br /><br />Point out how hardworking he is. Thank him for being thoughtful and patient, and a good listener. You will be surprised at how much better he will become.<br /><br />4) <strong><span style="color:#000066;">Be playful</span></strong>. Draw out his fun side. Once couples get established in the relationship, they tend to forget how playful and goofy they can be. Being playful will keep you young.<br /><br />5) <strong><span style="color:#000066;">Ease up on the guilt trips</span></strong>.!"<br /><br />6) <strong><span style="color:#000066;">Make a big to-do when he achieves something</span></strong>. Fix him his favorite meal or a special dessert. Put the children to bed early and break out the candles. Use your imagination. The bigger the better.<br /><br />7) <strong><span style="color:#000066;">Tell him how much you love him</span></strong>. Not with a card. Most men are not into receiving cards. Tell him face to face. A sincere statement can penetrate the toughest of hearts.<br /><br />8) <strong><span style="color:#000066;">Thank him for providing for you and your children</span></strong>. I know he is supposed to do this, but a wise woman will never take this for granted. Men equate long hours of hard work to a show of love. Receive this with a thank you.<br /><br />9) <strong><span style="color:#000066;">Thank him for supporting your pursuits</span></strong>. Behind every great man is a supportive woman. The reverse is also true.<br /><br />10) <strong><span style="color:#000066;">If you want to see a huge difference in your man, listen to him</span></strong>. Listen to his goals, his dreams and his frustrations. Give him a chance to talk without correcting him or getting defensive. Let him vent without taking it personally. A man will give his right arm for this one.<br /><br /><em><span style="font-size:85%;">Mark Webb is the author of How To Be A Great Partner and founder of Partner Focused Relationships™. Sign up for Mark Webb's "Relationship Strategies" Ezine ($100 Value). Just visit his website at </span></em><a href="" target="_new"><em><span style="font-size:85%;"></span></em></a><em><span style="font-size:85%;"> or </span></em><a href="" target="_new"><em><span style="font-size:85%;"></span></em></a><em><span style="font-size:85%;"><br /></span></em><br /.<br /><br /, <a href="">Honey, I Don't Have a Headache Tonight</a>, addresses just these issues, and it's on sale for Father's Day!)<br /><br />That doesn't mean, of course, that if he's into pornography you do weird things with him. I'm not talking about that, and <a href="">I've addressed that problem before</a>. I just mean that in most relationships, we could improve them a ton if we began to realize that men aren't sick for wanting sex so much; that's the way they were made. And besides, when you make love, you sleep better anyway!<br /><br /!<br /><br /><br /><a href=""><img style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px" alt="To Love, Honor and Vacuum" src="" /></a><br /><br /><b><i><span style="font-size:85%;">Subscribe to my feed!</span></b></i><br /><br /><br /><br /><a href="" target="_blank"><img src="" border="0" /></a><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday: A Winner! And a Way....<div><a href=""><img id="BLOGGER_PHOTO_ID_5345672233154986770" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a> <a href=""><img id="BLOGGER_PHOTO_ID_5345672649019268946" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 120px; CURSOR: hand; HEIGHT: 180px" alt="" src="" border="0" /></a>All week I've been running a contest to win a copy of my book, <a href="">Honey, I Don't Have a Headache Tonight: Help for women who want to feel more in the mood</a>. A bunch of you entered through Twitter, Facebook, and blogs, and I'm so excited about all the new people I have to discover once I wade through the entries!</div><br /><div>But in the meantime, the winner is....Victoria R.! I've already emailed her, so Congratulations, Victoria! She advertised the contest on Facebook.</div><br /><div>For the rest of you, remember that Honey, I Don't Have a Headache Tonight is <a href="">on special right now</a>, 25% off, and you can get it in time for Father's Day! Make his Father's Day something to remember! (Or get it through Amazon here:)</div><br /><br /><p align="center"><iframe style="WIDTH: 120px; HEIGHT: 240px" marginwidth="0" marginheight="0" src="" frameborder="0" scrolling="no"></iframe></p><div><br /></div><br /><div>Now, I want to share a little bit of wisdom that is in this book, as well as in <a href="">To Love, Honor and Vacuum</a>. Last week we started talking about how to get husbands more involved with the children, and some of you left comments saying you had basically given up. He wasn't interested, and there wasn't anything you could do.<br /><br />I found that really heartbreaking, but I also know that this is probably a very common feeling--probably MORE common than women who feel that their husbands are involved with the kids. Having a family that functions well is not that common an occurrence these days.<br /><br />So what can we do to form a family that is cohesive, and where everyone does enjoy being with each other?<br /><br />First, I think so much depends on how we organize after dinner times. If you make dinner, but then leave it up to everyone how they will spend their evening, chances are they will scatter (or he will, anyway), and family time won't happen. If, instead, you make plans so that EVERYONE will do something together, then chances are it WILL happen.<br /><br />Let's look at a scenario. You make dinner haphazardly, and try to get everyone to the table. Everyone arrives one at a time, and some of them start eating without waiting for others. As soon as people are done, they get up. Your husband goes and watches TV. Your little ones go and play video games, except for the smallest, who clings to your leg. You start cleaning up. The whole episode took about 8 minutes, 6 of which you spent getting up and down fetching things for the kids.<br /><br />Now, let's look at it a different way. Dinner is ready. You call one of your kids, who is over 5, to set the table. You put candles on the table. You use nice napkins. You call everyone together, and don't let them eat until you're all seated. You sing grace, or say grace, or do something fun to start the meal (holding hands is good, because it prevents others from digging in). Now dinner has an atmosphere, so it's an event, not just something that one eats.<br /><br />While you're eating, you have a trivia book that you ask your oldest one to read from, or a joke book for your 8-year-old, or a list of conversation starters for older kids. You play a game, like Stump the Dad, where everyone has to think of a question he doesn't know, or you have to make him laugh. You talk about your day, or homework. Everyone has to share one thing that was good about the day, and one thing they hated (even dad).<br /><br />Dinner is now something where people connect, and you can start this with kids as young as toddlers. Dad can even get involved. Now you're bonding.<br /><br />You have a schedule as to who does the dishes, who puts the dishes in the dishwasher, and who clears the table. Everyone pitches in (including Dad). Those that aren't on the schedule are excused, but the others work. After dinner you play a game, or go for a walk together, or go kick the soccer ball around outside. You ALL do this. It becomes an evening routine.<br /><br />What you'll find is that if dinner is more of an event, and the kids are involved in cleaning up, and you go outside after dinner, Dad will start developing more of a relationship with the kids. But notice that you're not making him do anything on his own; you're just organizing the family so that you all spend time together.<br /><br />This won't happen overnight. You may have to push through their resentment or their complaints. But if you want a different sort of family life, don't let them ruin it for you! You're the mom. You set the tone for the house. You are not helpless! Talk to your husband about it, and tell him that kids do better in school when they eat dinner together and talk at the dinner table. Tell him it's important to you that you all get exercise. Show him that you're working for everyone's best interests, and make it fun! Don't get mad at people if they don't jump on the bandwagon at first; keep pushing, and they'll join in.<br /><br />Deep down, people want to connect. They want to do family things. But if it hasn't been a habit, there may be resistance. But that doesn't mean they won't enjoy it, or won't do it eventually.<br /><br />So tell your husband what's important to you, and set it up. Don't wait for him to do it. Make dinner an event, and plan something together afterwards, and you'll find your husband laughing more with the children.<br /><br /><strong><span style="color:#663366;">Now it's your turn. How do you make family times happen when family doesn't always want to? How do you encourage your husband to be with the family? I want to hear from you! Just go to your own blog and write a post, copy the picture from the top of this post, and then come back and enter your URL in the Mr. Linky!<br /></span></strong><br />Or, if you don't have a blog, just leave some comments! We'd love to hear how you get your family together!<br /><br /><div><a href="" target="_blank"><img src="" border="0" /></a></div><br /><div><!--: Letting Men Be Men<a href=""><img id="BLOGGER_PHOTO_ID_5343072372741548898" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a>Hello, everybody! It's time to talk marriage!<br /><br />First, thanks for the replies on my post this week about <a href="">how to get husbands to care for their children</a>. Keep commenting over <a href="">here</a>! I'm going to turn it into next week's Wifey Wednesday!<br /><br /.<br /><br /.<br />!<br /><br />But I wanted him to go. We have lots of time together, he and I. We prioritize it. But sometimes guys just need to be with other guys. And we don't always let them. We get upset because it takes time away from us, or from the kids.<br /><br /.<br /><br /!<br /><br />But men don't have that as much. Apparently less than 10% of men have a real, male friend that they could actually bare their souls to. Many men have acquaintances that they do things with, but they don't actually talk.<br /><br />And the only way to get to that level of relationship is if they start to spend time together and act like men.<br /><br /><a href=""><img id="BLOGGER_PHOTO_ID_5343075696043033010" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 120px; CURSOR: hand; HEIGHT: 180px" alt="" src="" border="0" /></a>When I wrote my book, <a href="">Honey, I Don't Have a Headache Tonight</a>,.<br /><br /.<br /><br /.<br /><br />And we need to let him be a man in the way that he relates to the kids, too. Don't expect him to parent the way you do! You are not necessarily the expert; kids need both parents.<br /><br /?<br /><br /?<br /><br /.<br /><br /><strong><em><span style="color:#663366;">If you're wondering how to walk this line, or how to help him feel masculine, I have lots more in </span></em></strong><a href=""><strong><em><span style="color:#663366;">Honey, I Don't Have a Headache Tonight</span></em></strong></a><strong><em><span style="color:#663366;">! And best of all, it's on </span></em></strong><a href=""><strong><em><span style="color:#663366;">special for June</span></em></strong></a><strong><em><span style="color:#663366;">! I figured I'd put it on for Father's Day: it's a gift YOU will read, and HE will reap the benefits of! Find out more </span></em></strong><a href=""><strong><em><span style="color:#663366;">here</span></em></strong></a><strong><em><span style="color:#663366;">! </span></em></strong><br /><strong><em><span style="color:#663366;"></span></em></strong><br /><br /><strong><em><span style="color:#663366;">I also have a 45-minute hilarious and practical talk I gave on the same subject for sale this month, too. </span></em></strong><a href=""><strong><em><span style="color:#663366;">Don't miss it</span></em></strong></a><strong><em><span style="color:#663366;">! I know it will change your marriage!</span></em></strong><br /><br />Now, let's talk about masculinity and femininity and how to help him be a man. Unfortunately, Mr. Linky isn't working right now, so just leave the link to your Wifey Wednesday post in the comments! Let's talk about how to let guys be guys (and how to put reasonable limits on it, too!). To participate, just copy the picture at the top of this post, and write a blog post on your own blog about marriage. Then come back here and leave your link!<br /><br /><div>: Looking Good for Him<a href=""><img id="BLOGGER_PHOTO_ID_5340470027079484962" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a> <div>Yesterday I asked a question on this blog: <a href="">Does appearance matter</a>?<br /><br />You see, I am torn about the issue. On the one hand, I think women berate themselves far too much on image issues. They say that weight is the number one thing women feel guilty about, as if God is more concerned with our waistlines than He is our hearts. And it is also definitely true that our insides matter more than our outsides. A truly beautiful woman is one who is gentle in spirit, true in character, loving in outlook. These things are biblical, and they come first.<br /><br />But I'm uncomfortable with leaving it like that, because I know that when it comes to men, looks matter. So as a wife, what is our responsibility to look good for our husbands?<br /><br />I was thrilled with all the comments I received, and I want to summarize my thinking on the issue, with some help from some of the commenters.<br /><br />First, I think the issue is not what we look like but the effort we put in. Only about 1% of us will ever be able to look anything like supermodels. But as anyone who has ever watched the show What Not to Wear knows, all of us, regardless of body type or features, can make an effort to look attractive. We don't need to be Jennifer Aniston, but we can take pride in ourselves.<br /><br />Here's a video that I did a while ago, if you haven't seen it yet, about how much women berate ourselves for our bodies. The point, again, is that we can't be Barbies. we don't want to do that. But we do want to make an effort to show our husbands that we care. I think Cassandra, in the comments, summed it up well. She said that early in the marriage she asked her husband these questions:<br /><br /><blockquote>1. What can I do that will bring joy to your heart?<br /><br />2. What can I do that will absolutely delight you?<br /><br />3. I know I don't have to do any of this, but, if I have some extra time, are there desires that you have that I can attend to? </blockquote><br /><br />And that's her motivation for trying to look nice for him. It isn't because she's afraid of him straying. It isn't because she's shallow. It's just because she wants to present herself to him in a way that he will like, and feel special. And men are visual creatures, so appealing to his visual senses is important.<br /><br />I think that's what it's all about. Do you make your husband feel special? Do you let him know by what you do that you're looking forward to seeing him again?<br /><br />Carrie intimated about this when she said this:<br /><br /><blockquote>He likes to see my eyes light up, for me to indicate he's still the desire of my heart after all these year...those are among the things he sees as beautiful, even when I'm in my favorite OLD cotton nightgown, face scrubbed and hair pulled back in a braid.</blockquote><br /><br />The important thing for her husband when he comes home is that Carrie looks like she's glad to see him. And let's be honest, here, women: many times we don't look it. Especially when we have small children, it's easy to get into the "you're home now, so you take the kids so I can finally get something done" mode. We don't delight in being with him again; we just push things on him as soon as he's in the door.<br /><br />Part of being a good wife, then, I think, is to show your husband you love him and are eager to see him in a way that speaks to him. And taking the time in your very busy day to look presentable is one way to do that. Another Cassandra said this about her husband:<br /><br /><blockquote>He says that men feel betrayed if they marry one thing (makeup, nice clothes, nice body) and wind up with something else 20 years later (way larger body, no makeup, sloppy clothes) that by caring for ourselves, it says volumes to them...that would never have occured to me unless he said it first...then i read it in a book later and thought, wow, guess that's across the board for most guys...</blockquote><br /><br />I think that's true, too. Now men don't always care for themselves, either. Many of us are married to guys who have gained 50 pounds since the wedding, and we wish they'd lose it, too. But marriage is not about only acting loving when he first does something nice. It's about taking the initiative.<br /><br />So here's your challenge this week: can you take five minutes before you see your husband again, either because he's arriving home from work or because you are, and make yourself look nice for him? Can you put the effort in to show him that you were looking forward to him coming home, and then, when he gets in the door, can you show him that? Even if he doesn't respond right away? Make the effort. And then, over the next few weeks, see what happens!<br /><br /><strong><em><span style="color:#663366;">Do you have your own marriage advice for us? Or would you like to respond to this post? Why not write your own Wifey Wednesday post? Just copy the picture above by right clicking it and saving it, and then go to your own blog and write your own post. Come on back here and enter the post's URL in the Mr. Linky (if it works, it's being temperamental) or in the ocmments!</span></em></strong><br /><br /><strong><span style="color:#000066;">Here are other marriage resources you'll enjoy:<br /></span></strong><a href="">Honey, I Don't Have a Headache Tonight</a>: Help for women who want to feel more in the mood (the book)<br /><a href="">Honey, I Don't Have a Headache Tonight</a> (the talk as an audio download)</div><br />><br /><div><script type="text/javascript" src=""></script><br /></div><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday: What It Means to Become One<a href=""><img id="BLOGGER_PHOTO_ID_5337871939432622914" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a> Last week, on Wifey Wednesday, we were talking about things <a href="">we wished we had known before we were married</a>. And my guest, Christine Pembleton, said that she wished that she had known that you wouldn't be "one" right away. That takes time.<br /><br />Her statement started a discussion in the comments section, since as one woman correctly pointed out, spiritually we are automatically one upon marriage, based on the verse:<br /><br /><blockquote>And the man shall leave his father and mother, and cleave to his wife, and they shall become one flesh.</blockquote><br />Absolutely. They are one. But that doesn't mean that we FEEL like we're one, which is what Christine was trying to say. So I want to take up that discussion today and get it going again.<br /><br />Before we are married, we only have ourselves to worry about. We don't have to consider another's feelings; we're all bent on making decisions that will make ME happy. I am the focus of my life.<br /><br />At marriage, that feeling naturally continues. When we're first married, we start to wonder, "is he making me happy?", or "is he treating me well?", "is he acting like a good husband should?". We're new at this, so it's only natural that we should question whether he's doing what he's supposed to. After all, we have images of what being the proper wife is, and we're doing that, but is he holding up his end of the bargain?<br /><br />We're focused on what he is doing, not what we are doing, because we're used to giving ourselves a pass. We can always find reasons why it was okay for us not to be giving in that particular situation. We can always justify ourselves. But our husbands are a different matter.<br /><br />The other issue, I think, is a gender one. Deep inside we want him to make the first move. So if we feel like he's not treating us appropriately, we may withdraw and wait for him to make it up. And we think that's okay because he's supposed to treat us better than that.<br /><br />What we don't see is what he is feeling. Chances are he's just as disillusioned as we are, because he had expectations going into the marriage, too, that aren't being met. And while this situation is quite typical for many newly married couples, whether or not it keeps going on is up to us. Because for many couples, this is the constant state. For decades this is how they relate to each other: judgment, justification, resentment, withholding. It's all about my feelings and my rights.<br /><br />And so we face a choice. Our husbands will always disappoint us because they are not US. They don't have the same opinions or values or expectations, so they can never live up to ours. So what are we going to do: are we going to continue this cycle, or are we going to become one?<br /><br />The ball, I think, is in your court. Don't wait for your husband to act. But here is the key to turning on this "oneness" part of marriage: you have to.<br /><br />He doesn't need to justify his feelings; they are his feelings. And now that you are married, they should matter to you just as much as yours do. It matters when he's upset. Don't try to get him to justify it or talk him out it; be concerned about it. Because when he's upset, part of you is upset. It matters if he feels lonely or frustrated, because that means you are lonely and frustrated.<br /><br />If you can start putting as much weight on his feelings as you do yours, or even 50% as much weight on his feelings, you'll likely find that your marriage will improve exponentially, because you're reaching out.<br /><br />We women are very good at DOING things for other people, but we often keep our hearts in reserve. We may do all the laundry, and cook him nice meals, but we do it on our terms, not his. Sometimes it's harder to feel than to do. And as a wife, his feelings and cares do matter.<br /><br />When you start valuing those, he's likely to reach out to you more. And as he reaches out to you, you are going to start feeling like one. It doesn't happen overnight. And I'm not saying you should <a href="">accept si</a>n, or <a href="">not confront him on things </a>that are important. I'm only saying that his viewpoint counts, and you need to give it the weight it deserves. Then, and only then, will you begin to feel like you're one.<br /><br />What about you? Do you feel like you're one in marriage? How did that happen? Write your own Wifey Wednesday post, and then come back here and leave your URL in the Mr. Linky, or leave a comment if you don't have a blog! Let's keep the discussion going!: What I Wish I Had Known Before I Was Married<p><a href=""><img id="BLOGGER_PHOTO_ID_5335275348361366770" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><br /><div><a href=""><img id="BLOGGER_PHOTO_ID_5335277641856578162" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 180px; CURSOR: hand; HEIGHT: 180px" alt="" src="" border="0" /></a>Today on Wifey Wednesday I have a special guest. Christine Pembleton is a mom, an author, and a wife, and her new book "<a href="">Lord, I'm Ready to Be a Wife</a>" is now ready, too! She's come by to answer some questions for us. While her book is directed at single women, I think many of us married women need a reality check and need to keep these vital principles in mind.<br /><br />So I asked her some questions, and she answered! I'm in purple, and she's in blue, because I like purple and it's my blog. Let's talk to Christine:<br /><br /><span style="color:#330033;"><span style="color:#993399;">Christine, what’s the biggest mistake that women make about their attitudes when they get married?</span><br /></span><br /><span style="color:#330099;">The biggest mistake a woman can make, in my opinion, is to expect to automatically become one with her husband after they've taken their wedding vows. Marital bliss is a process. And building a life together takes time. Married couples who have been married for 20 years are still working towards this.<br /></span><br /><span style="color:#993399;">I totally agree with this! When Keith and I speak at marriage conferences, we like to say that we've been married for 17 years, and happily married for 13. The first few were really tough. But knowing that you're sticking it out for the long haul gives you the energy to keep going!<br /><br />Okay, here's another one: I’ve heard it said that women get married to make themselves happy. Do you think this can backfire?<br /></span><br /><span style="color:#330099;">Sure this can backfire. Marriage can bring happiness to a person's life, but it can also bring heartache and disappointment. There is nothing in life that will make you happy 24-hours a day, but if we focus our need for joy to the Lord, He will be that source of unexplainable joy, through the most challenging situations of our lives, even our marriages. One note: marriage should not be miserable either. I definitely think there should be more happy moment than sad ones, but there will be tears. If you look to the Lord to help you through those times, you'll make it through them with peace.<br /></span><br /><span style="color:#993399;">What should we teach our children more to prepare them for marriage?<br /></span><br /><span style="color:#330099;">Sharing and compassion for another person's needs. Marriage really takes more compromise than people today realize. Knowing how to care for someone else's need, and to be selfless, will help any man or woman be more prepared for the requirements marriage brings to their lives.<br /></span><br /><span style="color:#993399;">I think having a sibling can be really helpful here! I grew up as an only child, and I had never really had to adjust to living with another person before. Seeing my own children negotiate whose turn it is to do something or whose space it is actually makes me smile, for while it seems like they're bickering, they're also learning how to share and work things out! I do think single children have a harder time with marriage, but that could just be my own bias.<br /><br />How do you think women should prepare for the physical aspects of marriage?<br /></span><br /><span style="color:#330099;">It all depends on the life a woman has lived before she's gotten married. If a woman has had a limited or non-existent sexual life before she's gotten married, it can take time to get into the mindset of being intimate with her husband each day or week. If she has been sexual, it might be difficult not to compare her husband to the other lovers she's had before. I definitely believe we as the Body of Christ should have forums for married men and women to openly share with unmarried people their experiences of building a sexual relationship. This would help them mentally prepare for that life as a married person.</span><br /><br /><span style="color:#993399;">Me, too! That's what I want Wifey Wednesday to be! I think we in the church don't really have good places to talk about sexual stuff in a healthy way, and I wish we did. So I try to open up here, and let the chips fall where they may. I think we need to ask questions and ask for help.<br /><br />Do you think we value marriage TOO much? Do women sometimes seek their fulfillment in their husbands rather than in God?<br /></span><br /><span style="color:#330099;">In the 21st century, we don't value marriage enough. Yes, women can seek fulfillment in their husbands rather than God but it only takes a few days before you realize that's not going to happen. I believe the bigger problem is that few married couples are really experiencing the benefits of oneness in marriage, and so very few people really understand how beautiful marriage can be, when you've build a marriage over time, and have come to understand your spouse. Like our relationship with God, getting to know a husband takes years, trust, and vulnerability. I believe the fruit a healthy marriage includes strength, understanding, encouragement, and exponential increase in one's ability to prosper in soul, spirit and body. Marriage does make our lives better, or at least it should. God is our source of purpose, and marriage provides us an opportunity to exercise that purpose, as we care for the life of our spouse, as unto the Lord.<br /></span><br />Great answer! Thanks Christine! And you can find out more about her book right <a href="">here</a>. </p><p>Now, why don't you join the discussion? What one piece of advice do you wish women had given you before you were married? What's one thing that really surprised you? Leave your answer in the comments, or write your own blog post about it and join Wifey Wednesday! Just come on back here and leave the URL for your post in the Mr. Linky!<br /></p></div><br /><br /><div><script type="text/javascript" src=""></script><br /></div><br /><br /><div>: The Building Blocks<a href=""><img id="BLOGGER_PHOTO_ID_5332688970989604194" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><div></div><div></div><div>So many movies today have everything backwards. The couple sleeps together, and then they decide if they want to be together. They start hanging out to see if they really click. In other words, the sex comes first. The relationship is built on sex.<br /><br />In reality, sex is a reflection of other parts of your relationship. It isn't the base. You cannot build a relationship on sex. You need companionship, spiritual intimacy, and trust first. <br /><br />So if your sex life isn't stellar, it probably isn't because of sex. It's probably a sign that there's something wrong with other parts of your relationship.<br /><br />And in the same vein, if you want your sex life to improve, you should probably concentrate on other things first. <br /><br />Now that's the opposite of what most advice in secular bookstores will tell you. They'll try to get you to try the latest sex toys, or the latest techniques, or whatever. Don't. That's not the point. What you need to do instead is build the other parts of your relationship. Work on your friendship, so that you feel companionable, and want to be together. Connect with each other on an emotional basis throughout the day and throughout the week. But most of all, work on your spiritual intimacy.<br /><br />Spiritual intimacy and sexual intimacy are very closely linked. Often the times I feel the most amorous towards my husband are after we've prayed together. There is something about coming to God together that makes you want to really connect in other ways. And yes, I'm being serious! I know it's hard to think about God and sex in the same sentence, but He did make it and He does know what you're doing. So you don't have to be embarrassed!<br /><br />Anyway, I think this has repercussions for how we handle sexual differences and difficulties. Sex is never the cause of anything; it is only the reflection of other problems. If you want to rebuild your relationship, don't focus on anything sexual. Focus instead on the spiritual. <br /><br />Pray with your husband. If he doesn't want to pray with you, then at night, while you're lying in bed, put a hand on his head and whisper prayers. Read a Psalm out loud before you go to sleep. Read Song of Solomon together. <br /><br />And if your problem in your marriage is that your husband seems distant to you in every way, work on your own relationship with God, too. You grow close to God, and go to Him with your very legitimate needs for sexual fulfillment and intimacy, and He will help you with those needs. And your husband will likely see the difference.<br /><br />I truly believe the best thing a couple can do for their sex life is to do a Bible study together. I know it sounds insane, but I'm speaking from experience.<br /><br />So what do you think? How do you build your spiritual intimacy, especially with a husband who doesn't feel like being a spiritual leader? I'd really like your insights!<br /><br />Unfortunately, Mr. Linky isn't being reliable at the moment, so we'll have to leave links in the comments section. But if you want to participate in Wifey Wednesday, just write your own post on your blog, link back to here, and then come on over and write in the comments the link to your post. And then you'll build your own blog traffic!<br /><br /><strong><em><span style="color:#330033;"></span></em></strong> </div><div><strong><em><span style="color:#330033;">Need more resources for your marriage? Here are some you may find helpful:</span></em></strong></div><div> </div><div><a href="">Light My Fire:</a> Audio download on how to enhance the romance quotient in your marriage</div><div><a href="">Love Coupons: Increase the passion with these (non X-rated) coupons you can give your husband!</a></div><div><a href="">Honey, I Don't Have a Headache Tonight: Help for women who want to feel more in the mood<br /></a><!--: Complaint Free Week<a href=""><img id="BLOGGER_PHOTO_ID_5327485783630799314" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><br />This is <a href="" target="_blank">complaint free week</a>, so let's talk about complaining in marriage!<br /><br />What do you do when you're unhappy about something in the marriage? How do you bring it up in a constructive way?<br /><br />The problem many of us have, I believe, is that we either nag our husbands or we sit in stony silence. Neither is productive. I believe firmly that we must accept our husbands as they are. We must love them as they are, in the same way we love our children unconditionally. But that doesn't mean we accept everything they do. And if there is something that is really bothering you, how do you bring it up in a way that works towards a solution?<br /><br />Too often we complain to our husbands. That's going to backfire, baby. Men's biggest need, you see, is to feel competent. They want to know that we think they are capable of providing for the family and being a good father and husband. When we start judging their performance, they feel undermined, and they can retreat. So complaining not only is mean; it's also counterproductive.<br /><br />Here's what I would suggest:<br /><br />1. Before saying anything, check your heart. Don't do it out of anger for him; do it out of concern for the relationship.<br /><br />2. When you do talk to him, own the problem. Don't say, "you make me so mad when you...". Say, "I feel uncomfortable when you..." It's a little thing, but then you're claiming the problem. And then together you can work on a solution.<br /><br />3. Wait until you're both relaxed to bring it up. Having a weekly date night where you just connect and talk about the family and relationship is a great way to deal with some of these issues. If he doesn't seem excited about that idea, then you make it exciting! Feed the kids dinner first, and save your dinner with your husband until 8:00 or later after they go to bed. Make it into something that looks fun!<br /><br />Those are tips about the timing and the way to bring something up. But let's look at some other tips on how to avoid problems in the first place, or minimize those that are already there.<br /><br />I believe most problems in marriages, from sex to parenting to money, stem from the fact that the couple isn't connecting either on a friendship level or on a spiritual level. In other words, if you want to connect better sexually, work on the other two fist. So here are some more tips:<br /><br />1. Be your hubby's friend. Find things you can do together that you enjoy. If you hate that he spends so much time at the computer or watching TV, then come up with other things that the family can do that are fun. Take a walk. Take up jogging. Play soccer in the park. <a href="" target="_blank">Go biking</a>. Whatever. Just do stuff together, and then you're more likely to laugh together.<br /><br />2. Connect on a spiritual level. If he isn't praying with you, you can take the initiative and pray together before bed. Read the Psalms before you go to sleep, or even better, Song of Solomon. When you connect spiritually, a lot of the other problems disappear.<br /><br />That's it! Tips on how to stop complaining and do something constructive in your marriage. Build up, don't break down.<br /><br /><strong><span style="color:#000066;">And so we're on to Assignment 2 in Complaint Free Week:</span></strong> Find a way to carve out time in your marriage to talk about the relationship, so you won't feel so inclined to complain. Get creative! Make it fun! But make it regular. Think today about how you can do that in a way that he will enjoy it, too.<br /><br /><span style="color:#330033;"><strong>I can't put in a Mr. Linky because my blog can only display one at a time, and I want to leave the one for Complaint Free Week up. So if you have some marriage advice, we still want to hear it! But you'll have to put your link in the comments. Thanks so much! </strong></span><br /><br /><strong><em><span style="color:#663366;">My book, <a href="" target="_blank">To Love, Honor and Vacuum</a>, has a whole chapter on how to talk to your husband without nagging or complaining. It's a great one to check your attitude! And don't forget to click on Sheila's Store (just to your left). I've got the books I've written, plus a ton of other picks that will help your marriage!</span><br />< He Makes Me Feel Safe<a href=""><img id="BLOGGER_PHOTO_ID_5330084895061865282" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br />Usually in Wifey Wednesdays we talk problems. I name a common problem in a marriage, and then offer a possible solution.<br /><br />Today I want to do something different. Tell me what you love about being married! Tell me how he makes you feel safe. Tell me how he helps you to share the burden.<br /><br />I have a dear friend whose marriage is falling apart, and it's not primarily her fault. I won't go into the details, but you can trust me. Last week she had a big health scare, and she had to walk through it alone.<br /><br />It just reminded me of some of the neat things about marriage. Even if your marriage isn't stellar; even if you're sometimes aggravated; even if you wonder if you're ever going to feel truly loved and accepted, I hope we can all agree that there are some wonderful things about being married. Even if one is that we don't have to walk through life alone.<br /><br />I know many of you struggle, but today let's turn our hearts to gratitude. What do you appreciate about being able to share the load? What do you like most about having someone to lean on?<br /><br />For me, I just like someone to talk to. Even if it's just while we lay in bed at night, or while I'm getting ready in the morning and he's in the shower, I like having someone who cares about my day and whom I can share frustrations with. It's a little thing, but it makes me feel wonderful to know that there is someone else who knows what's on my heart, who knows what's on my plate, and who cares. I'm not carrying it all alone.<br /><br /><span style="color:#330033;"><em><em><strong>What about you? Why not participate in Wifey Wednesday today? Just write your own post, put my Wifey Wednesday picture up on top of it, and then come on back here and enter the URL of your post in the Mr. Linky. Or you can just leave a comment, if you don't have your own blog! But let's talk gratitude today!</strong></em></em><br /></span><br />This week I'm also introducing people to me a little bit more, and one of the things I want to tell you about is some of the great resources I have. I speak quite a bit to women's groups and marriage groups, and many of those talks are <a href="">available for download</a>. Today, though, can I make a recommendation? If you and your husband are stuck in a rut, why not listen to our humorous "Light My Fire" talk that Keith and I gave together? It's all about how to reignite romance in your marriage. Download it <a href="">here</a>.: Made for Each Other<a href=""><img id="BLOGGER_PHOTO_ID_5324888317302898786" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><br />Hello, everyone! And happy Wednesday!<br /><br />This has been an exciting week at my house. My husband turned 40 yesterday, and on Saturday I threw him a huge surprise birthday party, complete with square dancing. Sounds geeky, but boy was it fun. My sister-in-law, who is not geeky at all, said that she had the time of her life.<br /><br />Because we threw the big bash on Saturday we didn't do much yesterday on his actual birthday. It was more low-key, and we just talked. And it made me think of this column that I wrote a while back, which I'm going to publish here. I said to Keith yesterday that even though we're getting older, I'd rather be 40 than 30. We're closer now than we were then. We're becoming more like each other. We fit better. And in this column, I explain why:<br /><br /><blockquote.<br /><br />Of course, Keith recently backed into a tree and shattered our van’s windshield, but since this was his one and only infraction in our whole marriage, we viewed it as an aberration rather than a pattern. So when he went to buy a new car this fall, he bought a standard. I can’t drive a standard. So I can’t drive his car. I’m still trying to figure out if there’s some hidden meaning there.<br /><br />Keith and I have other differences, too. Keith has the “all the lights in the house must be turned off if not needed” gene. I’m missing that one. His idea of a relaxing afternoon is to actually relax. I like taking energetic bike rides. He likes war movies. I like Jane Austen. We’re a strange pair.<br /><br />And yet, as celebrated our sixteenth anniversary just before Christmas, what most often occurs to me is how alike we’ve become. Who we are, I believe, is partly a function of who we grow to be as we walk, day to day, with those we love.<br / all.<br /><br /.<br /><br />Or take food. I crave sweets, but not fat or salt. Keith, on the other hand, once drank a cup of bacon grease because someone dared him..<br /><br /.<br /><br />Over the last sixteen.</blockquote><br /><br />So often we think that when our marriages don't work it means that we married the wrong person. And yet, I don't think there is a right person. I think you become the right person, the more you commit to each other and stick it out.<br /><br / Bubba," then our marriages will blossom.<br /><br />Next week I want to talk about specific strategies for that. But for today, I just want to leave you with this concept:<br /><br /><strong><em><span style="color:#330033;">Marriages don't succeed because we marry the right person. They succeed when we become the right person.</span></em></strong><br /><br /><strong><span style="color:#000099;">More resources that may help you with this:</span></strong><br /><a href="">Thoughts on the nature of change in marriage</a>, from To Love, Honor and Vacuum<br /><a href="">My podcast on change in marriage</a><br />My book, <a href="">To Love, Honor and Vacuum,</a> with lots on this very subject!<br /><br />Now, do any of you have any marriage thoughts you'd like to share? They can be a question, a suggestion, or an insight. Write your own Wifey Wednesday post! Just post it on your blog and come back over here and enter the URL of your post in the Mr. Linky. And copy the picture at the top of this post, too, to make your post pretty! We look forward to reading it.<br /><br /><div><!--: Watch What You Say<a href=""><img id="BLOGGER_PHOTO_ID_5322284394858765218" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><br />Many of us women marry the potential inside our husbands. We don't marry our husbands.<br /><br />We see what he can become if only he could see the light and be more like--ME!<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />But when we try to "fix" him, we often drive him away. And what are some of the ways we fix him?<br /><br />Watch what you say to your husbands. Do you nag? Do you tell him how he could shape up? Or do you simply teach him? So often we teach without realizing it.<br /><br / it, "you're not playing with him right." Do that everytime he plays with Johnny, and you could drive a wedge between them. Not just that, but you say, "I am the parent who really knows how the kids work." Not good for family relationships.<br /><br />And we do it in all kinds of other areas, too. Dishes. Fixing the house. Talking to friends. Jobs. We're always offering helpful suggestions.<br /><br />What's wrong with being helpful? It gives the impression that we don't think they're competent, and men's biggest need is to be seen as competent and capable.<br /><br /.<br /><br /.<br /><br /.<br /><br />No, he won't always do everything as well as you do. But you don't do everything as well as he does, either. Accept that, and instead appreciate him for what he does do. You'll find that attitude change makes a major difference in your marriage!<br /><br />In the book <a href="">To Love, Honor and Vacuum</a>, I have a whole chapter on how to watch how we talk to our husbands, and how we can say things in ways that push his buttons, without even realizing it. It's a <a href="">really helpful resource</a>:<br /><br /><p align="center"><iframe style="WIDTH: 120px; HEIGHT: 240px" marginwidth="0" marginheight="0" src="" frameborder="0" scrolling="no"></iframe></p><br /><br /><strong><em><span style="color:#663366;">Now, do you have any marriage advice you can share? Or any problems you'd like advice about? Just copy the picture at the top and write your own Wifey Wednesday post on your blog! Then come back here and enter your URL in the Mr. Linky. We'd love to hear from you!<br /></span><><!-- AddThis Button END --></div><div><a href=""><img style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; BORDER-LEFT: 0px; BORDER-BOTTOM: 0px" alt="To Love, Honor and Vacuum" src="" /></a></div><br /><br /><div><script src="" type="text/javascript"></script></div><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday: Some Sobering Thoughts<a href=""><img id="BLOGGER_PHOTO_ID_5319707550915163202" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><br />I write here every week on marriage. I talk at marriage conferences at marriage. I really think that the only way our country and our communities will be turned around is by families sticking it out and deciding to love each other. And that's my primary calling in this life: giving people the resources and encouragement to work on their marriage, while pointing them to the One who can help.<br /><br />But every now and then I know there are marriages that cannot survive in their current form, and I don't want people to think that I'm telling you that you have to stick to it, no matter what. I'm quite aware that for some people, that may not be a good or even godly decision. So I'd like to just address some of those really hard issues right now.<br /><br />If your husband is abusive towards you or the children, you have to get out. That doesn't mean the marriage is necessarily over; perhaps God can change him significantly and reconciliation in the future may be possible. But that would have to be a long road, after he had counseling, and had made major changes. And you would have to have partners who would hold him and you accountable to make sure it didn't happen again. I think this is the exception rather than the rule. Abusive husbands are dangerous, and to say that we should stay is just not right.<br /><br />I also had a friend who had to leave a marriage because her husband was addicted to gambling, and would gamble all their money away. She had no choice if she wanted to provide a stable upbringing for her children, where they could be assured of having money for food.<br /><br />Addictions of any kind are dangerous. Addictions to alcohol, drugs, or pornography can also destroy a marriage. And affairs are serious. If your husband has had affairs, or is a compulsive pornography user, you may have to get out.<br /><br />You are not, however, alone. God, I believe, is especially close to those who are broken hearted and betrayed, and He gives you strength you never knew you had. Leaving a relationship like this can be so difficult, especially as a Christian, because chances are you've been covering for him with everyone for years. The kids don't know there are problems; your parents don't know there are problems; your friends think everything is fine. And then you leave, and it's as if you've dropped a bomb. But if it's the right decision, you don't need to feel guilty. If God is leading you in that direction, He will help and He will pave the way.<br /><br />But separating yourself from your husband does not mean the marriage is necessarily over. Sometimes you need to take drastic action to help him see the consequences of his actions.<br /><br />The absolute best book on this is Love Must be Tough by James Dobson.<br /><br /><iframe style="WIDTH: 120px; HEIGHT: 240px" marginwidth="0" marginheight="0" src="" frameborder="0" scrolling="no"></iframe><br /><br />In it, he talks directly to spouses, and especially women, who want their marriages saved, but their husbands are destroying the marriage by their actions. And he shows them that staying in the marriage and the house, trying to woo him back and change his behaviour, will surely backfire. Instead, if the infraction is big enough, you have to take steps to protect yourself and your kids. And in taking these steps, you precipitate a crisis, making it more likely that he will address his issues.<br /><br />So let's keep this in perspective. If you're mad at your husband and he's been drunk once, that doesn't mean he's an alcoholic and you have to leave. If he was caught with pornography once, and he's agreed to parental controls on the computer, you don't necessarily have to get out. But if these things have been continuous, ongoing, and growing worse, you may have to take action.<br /><br />God wants marriages saved. But He doesn't want you abused or put in a dangerous situation. He doesn't want your kids hurt. And He doesn't want infidelity.<br /><br />I hope nobody reading this post needs Dobson's book, but I know there are some who do. My prayers are with you as you navigate this most difficult time in your life. And always remember, you are not alone.<br /><br />Have any marriage advice you want to share? Why not contribute to Wifey Wednesday? Go to your own blog, write a post, and then come back here and enter the URL in the Mr. Linky below!<br /><br /><div><script type="text/javascript" src=""></script><br /></div><br /><div>: Don't Hide Your Gifts Under a Bushel!<div><a href=""><img id="BLOGGER_PHOTO_ID_5317094940327626546" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><br />Last Friday I was on 100 Huntley Street, a Christian television program that airs across Canada and in parts of the U.S. Here's a picture from that show. I'm the one in the fuchsia blouse: </div><div><br /><img id="BLOGGER_PHOTO_ID_5317095098893577810" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 214px; TEXT-ALIGN: center" alt="" src="" border="0" /><br />Anyway, we were talking about "Gender or Giftedness"? The question was, "what should determine what gifts women exercise: their gender or their giftedness?" That's a loaded question. We didn't really get into roles in ministry so much as this idea that the division between men and women is really a result of the fall. And God equips women to do amazing things. Wherever we're planted, whether it's in our families, or in the workplace, or in the church, we need to exercise the gifts that God has given us. That may look different in different denominations, but God wants to use women.<br /><br />That got me thinking quite a bit about marriage, and that's what I want to talk about today: how gifts interact with marriage.<br /><br />A few years ago I was leading a women's Bible study where we were working our way through the book of Acts. We were looking at some of the women who were amazing teachers and leaders. And many of the women in my study said something along these lines, "I'd love to do more in my family. I'd love to have devotions after dinner, and memorize verses together, and serve together, but my husband won't take the initiative. So it doesn't get done."<br /><br />Now, for those of you who aren't Christian, bear with me for a moment, because I think what I'm going to say relates to all of us. But the point I want to make here is that many times we women use our husbands lack of interest as an excuse not to do important things in the family.<br /><br />My husband and I are both gifted teachers, but I'm better with smaller children than he is. To say that he has to be the one to tell stories about God--or anything--to the children would be silly. Most women are more effective prayer warriors than their husbands, according to surveys. To say that we can't pray for our families out loud unless our husbands lead it only hurts the family.<br /><br />I know some may disagree with me, but I truly don't think this is a matter of roles. God has called us to raise godly families. If our husbands are not helping in that endeavour, that does not get you off the hook. You have a brain. You have a mouth. You need to use them!<br /><br />And this doesn't only apply to spiritual matters. Let's say that you want to get the kids to stop watching so much television, but your husband doesn't really care. Or let's say that you want to get the kids exercising more, but he's not interested. Does that mean that you let the kids continue to be couch potatoes, even though you know that's bad for them?<br /><br />There is a balance, of course. If you take over all parenting responsibilities, leaving him with nothing, it's easy to shut him out. You certainly don't want to do that. You always want to leave room for him to join you. But don't abandon the project altogether simply because he's not on board. If it's important to do, it's important to do.<br /><br />So let's look at some strategies together.<br /><br />If you want to read Scripture with the kids, and he couldn't care less, then can you do it when he's not home? Can you carve out time right after the kids come home from school, or after breakfast before they go to school? Can you do memory verses in the morning? I know people say the best time is at the dinner table, but you also want the dinner time to be for your husband, too. So try to get creative!<br /><br />The other thought is that many men don't want to "do devotions" after dinner because it seems boring and they don't know how to lead it. I mean, what does "do devotions" mean, anyway? But there are some wonderful books and internet resources on family devotions. If you pick something like that up, and if it includes games and quizzes and even jokes you can read together, he may see that it's not a big deal. Get the book out in the middle of dinner and suggest you read it together. Start with a particularly fun one. And then suggest that you all take turns, so that your husband has his turn, too.<br /><br />And what about the television issue, or the exercise issue? Again, many men aren't on board because television is what they do after dinner. Why take that away? But isn't that the point? Nobody wants something TAKEN AWAY. It's much better to ADD. So if your husband wants to watch TV, and your kids want to play on the computer, and you want them to play outside, then instead of saying "shut off the TV", how about buying some second hand bikes and suggesting everyone go for a bike ride? Or buying a soccer ball and suggesting everyone head to a local park?<br /><br />You can take the initiative without setting down rules that your husband has to follow. You can change the family dynamic without turning it into a big production. Just do it. Don't hide behind your husband, saying, "well, since he doesn't want to do it, I can't". That's not true. If it's important, it's important. Use your brain power to figure out how to make the changes you want to see in your family as fun as possible for all concerned. And you just may find that they start to get on board--even your husband!<br /><br />Now, do you have any marriage advice you want to share? It can be about anything, but if you have any suggestions about how to get your husband on board to important family changes, I'd especially like to hear that! Just go to your own blog and write a Wifey Wednesday blog post! You can copy the picture at the top of this post and use it, too. Then come back here and enter your URL. Looking foward to reading it!<br /><br /><a href=""><img id="BLOGGER_PHOTO_ID_5317099151903161074" style="FLOAT: left; MARGIN: 0px 10px 10px 0px; WIDTH: 77px; CURSOR: hand; HEIGHT: 117px" alt="" src="" border="0" /></a><strong><em><span style="color:#663366;">I talk a lot about this issue of creating the right environment in our families in To Love, Honor and Vacuum: When you feel more like a maid than a wife and a mother. Find out more about that book </span></em></strong><a href=""><strong><em><span style="color:#663366;">here</span></em></strong></a><strong><em><span style="color:#663366;">.</span></em></strong><br /><br />: Carelessness is not an Option<a href=""><img id="BLOGGER_PHOTO_ID_5314319130431877938" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><br /><div>Does God make a difference in your marriage?</div><div></div><br /><div>Now, before you say, "Of course He does!", and murmur all the Christian platitudes, just take a step back for a moment and let me talk.</div><div></div><br /><div>The divorce rate among Christians in most parts of the country and in Canada is actually lower than the general population--significantly lower. Unfortunately, in the Bible belt in the U.S. it's a tad higher, which is the statistic that is often mentioned when we talk about Christians and marriage.</div><br /><div></div><div>So for most of us, God does make a difference.</div><br /><div></div><div>But our divorce rate is nowhere near 0. Just because it's not 30%, like the rest of the world (it's not 50%; that's a false statistic, too), doesn't mean that we should rejoice at 22% or even 18%. That's still high.</div><br /><div></div><div>And I'm extremely troubled by that. I see so many of my friends who go to church, and who honestly do believe, but God doesn't seem to come into their lives in other ways--what movies they watch, how they spend their time, how they spend their money, how they raise their kids. They've simply blended into the culture.</div><br /><div></div><div>I have to, in many ways. We all have. But my husband and I decided early in our marriage that we would be intentional. We would not let the culture take us over. While we're far from perfect (we sure could stand to pray a lot more than we do), we at least talk about it and wrestle with how to bring God into our marriage and our family.</div><br /><div></div><div>I had some really bad news this week. A couple I love dearly have split up. Now there are good reasons, though I'm not fully apprised of them, and in their situation this sounds like the prudent course. I won't elaborate more than that, but let me just say that sometimes separation is necessary.</div><div></div><br /><div>From the little I do know, though, it sounds like one partner in the marriage has let culture infiltrate too much into his/her thought processes, so much so that his/her morality has been seriously compromised. I'm sorry for being so vague, but I don't want to betray any confidences.</div><br /><div></div><div>And this is happening all over the place! I know another marriage that split up because he had an affair. This man ran a praise team. He stood with his wife while she went through cancer treatment. And then he left her anyway, when she was already feeling ugly and unattractive. And now he's trying to get out of paying child support; this, a man who has written praise songs that are still played on our Christian radio station.</div><br /><div></div><div>We all know stories like that, don't we? And chances are, the first thing in your mind is, "I thought they were such a great couple! What happened?"</div><br /><div></div><div>Maybe they were a great couple. But even great couples can fall apart if the marriage isn't tended well.</div><br /><div></div><div>Think about all the things that work against marriages today. How many marriages do we know have been destroyed by pornography? Pornography is now implicated in the majority of divorces. It is not harmless. It is not something "fun" that adds "spice" to your marriage. It is poisonous, and it ensnares people, especially men. It lowers their sex drive, eats at their soul, and consumes their time. And what are we doing about it?</div><br /><div></div><div>All addictions--workaholism, affairs, pornography, alcohol--could be avoided if we all simply were intentional in our marriages. If we decided from the outset that we would limit the computer, that we would always have dinner together, that we would spent time each night connecting, that we would put our time with our spouse as a priority, even before our kids, maybe our marriages would last.</div><br /><div></div><div>One partner can never completely save a marriage. The other needs to agree too, and if your spouse has deserted you or cheated on you, that is not your fault. I am not blaming you. </div><br /><div></div><div>But at the same time, carelessness is not an option. If your marriage is going well right now, don't assume it will always be like this. Develop habits so that the things that can drive us apart don't start taking over our marriages. We need to be vigilant. Never assume that you're the one couple that this stuff will never hit. Never assume that your husband would never look at pornography, or that you will never be tempted to have an affair. Instead, take steps now to make sure that this won't happen. </div><br /><div></div><div>Every marriage break up is like the death of a small civilization. It hurts the kids, it hurts ourselves, it hurts our families. </div><br /><div></div><div>Please take steps to make sure it doesn't happen to you. None of us is invincible.</div><div></div><br /><div>What do you think? How have you put hedges around your marriage? How do you deal with the pornography threat? Write your own Wifey Wednesday post, and then come back here and enter your URL in the Mr. Linky. I'd love to keep this discussion going!</div><br /><div>><br /><br /><div><script type="text/javascript" src=""></script><br /></div><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday: Spending Time Together<a href=""><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 320px; height: 197px;" src="" border="0" alt=""id="BLOGGER_PHOTO_ID_5311902301156514050" /></a><br /><br />Hi everybody! Thanks for joining me for Wifey Wednesday, the signature post on this To Love, Honor and Vacuum blog. And this happens to be my 600th post! Woo hoo!<br /><br />Anyway, today I thought I'd tell you the story of two friends of mine that we'll call Bob and Sue.<br /><br /.<br /><br />After a few years the routine became, well, routine. Nobody really questioned it anymore. The kids rarely saw both parents together, because they were rarely together. They didn't have weekends together. One or the other was always working.<br /><br />Bob and Sue just stopped doing things as a couple. They did things with other couples, or with extended family, like playing cards or having parties, but they rarely did things just the two of them.<br /><br />So it was hardly surprising when Sue found greener pastures elsewhere (which, in retrospect, didn't turn out so green).<br /><br />Now in this particular case, it was mostly Sue's choice to never be home with Bob. I actually know Bob well and don't want to lay much of the blame at his feet. But I want to talk about a few lessons from their failed relationship.<br /><br />1. The marriage comes first, not the kids. They were so focused on not getting baby-sitting.<br /><br />2..<br /><br />3. Find time to be together. That's a tough one, and I've talked to women who say, "the only time we have is in the evenings after the kids go to bed, and then he just wants to veg in front of the TV". Tis a problem. But you have to remind yourselves why you're together in the first place. <br /><br />So what are some inexpensive date ideas? <br /><br />1. Feed the kids a quick dinner, put them in front of a movie, and then put them to bed early. You eat dinner with your husband later, by candlelight.<br /><br />2. Go for walks after dinner so you can talk with your hubby while the kids play in the park. Perfect for the coming spring!<br /><br />3. If you live near waterfront, take a drive down there with the family. While the kids skip stones, you can sit hand in hand with him.<br /><br /!<br /><br />5. If the kids are in school, meet up for lunch. Sometimes that's easier than dinner!<br /><br />What about you? How do you keep your relationship alive? How do you find time for each other? Share with us, either in the comments or in the Mr. Linky.<br /><br />To join Wifey Wednesday, just go to your own blog and write a Wifey Wednesday post (you can right click the picture to save it and use it). Then come back here and enter the URL of your post in the Mr. Linky!<br /><br /><div><script type="text/javascript" src=""></script><br /></div><br /><br /><div> --><br /></div><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday - WFMW: Turning Up the Heat<a href=""><img id="BLOGGER_PHOTO_ID_5309316259716682146" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 300px; CURSOR: hand; HEIGHT: 230px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><div><a href=""><img id="BLOGGER_PHOTO_ID_5309316046083271458" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a> I'm cheating a little bit this morning. I'm combining Wifey Wednesday with Works for Me Wednesday, because they're in the same category.<br /><br />I've been talking <a href="" target="_blank">a lot </a>lately about how we women can <a href="" target="_blank">increase our libidos</a>. I've even written a <a href="" target="_blank">book </a>about how to turn up the heat. (Now some of you have the opposite problem: he's the one with the headache. I'll tackle that one soon, too!).<br /><br />And I want to talk today about a method that sounds a little edgy, and maybe even a little scary, but believe me, it can work.<br /><br />One of the problems we women have is that for us, sex is in our heads. We're not usually aroused on our own in the way men are. We have to be thinking about it, and meditating on it, and feeling close to him first. Our bodies follow our heads; for him, his head often follows his body.<br /><br />What that means is that we are often plagued with indecision. We're lying in bed, wondering if we should tonight. "Am I in the mood?", we incessantly ask ourselves. We don't want to start if we're not, but on the other hand, it's been a while since we did. I really should. But that's not a good reason, is it? And does he expect it? I'm not sure. Can I get in the mood? How do I know? I wonder if he's asleep yet. <br /><br />Have you ever had nights like that? The funny thing is that if we just DECIDED early in the day that we were going to have fun tonight, and we started deliberately feeding those thoughts to ourselves, and then we threw ourselves into it, our bodies probably would follow. Maybe not for you if sex still hasn't felt good (and if that's the case for you, I recommend <a href="" target="_blank">this post</a>), but for many of us it's not that sex isn't good; it's that sleep is better. <br /><br />Unfortunately, that doesn't help our marriage. When I was writing <a href="" target="_blank">Honey, I Don't Have a Headache Tonight</a>, I talked to a woman who was in exactly this position. She realized her marriage wasn't as strong as it could be because their sex life wasn't great, but she didn't know how to increase her libido. So one birthday she presented her husband with twelve sex coupons that he could use, one a month, when he was especially desperate. That way she promised that they would have a fun time, and she would throw herself into it, and he didn't have to worry about living in a sexual black hole.<br /><br />It worked like a charm. And what she found was that when the decision was taken away from her (not by force, of course, but by giving him some control), she was able to enjoy herself more because she didn't put herself through all that rigamorale about "am I in the mood"?<br /><br />I took that to heart, and I created coupons that we can use, too. They're not X rated, but they are fun, and if you want to try it, just <a href="" target="_blank">go here</a>!<br /><br />If that's a little too scary, don't worry about it. But I challenge you to think about this: are you the one who always decides when to make love? Even if he initiates, are you the one who always says "yes" or "no"? That's not a good place to be in, because he can start to feel like he has no control in an area of his life which is really important to him. So how about this? Decide that over the next week, you will say yes, or better yet, even initiate, even if you're not particularly in the mood. Throw yourself in it for him. I'm not talking about placating him; I'm talking about deciding to have fun. We do have control over our minds, so let's start thinking positive thoughts about it. And if he feels more loved, then your marriage really will improve!<br /><br /><a href="" target="_blank"><em>Click here for your love coupons!</em></a><br /><br />Now, what about you? Do you have an advice you'd like to share with us about marriage? It can be about anything! Just go to your own blog and write a post, and then leave the URL in the Mr. Linky!</div><br /><br /><div><script src="" type="text/javascript"></script></div><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday: Where do you go for help?<a href=""><img id="BLOGGER_PHOTO_ID_5306717335918875778" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><div><br />We get married with stars in our eyes, expecting everything to be great. But then something happens: we have issues with sex; we don't see eye to eye on kids; we don't feel loved.<br /><br />And where do we turn for help? When a couple honestly needs help, or a wife honestly needs advice, what do you do?<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />This is biblical, too! The older women are supposed to help the younger women figure out how to love their husbands. So find an older woman you can talk to, and call on her for advice. Most women would love to be a mentor!<br /><br /?<br /><br /!<br /><br />So I've decided to write an ebook called "<strong><span style="color:#330033;">Sex Questions You're Afraid to Ask Your Pastor</span></strong>". I've set up some web forms where you can enter your questions anonymously, and a different one where you can enter your email so that you can be notified when the questions are all answered!<br /><br /.<br /><br />If you have questions you want answered, just go <a href="">here</a> to enter them. I've got a bunch already, but I'd love to have more! And I really do want to help those of you who just don't know where to turn.<br /><br /!<br /><br /><div><script src="" type="text/javascript"></script> Important is Caring for Yourself?<a href=""><img id="BLOGGER_PHOTO_ID_5303848971881713138" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><br />Are you an introvert or an extravert?<br /><br />If you're the life of the party, you may automatically say you're an extravert. But that's not necessarily true. An introvert is someone who gets energy from being by themselves. They process things internally, and usually don't speak until they've made up their minds about something.<br /><br />An extravert, on the other hand, processes things by speaking. They need to talk it through. They get their energy from being with other people. So if they have a big decision to make, they call five friends and talk about it. An introvert may call a bunch of friends, too, but only after she's already thought it through.<br /><br />Now here's where this comes into play in a marriage. If you're an introvert, chances are you need time just to be by yourself in order to stay emotionally healthy. I'm actually an extravert, but barely. I need that time to myself, too.<br /><br />I've been on vacation for a week with my family, and it's been great. But we're leaving in about five hours and what I really really want to do right now is take a walk on the beach by myself. I haven't been by myself for a week! But the family often interprets that as me being depressed (which I'm not) or me rejecting them (which I'm not). So I have to sit down and explain I just need some thinking and praying time. And I will do that as soon as I've posted this!<br /><br />But in the meantime, even extraverts may need time to themselves, especially with small children. And if we don't get that time, then when our husbands want us to be available for them we can become quite resentful. They're stealing the only time we have for ourselves! And then they expect us to be there for them! How selfish!<br /><br />You see how this can become a big problem? He just wants to connect, and there's nothing wrong with that. And you want to connect, too, but you first need some time to replenish your batteries. He experiences that as rejection.<br /><br />So, ladies, what's the answer? Today on Wifey Wednesday, let's share what we do for ourselves so that we're not exhausted, and we feel rejuvenated.<br /><br />Personally, I do two things: I knit, and I take baths. I love baths. They give me some thinking and planning time which I desperately need (I often take a piece of paper and pen in the bath with me. They get soggy, but they do the job). And I knit to ground me.<br /><br />What about you? Do you have any suggestions for us as to how to find time to ourselves? And how important is it? Let's talk about it!<br /><br /><span style="color:#330033;"><em>(I'm hoping the Mr. Linky shows up. I'm writing this a day ahead and posting it tomorrow, so hopefully it will. But if it doesn't, just leave your link in the comments! And by next week I'll have the Mr. Linky thing solved!)</em><br /></span>: Knowing His Love Language<a href=""><img id="BLOGGER_PHOTO_ID_5301337396711290434" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br />Last week, during my online party for <a href="">Honey, I Don't Have a Headache Tonight</a>, I started a bunch of conversations both here and on Twitter and Facebook.<br /><br />And one thing that kept coming up was love languages.<br /><br />So my question to you today is: Do you know your husband's love language?<br /><br />For those of you who don't have a clue what we're talking about, let me explain. We all tend to want to receive love in a certain kind of way. We have preferences that determine whether or not something says "I love you". The five possible love languages are:<br /><br />1. Touch<br />2. Time<br />3. Words of Affirmation<br />4. Gifts<br />5. Gifts of Service (doing something for someone).<br /><br />Before you can figure out what your husband's love language is, it's good to figure out what yours is. Here's why: we tend to give love in the same way that we want to receive it. So if you're a huggy bear, chances are you hug everyone in sight, and want them to do the same for you.<br /><br />So perhaps you're hugging your husband all the time, and you feel like therefore you are showing him love. So why isn't he reciprocating? What is wrong with him?<br /><br />What may be going on, though, is that he may not be receiving it as love. He may even find it a mild irritant. So we need to know what makes his clock tick, and be aware of where we may be tempted to love in a way that he doesn't necessarily understand.<br /><br />It took me a long time to figure out my own love language. I always thought it was touch, because I love being hugged. But I think that's something that's common to a lot of women. What really speaks to my heart, though, are words of affirmation. When he tells me that he thinks I'm beautiful, or he likes my writing, or he thinks I'm a great mother, that does wonders for me.<br /><br />It turns out that his is the same thing, but I didn't realize that, either. I always thought it was touch, because men seem so interested in--well, you know. But he needs to hear words of affirmation, too.<br /><br />When we were first married, though, the words that I said to him didn't necessarily affirm him. I was constantly saying, "I love you", or "I think you're a great husband", or later on, "you're such a great dad".<br /><br />But one day, when we were talking, he got exasperated with me and said, "but why do you love me? Why do you think I'm a great husband?" What he needed was not just to know my thoughts, but to know what lay behind them. When I started to say, "you're such a great dad with the way you play with the kids," or "Rebecca just loves the way you take time to listen to her," he felt affirmed.<br /><br />He needed to hear the why, and not just the what. I've now learned that when he's really down, it's even more important to say these things.<br /><br />I have a friend whose husband love language is gifts. He just loves choosing the perfect gift for people. He loves giving more than receiving. But she couldn't care less about gifts, so she doesn't put the same kind of effort into it. When he gives her something incredible for Christmas, she likes it, but she's not in heaven or anything. But when she just gives him a gift card to a favourite store, he's devastated. It says to him, "you weren't worth putting any thought into this year."<br /><br />So she's learned now to think carefully about gifts for him, and to start studying him to find out what would be a good gift. It goes against her natural bent, but she's had to learn so that he can feel loved.<br /><br />If you're not sure of your husband's love language, why not read The Five Love Languages? You can even read it together for Valentine's Day. But this year, try to speak his language!<br /><br /><div><iframe src="<1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><br /><br />Now, you may be thinking: why should I speak his if he doesn't speak mine? But let's remember that marriage is not about manipulating him into doing what we want. It's about learning how to love. And ironically, often the best way to get our own needs met is to meet his! That doesn't mean that we meet his needs in order to get him to do something; it's just that when we act in a selfless way, and show love to him, he feels appreciated. He feels valued. He feels loved. And when he feels loved, he's more likely to reach out to you, too. <br /><br />But even if he doesn't, you are still acting in a loving manner, and learning how to serve. And that pays dividends all on its own!<br /><br />Now, do you have some marriage advice you want to share? Have you had an interesting time working out your love languages? Why not join us for this discussion? Just leave your link in the comments below!<><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday: Blog Scavenger Hunt!<a href=""><img id="BLOGGER_PHOTO_ID_5298975334132490786" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 197px; TEXT-ALIGN: center" alt="" src="" border="0" /></a><br /><div>Today, for Wifey Wednesday, we're going to party! </div><div> </div><div></div><div></div><div>It's party day for my book, Honey, I Don't Have a Headache Tonight: Help for women who want to feel more in the mood! When you <a href="">order it today </a>you get a whole pile of free gifts!</div><div> </div><div></div><div></div><br /><br />So today, we're going to do something different. A bunch of my internet buddies have volunteered to do Blog Scavenger Hunts for me this morning, and I'm so grateful! They've left their own insights on marriage and you-know-what!<br /><br />If you go through these blogs, and collect all their secret words, you can then follow the instructions to submit the phrase they make into my ballot!<br /><br />The winner will get a copy of my book Reality Check, and an audio download of my talk "Protect Your Marriage". It's fun!<br /><br />First Stop: <a href="" target="_blank">Mrs. Juice Box</a><div>Second Stop: <a href="" target="_blank">Home Sweet Home</a></div><div>Third Stop: <a href="" target="_blank">Multi Tasking Mama</a></div><div>Fourth Stop: <a href="" target="_blank">Mother Inferior</a><br />Fifth Stop: <a href="" target="_blank">Grace Comes by Hearing</a><br /><br />Each blog will direct you to the next one, so you don't actually have to keep stopping by here! But I've listed them all in case there are some problems. </div><br /><br />Then just follow the directions to fill out the ballot!<br /><br />The winner will be announced right here a 10 p.m.! <br /><br />Now, does anyone else have marriage thoughts they want to share on Wifey Wednesday? You can do it in the Mr. Linky below!<div><br /><br /><div><script src="" type="text/javascript"></script></div></div><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila Wednesday: Helping Your Husband Feel Strong<p align="center"><a href=""><img src="" /></a></p><br /><br />Last weekend my husband and I flew out to Vancouver for a conference with Family Life Canada. We speak with the around the country at marriage conferences, and this was our staff retreat.<br /><br />Loads of fun and loads of laughs, but one of the nuggets I gleaned from the time together was from a marriage talk on how to communicate better.<br /><br />I know I've been talking about <a href="" target="_blank">sex</a> <a href="" target="_blank">a</a> <a href="" target="_blank">lot</a> here on Wifey Wednesdays lately (and next week is my <a href="">HUGE party </a>for <a href="">Honey, I Don't Have a Headache Tonight</a>), but I want to take just a minute and talk about something else today.<br /><br />Here's the gist: men like to feel like they know what they are doing. If they feel like they're not competent, they'll move on to another thing. So if you're always nagging your husband to fix something around the house, and then you berate him for not doing it right, he will rarely fix anything ever again. He doesn't like to fail. Get it?<br /><br />Or if he takes you out to dinner, but he chooses the wrong restaurant, don't let him know that right away. You'll chase him off planning dates again. He doesn't want to fail.<br /><br />But he does like to feel competent! So spend some time with your husband in areas that he feels confident, because then it's like you've entered his favourite world. He will feel so affirmed and so connected to you, in the same way you would if he sat down and talked to you for hours just about how you're feeling.<br /><br />Here's how it works. My husband loves history, and especially military history. He knows everything about the Pelopenesian Wars (I know that's spelled wrong), or the civil war, or the Seven Years War, or anything about war in modern history. He and friends play out war games. He reads war stuff. He lives and breathes it.<br /><br />But it doesn't really interest me. So I have two choices. I can ignore it altogether, and let him do his little thing, but then when we get together insist that we talk about something important, or every now and then, when we're out walking, I can ask him a question about a battle. And then suddenly, this man who wasn't talking a lot before, will open up with a stream of information.<br /><br />And he'll feel very affirmed, because I have asked about something where he can teach me. And if I try really hard, I can see that it really is interesting.<br /><br />One of the mistakes that women often make is to leave their husbands hobbies as if these have no relevance for them. They're just something that the men do on their own, and we have to humour them. But that's not true. They're something that excites our husbands. It's something they think about deeply in their inner world. And don't you want to share that?<br /><br />Now I'm not saying that you have to actually participate. If your husband plays poker with the guys every Friday night, he probably doesn't want you there. My husband has fun with his friends playing his games, and I would wreck the dynamic. But that doesn't mean that he doesn't want me to be interested.<br /><br />Women talk more than men do, and so we often determine the subjects that are open for discussion in our marriages. Don't leave his hobbies out. Maybe it's his work that he loves to talk about. Maybe it's computers. Whatever he loves doing, enter that part of his life. Just listen. And afterwards, he'll probably feel much closer to you because you've shared something precious to him.<br /><br />Tonight, what are you going to talk about? What does your husband love? Ask him something about it. Let him share it. And see what happens!<br /><br /><strong><em><span style="font-size:85%;color:#330033;">Don't forget about </span></em></strong><a href="" target="_blank"><strong><em><span style="font-size:85%;color:#330033;">my party </span></em></strong></a><strong><em><span style="font-size:85%;color:#330033;">next week for Wifey Wednesday! I'll have a blog scavenger hunt, a teleseminar, a Twitter party, and more! Find out more here!</span></em></strong><br /><br />Do you have any marriage thoughts for us today? Why not write a post on your own blog, and then come back here and link to it in Mr. Linky!<br />><br /><br /><div><script type="text/javascript" src=""></script><br /></div><div class="blogger-post-footer"><img width='1' height='1' src=''/></div>Sheila | http://feeds.feedburner.com/WifeyWednesdays | crawl-002 | refinedweb | 20,218 | 73.47 |
How to use Vue.js in Sitecore
One of the abilities of Vue is being progressive. It means you might only introduce Vue.js core library or using full functionality of vue.js using Vue CLI.
In the recent Sitecore project that I was designing the Frontend side of it, initially I introduced the core library of vue.js for the search page by using Vue directly inside MVC razor code.
Then based on the requirement, I needed to run a few pages in the Sitecore as a SPA app. However, since not everyone has sitecore on their machine to develope, I was asked to come up with a solution to build a standalone app with the ability to be embeded in SItecore. (With SItecore 9 you wouldnot have any problem but we used version 8.2)
I came up with a solution to build a standalone SPA
vue.js app and bring it to the sitecore as a web library which I am elaborating it in the next section.
Exporting Vue.js as a library into Sitecore
Step1 : Build your Vue.js app with Vue CLI
build your vue with
vue cli and design your app pretending you don't have any Sitecore integration :)
You can easily use the VueX (state manager) and Router and any styling framework like Vuetify or bootstrap inside your app.
you need a content editable app?
In some cases you need your
vue.js app to be content editable so for that scenario, you need to build a template for the labels and images and all other content editable texts to be used inside the
Vue.js App and expose a
Sitecore API to make them available to the Vue.js app.
Step 2:
Register your components in Vue to be accessible as a library.
import Vue from "vue"; import app from "../App.vue"; Vue.component("app", app); export default { app }
Step 3: Tweak your package.json file
You need to tell your Vue.js app to be acting like a library instead of a web app. so you need these changes in your package.json file:
{ "name": "tool-vue-lib", "version": "1.0.1", "private": false, "author": "Nelly Sattari", "main": "./dist/tool-vue-lib.common.js", "files": [ "dist/*", "src/*", "public/*", "*.json", "*.js" ], "scripts": { "build-lib": "vue-cli-service build --target lib --name tool-vue-lib ./src/components/index.js", }, ... }
Then you need to run :
npm run build-lib
You will see some JS/CSS files with
umd and
common.js format will be built inside your dist folder. also This folder can be browsed by using any
http-server app.
I installed
http-server to view the app. See if you have any otherwise install one app.
Step 4: build a private npm repository
Publish your app in npmjs or in some private repository of your organization. I used Verdaccio for publishing the Vue.js app
publishing the client app to a private repository with @scope namespace
- Add a @scope name to your package.json file in the client app
"name": "@yourcompany/tool-vue-lib",
register your app into the private repository:
npm login --registry= --scope=@yourCompany npm config set @yourCompany:registry npm publish (This step should happen inside the app folder which is meant to be published)
You might get an error on the publish contains of this error which means you need to increase the
version in your package file to publish a new version of your app.
npm ERR! registry error parsing json npm ERR! code EPUBLISHCONFLICT npm ERR! publish fail Cannot publish over existing version. npm ERR! publish fail Update the 'version' field in package.json and try again. npm ERR! publish fail npm ERR! publish fail To automatically increment version numbers, see: npm ERR! publish fail npm help version
If you have not done it before refer to npmjs to add your user/pass and publish your app.
Step 5: Sitecore integration
This is an important step that you need to install your
Vue.js app into your Sitecore as a normal
npm library.
If you used a private npm repository to publish your vue.js app then make sure you install it in Sitecore from right path.
You need to add the @scope to tyour registry otherwise it will pick it from the npm public repository. To avoid manual change to the npm config, you can add
.npmrc file to the root of project just beside the package.json and add the following config:
@yourCompany:registry= strict-ssl=false
Get the latest version the client app in sitecore
"devDependencies": { "@yourCompany/ClientApp": "latest", }
Render the client app in sitecore
Depend on the requirement you can build a layout specific for the tool and drop the JS and Styles into that.
You need a
Div with the id you used in your client app:
<div id="appCLient"> <app></app> </div>
and a Javascript file with this spec:
import Vue from "vue"; import { app } from '@yourCompany/ClientApp'; $(document).ready(() => { new Vue({ el: '#appCLient', components: { app }, router: app.router, store: app.store }); });
In case you used Vuetify as a styling framework in VUe.js
Inside the feature you need to import the pollyfill for the sake of Vuetify to be rendered in IE.
If your Webpack has an entry file then you need to import the babel polyfill to that file. If not and if you take the list of JS files from an array then you need to inject it to one of your Js files and push that file to the begining of the Array.
import '@babel/polyfill'; import Vue from "vue"; import { app } from '@yourCompany/tool-vue-lib'; $(document).ready(() => { new Vue({ el: '#app', components: { app }, router: app.router, store: app.store }); });
OR
allScriptArrays.unshift(path.join(__dirname, '..', '..', '..', 'Feature', 'Tools', 'code', 'scripts', 'index.js*')); | https://www.nellysattari.com/integrating-sitecore-and-vue-js/ | CC-MAIN-2020-29 | refinedweb | 966 | 74.49 |
ReShar slipped your attention, here’s a nice tour of Roslyn on the C# FAQ blog at MSDN.
Immediately we at JetBrains were faced with multiple questions on the perspectives of ReSharper using Roslyn for its code analysis and how the two tools might compete. The flow of questions wouldn’t end, to the point of introducing a template to answer them:
Seriously though, it was clear that we needed to elaborate on the ReSharper vs Roslyn issue. Hence this post.
We sat down with Sergey Shkredov (@serjic), ReSharper Project Lead and .NET Tools Department Lead at JetBrains, and Alex Shvedov (@controlflow), a Senior Developer on the ReSharper team who’s responsible for ReSharper’s Generate functionality, code annotations and support for XML-based languages. The following Q&A is a summary of the conversation that we had with them.
What’s JetBrains stance towards Roslyn? Do we consider the technology and its Open Source status important and valuable?
Roslyn is definitely important and a good step forward for Microsoft in that it should help Visual Studio users take advantage of more C# and VB.NET code editing and analysis features in Visual Studio out of the box.
It should also help Visual Studio extension developers write code-centric extensions against a consistent API while having the opportunity to know how it works inside, thanks to the Open Source status of the project. This is not to mention hackers who are willing to spend their time forking the compiler and tuning it to make, say, C# the ideal language they’ve always envisioned.
We also believe that Roslyn is no less important for Microsoft itself. Faced with the burden of maintaining a plethora of Visual Studio integrated tools including code editing tools, IntelliTrace and code designers, the folks at Microsoft are interested in making these tools as flexible and easy to update as possible. Roslyn should enable updating .NET languages and experimenting with them faster than before. Apart from that, the old compiler wouldn’t let launch compilation steps in parallel, and Roslyn is expected to enable that, bringing more scalability to the table.
What’s the point of making Roslyn Open Source?
As to the act of letting Roslyn go Open Source, we don’t believe that Microsoft is expecting anyone from outside of the company to develop the compiler for them. Programming languages are entities too monolithic and complex to justify accepting external changes of any significance. Therefore, we expect Microsoft to keep the function of designing .NET languages totally to itself without depending on the community.
The true value of Roslyn going Open Source lies in enabling extension developers to look into Roslyn code that is relevant to their purposes: how it’s written and whether it’s efficient. They might debug or profile it to see if it’s the culprit of unexpected behavior in their extensions or if it introduces performance issues. This is possibly the workflow whereby meaningful pull requests might start coming in to the Roslyn repository.
As to possible endeavors to fork and modify the compiler to address application- or domain-specific tasks, this scenario appears to be a shot in the foot. Even if the default compiler in Visual Studio can be replaced with a fork, instrumental support for the fork ends as soon as you go beyond Visual Studio. In theory we can imagine a custom
INotifyPropertyChanged implementation based on a Roslyn fork that can even gain certain popularity. However, we can barely imagine supporting it in ReSharper as our intention is to focus on supporting the official version of Roslyn.
Will ReSharper take advantage of Roslyn?
The short answer to this tremendously popular question is, no, ReSharper will not use Roslyn. There are at least two major reasons behind this.
The first reason is the effort it would take, in terms of rewriting, testing and stabilizing. We’ve been developing and evolving ReSharper for 10 years, and we have a very successful platform for implementing our inspections and refactorings. In many ways, Roslyn is very similar to the model we already have for ReSharper: we build abstract syntax trees of the code and create a semantic model for type resolution which we use to implement the many inspections and refactorings. Replacing that much code would take an enormous amount of time, and risk destabilizing currently working code. We’d rather concentrate on the functionality we want to add or optimize, rather than spend the next release cycle reimplementing what we’ve already got working.
The second reason is architectural. Many things that ReSharper does cannot be supported with Roslyn, as they’re too dependent on concepts in our own code model. Examples of these features include Solution-Wide Error Analysis, code inspections requiring fast lookup of inheritors, and code inspections that require having the “big picture” such as finding unused public classes. In cases where Roslyn does provide suitable core APIs, they don’t provide the benefit of having years of optimization behind them: say, finding all derived types of a given type in Roslyn implies enumerating through all classes and checking whether each of them is derived. On the ReSharper side, this functionality belongs to the core and is highly optimized.
The code model underlying ReSharper features is conceptually different from Roslyn’s code model. This is highlighted by drastically different approaches to processing and updating syntax trees. In contrast to ReSharper, Roslyn syntax trees are immutable, meaning that a new tree is built for every change.
Another core difference is that Roslyn covers exactly two languages, C# and VB.NET, whereas ReSharper architecture is multilingual, supporting cross-language references and non-trivial language mixtures such as Razor. Moreover, ReSharper provides an internal feature framework that streamlines consistent feature coverage for each new supported language. This is something that Roslyn doesn’t have by definition.
Will it be practical to use both ReSharper and Roslyn-based functionality in Visual Studio?
This is a tricky problem as it’s still uncertain whether we would be able to disable Roslyn-based features (such as refactorings or error highlighting) when integrating into new releases of Visual Studio. If we’re unable to do that, performance would take a hit. Apart from ReSharper’s own immanent memory and performance impact, Roslyn’s immutable code model would increase memory traffic, which would in turn lead to more frequent garbage collection, negatively impacting performance.
We’re hopeful that this problem would be solved in favor of letting us disable Roslyn features that ReSharper overrides, because otherwise ReSharper would have to work in a highly resource-restricted environment. Irrelevant of whether this happens though, we’ll keep doing what we can do, minimizing ReSharper’s own performance impact.
As Roslyn is now Open Source, which parts of its code are going to be of particular interest to ReSharper developers?
We’ll be sure to peek into Roslyn code and tests from time to time, to see how C# and VB.NET language features are implemented. We don’t rule out that actual code supporting them is going to emerge before formal specifications are finalized. In fact, we’ve already started.
That’s more or less the picture of living in the Roslyn world as we see it today. As time goes by, we’ll see if things turn out the way we expected them to.
Meanwhile, if you have questions that were not addressed in this post, please ask in comments and we’ll try to come up with meaningful answers.
68 Responses to ReSharper and Roslyn: Q&A
Jean-Marie Pirelli says:April 10, 2014
Thanks for being honest like that.
I was not expecting you guys to use Roslyn, to be honest. Simply because Roslyn will be integrated in VS 13+ only and R# supports older versions of VS.
Jura Gorohovsky says:April 10, 2014
Yes, this is another good reason not to. It’s probably worth another 10 years before VS 13- releases become irrelevant.
Michael Damatov says:April 10, 2014
I’ve not expected from JetBrains to adopt Roslyn, however, I do expect from you to use Roslyn to verify assumptions you have been made during the development of ReSharper.
Jura Gorohovsky says:April 10, 2014.
Sebastiaan Dammann says:April 10, 2014
It would be great if R# would not disable code refactorings using Roslyn as they are quite easy to write.
Jura Gorohovsky says:April 11, 2014.
David Zidar says:April 10, 2014.
controlflow says:April 10, 2014!
David Zidar says:April 10, 2014!
Mike Andrews says:April 10, 2014.
Jura Gorohovsky says:April 11, 2014!
Roslyn! It’s got Electrolytes! | In Absentia says:April 10, 2014
[…] already started predicting the demise of ReSharper. It’s been a week or so, and JetBrains finally posted a Q&A where they explain their reasons for not moving to Roslyn, as predicted, at least not in the […]
Fujiy says:April 11, 2014
controlflow says:April 11, 2014).
David Zidar says:April 11, 2014.
Fujiy says:April 13, 2014
Jura Gorohovsky says:April 14, 2014 )
Petr K. says:April 16, 2014
Not sure if the sarcasm is really appropriate. Unfortunately, this thinking really IS common amongst developers.
Jura Gorohovsky says:April 17, 2014
Wasn’t meant as sarcasm at all, Petr. I simply find this sentence a perfect call to action.
13xforever says:April 11, 2014
I hope that R# will support the ability to use custom C# features, though I cannot think how you might be achieving this without using the modified Roslyn which supports these features.
Jura Gorohovsky says:April 11, 2014.
Vladimir Reshetnikov says:April 16, 2014.
Jura Gorohovsky says:April 17, 2014
Thanks for noting, Vladimir, although it doesn’t make it any clearer as to who decides to maintain it in one way or another.
Vladimir Reshetnikov says:April 18, 2014.
controlflow says:April 18, 2014
So, VisualStudio 2014 will ship (Mads announced that) with other, internal Roslyn build that Microsoft ‘has responsibility for fidelity, correctness or intellectual property used’?
Vladimir Reshetnikov says:April 18, 2014
The current plan is to use some stable branch of the open-source project
نگاهی به Roslyn | A Geek NotesA Geek Notes says:April 11, 2014
[…] در این بین واکنش jetbrains هم برای استفاده از Roslyn در ریشارپر جالب بود.که آنها […]
Joe White says:April 13, 2014
Good post; thanks for laying out the reasons so clearly.
I wonder whether there’s a way you could take advantage of Roslyn’s test suite to find things like compiler errors that R# doesn’t yet recognize.
Jura Gorohovsky says:April 13, 2014
Joe, there should be a way to take advantage of the test suite in terms of any errors and warnings that we don’t recognize, as well as to explore their performance testing practices.
Hannes K says:April 13, 2014. 😉
controlflow says:April 14, 2014 🙂
Jeremy Foster says:April 14,ura Gorohovsky says:April 17, 2014
Jeremy, thanks for your comment. We’ll be actively looking for other holes though and we’ll be finding them.
Ilya says:April 15, 2014#.
Jura Gorohovsky says:April 17, 2014
Thanks Ilya, we’ll see how it goes.
MindLogics says:April 16, 2014
Good post; thanks for laying out the reasons so clearly.
Jura Gorohovsky says:April 17, 2014
Thanks
Petr K. says:April 16, 2014.
Jura Gorohovsky says:April 17, 2014.
Patrick Smacchia says:April 17, 2014.
controlflow says:April 17, 2014
Pretty risky, huh? How everything is working now in VS? Current unmanaged C# language service is more memory hungry than Roslyn: 150-200Mb difference on R# solution 😉
Future evolution for free? It’s a myth 🙂 🙂
Patrick Smacchia says:April 18, 2014
Sure it’ll be interesting to see where the tooling will be in five years, in ten years, from now.
No, ReSharper will not use Roslyn | Dip Thoughts says:April 17, 2014
[…] The actual blog post can be found here. […]
C-J Berg says:April 25, 2014. 🙂
Niels Jørgensen says:April 25, 2014
Dead on!
I have all my fingers crossed that this is what will finally get you guys to do a complete C# IDE – we all know it’s going to be awesome 😉.
Eyal Shilony says:August 9, 2014
Exactly! I’d be one of the first to buy it, just leave VS or well, continue to support it but let some of us enjoy IDEA for .NET development! 😀
CodeRush vs ReSharper (the Roslyn debate) | Paul Usher says:April 25, 2014
[…] NO […]
Michael says:April 26, 2014
LOL an IDE by JetBraind for C# is never going to blow VS out of the water, you are crazy people.
Marcel Bradea says:May 16, 2014?
Jura Gorohovsky says:May 16, 2014
Thanks Marcel.
There’s no change in this regard though. We’re not currently planning to build a .NET IDE, cross-platform or otherwise.
Eyal Shilony says:August 9, 2014.
Neal Gafter says:May 12, 2014
You wrote “… Roslyn’s immutable code model would increase memory traffic, which would in turn lead to more frequent garbage collection, negatively impacting performance.”
That theory illustrates a deep misunderstanding of functional data structures. Fortunately it is not borne out in practice.
controlflow says:May 12, 2014?).
Kirill Skrygan says:March 25, 2015
Regarding the practice.
Solution with 320 projects. VS CTP6.
Just typed for 20 seconds in a 200-lines of code file. Etw shows there were allocated about 820 MB.
820.
Megabytes.
Although UI thread is pretty free, as a user I constantly feel this lagging.
.NET Developer Tooling: The Roslyn Revolution | Dot Net RSS says:May 15, 2014
[…] VS process. This will have a crucial consequence on both memory-consumption and performance. Not using Roslyn is the choice of the R# team and I am worried a bit since I am a big fan of […]
jrg says:May 20, 2014.
Stacey says:June 10, 2014
I am pretty sure that this could all change 10 or 15 times before Visual Studio 2014 actually lands in RTM, though. We should all know by now that the programming world changes every few minutes – anything can happen.
Retour sur NCrafts / Le projet Roslyn | Cellenza Blog says:July 29, 2014
[…] qu’elle n’utilisera pas Roslyn lorsque cet outil sera disponible dans sa version définitive (point de vue de l’équipe resharper sur le sujet). Tout ceci promet de futurs trolls très animés […]
Is Microsoft Going Open Source? - Admo.net Blog says:August 1, 2014
[…] that previously required purchasing third party tools such as JetBrains’ Resharper. That said, Resharper will still have its place even with […]
Roslyn (.NET compilers as services) now open source | Visual Studio Extensibility (VSX) says:August 8, 2014
[…] What to do if you have a huge investment in the previous technologies (automation code model or your own parsers). For example, ReSharper has decided not to use Roslyn… […]
Roslyn, the C# (and VB) .Net compiler platform | Wimpies C# Blog says:August 12, 2014
[…] toolmakers have already their extensive own (optimized) code base. See for example the bog post ReSharper and Roslyn: Q&A. Newcomers however can profit from the work already available from […]
Alex says:December 15, 2014
With Roslyn it will be possible to debug lambda expressions. If Resharper is not going to support Roslyn, will we loose on this new feature?
Alexander Shvedov says:December 15, 2014
No, you won’t lose this feature. ReSharper is a design-time tool for source code (mostly), we do not integrate into any of VS debugging capabilities. So as usual, compiling your code, debugging, intellitrace and edit & continue goes through old C# or new Roslyn compilers, R# has nothing to do with it.
Michael says:June 15, 2015
I’ve been a long time advocate for tools like Resharper; it’s saved me and the teams I’ve worked with countless hours performing code analysis, refactoring, and other daily challenges. Even menial stuff like discovering assemblies and making the appropriate references, is indispensable, IMO.
However, the short answer of “no” is disappointing to say the least. The times are changing, whether we like it or not, the OSS march is in full swing. Has been for well over a year now, in relevant C# .NET stacks. That’s not changing any time soon that I can surmise. The fact of life is that it is tough to keep pace when the sands are shifting so quickly, but that’s just the fact of life we must all deal with.
Hopefully you change your minds on this and make the necessary changes to keep pace.
Wouter Boevink says:July 22, 2015
Exactly our thoughts Michael!
Jeff says:July 24, 2015
I have been using CodeRush and ReSharper together, in my day to day work, for many years.
I stopped to pay my CodeRush licence last year, the reason is its performance is not getting better, and there isn’t much new feature coming along.
However, I recently find ReSharper’s performance for large solution is getting worse, especially the poor performance on Code Analysis. I have to disable solution-wide code analysis, and even file-level analysis sometime. The intellisence’s performance is not that good neither.
A performance benefit from using Roslyn ( from CodeRush ), even they do not mention competitor’s name, but I believe everyone knows.
Their ‘CodeRush for Roslyn’ is under preview stage, and planing to complete all features by the end of this year. Therefore, R# has another 5 months to think about it (I mean if you want).
I think Roslyn is more than just compiler, it opens an opportunity.
Steve Dunn says:September 19, 2019
5 years on, I’d be very interested to hear what JetBrain’s stance on this now is.
Do you think not switching to Roslyn was the correct choice?
There seems to be a lot of Roslyn PRs (), so it _appears_ popular, although I haven’t checked to see how many are external PRs.
Was Rider a response (at the time) to difficulties in getting such a complex plug-in working efficiently in Visual Studio?
Genuine questions – I personally *love* R# and I’m a huge fan of JetBrains (since before the reseller days!)
Jura Gorohovsky says:October 4, 2019
Hi Steve,
I’m the author of this post but since I’m no longer at JetBrains, I can’t really reflect whether this choice is currently considered correct or regrettable. I’ll ping someone at JetBrains to provide a comment on that.
I can comment on Rider however: at the time of publishing this post, Rider wasn’t on the radar at all. It took one more year for the first developer to start experimenting with the IntelliJ platform and come up with the first Rider prototype. Was the experiment a response to the complexity of ReSharper’s integration with Visual Studio? I believe it was to some extent, but to a greater extent it was just that: an engineering experiment, an effort from a part of the dev team to enter unchartered territory. Whenever you try to make sense of what JetBrains does and you need to figure out whether a certain activity was driven by business concerns or an engineering challenge, you can safely bet it’s the latter. | https://blog.jetbrains.com/dotnet/2014/04/10/resharper-and-roslyn-qa/?replytocom=75838 | CC-MAIN-2020-29 | refinedweb | 3,212 | 62.88 |
Eye tracking tobii T120
Hi, I am currently working with a tobii t120 and OpenSesame 3.2.7 (Python 2.7.13), using a Windows 7 32bit. It is the first time that I use both and I am having problems with pygaze_init.
When I try to run the experiment, I receive the following Error message:
What does this error message means and is there a solution to this problem?
Your help will be very helpful!!
Simone
Hi Simone,
It looks like the Tobii Pro SDK can't find you tracker. Is the T120 compatible with the Pro SDK? (And is it licensed for that?)
If the Pro SDK doesn't work, you could try the tobii-legacy backend, which doesn't require the Pro SDK.
Good luck!
Edwin
In case it is compatible and licensed, here's my $ 0.02. We had experienced a similar issue with a Tobii Spectrum. This is related to the way in which the SDK automatically looks for eyetrackers and theoretically selects the first available one. For us, this threw an error, because a different Tobii eyetracker had previously been connected. My suspicion is that this is cached in wherever libtobii looks for it.
Our solution/workaround (that's a fine line) was to use libtobii's first method and add the serial number of our eyetracker to the settings.
Hi Edwin and cesco,
I'm having the same issue as Simone, and I am running on the same eyetracker. I am very new to both eyetracking and Pygaze and was hoping to get more information about three things mentioned on this thread (e.g. 1. The Pro SDK license, 2. libtobii's first method, and 3. tobii-legacy backend):
Thank you so much for any help!
Edit: I resolve the issue I was having using the method cesco suggested!
Answering for future reference:
from pygaze import settings; settings.TRACKERSERIALNUMBER = #(but instead of "#" you'd put in your serial number.) | http://forum.cogsci.nl/index.php?p=/discussion/5232/eye-tracking-tobii-t120 | CC-MAIN-2020-05 | refinedweb | 326 | 66.94 |
Fix modules conflicts magento jobs
..
.. how to fix it the best way
I'm looking for an experienced Shopify D...looking for an experienced Shopify. for]
Topic: Water Crisis: Future Conflicts in South East Asia nations. Word count - 15000 word.
I have a Linux server with WHM/cPanel and need 3 Python modules installed: 1. requests 2. import [login to view URL] 3. import json Apparently pip needs to be installed as well. I prefer that be done via a TeamViewer session with me. I'll login to ssh and then you do the installs and test.
We need a joomla/java script pro developer to resolve the conflicts that we have on one websites. Website is joomla 3 - T3 framework. We will provide you full description.
...- Edit 2 Joomla modules and 2 icons; Total budget [login to view URL]
I would like to isolate bootstrap v3.3.7 to avoid css conflicts with SharePoint online. New namespace would be 'bootstrap-htech'.
...into live testing mode on Friday, so please do not bid unless you are truly expert with Wordpress and FULLY understand how to work with Divi and know how to avoid or fix plugin conflicts and keep the Divi module editor and visual editors working without error. You must also be confident you can ensure the site can handle massive traffic trying to buy).
.. chat on here and JIRA comments. This is for
i am looking for someone to Developper Modules For Dolibarr ERP & CRM link to download the source code : [login to view URL] install and active just the compta module from the modules ... then click on factoration in the top, now you will see list in the left like this : Factures clients Nouvelle facture Liste | https://www.freelancer.com/job-search/fix-modules-conflicts-magento/ | CC-MAIN-2018-22 | refinedweb | 289 | 74.79 |
Well, I've gotten far enough into my first Python project that I would like to split up the source. From the start, I built a library of dictionaries, which I import at runtime, and this works fine. I discovered that if I wanted to change a variable declared outsid a fuction, I had to declare it as 'global' with the function. I have nearly 100 functions that I'd like to import, rather than maintaining them in the main script. I tried putting them into their own file, but they couldn't see the objects (dictionaries & lists) that were loaded from the first file. So I tried putting them in the same file, but this didn't work either. So I made a class with all the functions inside, still no go. It's not that I haven't read the documentation on namespaces and scoping: it just seems like doubletalk to me. Is there some way I can import functions from a file, and have them behave just as though they are contained in the main script ? Byron Morgan | https://mail.python.org/pipermail/python-list/2003-February/231692.html | CC-MAIN-2018-09 | refinedweb | 181 | 77.16 |
NAME
MPE_Open_graphics - (collectively) opens an X Windows display
SYNOPSIS
#include "mpe.h" int MPE_Open_graphics( handle, comm, display, x, y, w, h, is_collective ) MPE_XGraph *handle; MPI_Comm comm; char display[MPI_MAX_PROCESSOR_NAME+4]; int x, y; int w, h; int is_collective;
INPUT PARAMETERS
comm - Communicator of participating processes display - Name of X window display. If null, display will be taken from the DISPLAY variable on the process with rank 0 in comm . If that is either undefined, or starts with w ":", then the value of display is ‘hostname‘:0 x,y - position of the window. If (-1,-1) , then the user should be asked to position the window (this is a window manager issue). w,h - width and height of the window, in pixels. is_collective - true if the graphics operations are collective; this allows the MPE graphics operations to make fewer connections to the display. If false, then all processes in the communicator comm will open the display; this could exceed the number of connections that your X window server allows. Not yet implemented.
OUTPUT PARAMETER
handle - Graphics handle to be given to other MPE graphics routines.
NOTES
This is a collective routine. All processes in the given communicator must call it, and it has the same semantics as MPI_Barrier (that is, other collective operations can not cross this routine)..
ADDITIONAL NOTES FOR FORTRAN INTERFACE
If Fortran display argument is an empty string, "", display will be taken from the DISPLAY variable on the process with rank 0 in comm . The trailing blanks in Fortran CHARACTER string argument will be ignored.
LOCATION
mpe_graphics.c 12/6/2001 MPE_Open_graphics(4) | http://manpages.ubuntu.com/manpages/karmic/en/man4/MPE_Open_graphics.4.html | CC-MAIN-2013-20 | refinedweb | 265 | 54.32 |
Re: SOAP::Lite server/VB .Net client
Expand Messages
- Duncan
Thanks for the suggestion - I added ->uri(namespace) for each data
element, but unfortunately, I still receive the same result.
Re: the XML syntax -- I put the XML output in XML Spy and it tells me
that it is valid (i.e. the XML output is correct)
Any other ideas? I've been researching this on the Web and am not
finding a lot of SOAP::Lite server to VB .Net client info.
Regards,
Dave
--- In soaplite@yahoogroups.com, Duncan Cameron <dcameron@b...> wrote:
> On 2002-12-10 DaveHod <davehod wrote:
> >I have a simple web service written in Perl with the latest
> >SOAP::Lite. (The service returns a complex type)
> >
> >The service works great with a Java client (using Apache Axis)
> >However, I cannot get it to work properly using a VB client. I
have a
> >proxy running and can see both the request and response msgs, which
> >are functioning properly. However, when VB catches the response, it
> >gives me the following error:
> >
> >"An unhandled exception of type 'System.InvalidOperationException'
> >occurred in system.xml.dll
> >Additional information: There is an error in XML document (1,
1153)."
> >
> >Are there any known issues with SOAP::Lite and .Net clients?
> >
> >I suspect that problem is that I need to modify the return of my
call
> >somehow, but am not sure what that would be. My return code is
below:
> >
> > return SOAP::Data->name('Response') ->type('SOAPStruct' =>
> > \SOAP::Data->value(
> > SOAP::Data->name('authorized') ->type('boolean'
=>
> >$response->{authorized}),
> > SOAP::Data->name('high') ->type('string'
=>
> >$response->{high}),
> > SOAP::Data->name('low') ->type('string'
=>
> >$response->{low}),
> > SOAP::Data->name('membername') ->type('string'
=>
> >$response->{membername}),
> > SOAP::Data->name('imageURL') ->type('string'
=>
> >$response->{imageURL}),
> > SOAP::Data->name('status') ->type('string'
=>
> >$response->{status}),
> > SOAP::Data->name('code') ->type('integer'
=>
> >$response->{code})
> > )
> > );
> >
> >
> >Dave
> >
> You probably want to have a namespace on the returned data items.
> See the INTEROPERABILITY section of the SOAP::Lite docs.
>
> Also, "There is an error in XML document (1, 1153)" is pointing to
> line 1, position 1153, which should show you what the problem is.
>
>
> Regards,
> Duncan Cameron
Your message has been successfully submitted and would be delivered to recipients shortly. | https://groups.yahoo.com/neo/groups/soaplite/conversations/topics/2189?var=1 | CC-MAIN-2015-18 | refinedweb | 366 | 55.84 |
Hi i am trying to construct a GameOfLife on java. I seem to be doign everything but the setpattern method correctly. the code compiles when but when trying to run the main method etc. or creating my own it does not let me.
this is my constructor and my setpattern method could anyone help.. i have been told by a colleague to write a forloop for the set pattern but i do not know how.
01 public class GameOfLife implements GameOfLife2DInterface {
02 private int rows;
03 private int columns;
04 private int grid[][];
05 private int emptyGrid[][];
06
07 /**
08 * Constructor for objects of class GameOfLife
09 */
10 public GameOfLife(int columns, int rows, int[][]pattern){
11 grid = new int [columns][rows];
12 setPattern(columns, rows, pattern);
13 this.columns=columns;
14 this.rows=rows;
15
16 }
17
18 public void setPattern(int columns, int rows, int[][]pattern){
19 grid = pattern;
20
21 }
thanks | http://www.javaprogrammingforums.com/%20loops-control-statements/14177-help-please-gameoflife-loop-help-printingthethread.html | CC-MAIN-2015-48 | refinedweb | 154 | 72.16 |
I'm trying to set up IoC (Castle Windsor) in my MVC 2 project here, using the section in Pro Asp.net MVC Framework book.
However, I cannot compile after creating a custom controller factory as stated in the book.
This part give me error:
// Constructs the controller instance needed to service each request
protected override IController GetControllerInstance(Type controllerType)
{
return (IController) container.Resolve(controllerType);
}
Telling me that no suitable method have been found to override?
Does someone know if there's a problem with the code in the book or something changed with recent versions of things (wont suprise me..got some books on MVC here rendered completely useless with the evolution of asp.net mvc)
View Complete Post
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/links/46745-asp-net-mvc-2---ioc-castle-windsor.aspx | CC-MAIN-2016-44 | refinedweb | 135 | 63.8 |
March 2009 Board reports (see ReportingSchedule).
These reports were due here by Wednesday, 11 March 2009 so that the Incubator PMC can: The winter vacation has just finished for several weeks. Recently, we are preparing some document files like components installation guide and external lib declaration as Bill had told us. Most of the work would be done in several days. We've started to compare api of FFmpeg and vobis、theora. The running demo of Bluesky is under process too.
Next step:
- Waiting for the second code view by our mentor Bill.
- Ideally, we will begin to replace code of FFmpeg by vobis and theora.
Cassandra
Click
Click is a page and component oriented Java web framework.
Click has been incubating since July 2008.
Tasks completed since December:
- Replaced all incompatible licensed libraries
- Click 2.0.1 was released from the Apache Incubator
- New JIRA was created and issues imported from old version
Top priorities:
- Review the current diversity in the developer community
Empire-db
This is an out of schedule board report, that the Incubator PMC asked us to provide due to the following incident:
The situation
A committer “C” of Empire-db had the idea to create and provide an example application that demonstrates how to use Apache Empire-db together with Apache CXF. Initially he intended to write the code himself, but then he found himself too busy and never really got around doing it. So he decided to ask a student S instead to write the code for him using his templates and ideas. S then wrote the code with a little aid of C and he got paid for it. The work contract S had with C said that all rights over the code would exclusively belong to C.
When the coding was finished, C asked S to submit the code using his Apache SVN account. For that C temporarily logged S in from within Eclipse to SVN on one of C’s computers (Please note: the login was performed by C the password itself was not given to S). C then also asked S subscribe and write to the Empire-db-dev mailing list to resolve problems he had with the Maven project layout. C believed that all actions taken were legitimate and in the best interest of the project and the ASF.
The issues
When a Mentor of the Empire-db project became aware of this transaction, he raised strong concerns regarding the following two issues:
- Legal concerns that an ICLA from S would be required for the code that was contributed.
- Security concerns, whether access to the SVN could have been abused by S or the password for the SVN account for C could have been revealed by S.
Furthermore he pointed out, that sharing an account - even temporarily - is not approved by the community and hence must under no circumstances be repeated.
These concerns were also forwarded to the Incubator private mailing list, where the actions taken by C also upset many people. There was a clear verdict, that the mentor’s concerns and disapproval were shared by everyone else.
C was surprised by the reaction of the Incubator PMC and defended himself with the following arguments:
- Since C is the exclusive legal owner of all rights over the code that was submitted, only he could contribute it to the ASF anyway. Hence an ICLA for S is from a legal point of view not required, even though he might be the originator.
- It is very unlikely and there is absolutely no reason to believe that the account has been abused or compromised by S in any way, since the login was only valid for the actual Eclipse session. For people of the same company, working in the same LAN, there might be technically easier ways of compromising an account. Even so he takes full responsibility for everything that is or was done under his account.
C posted his statements on the Empire-db private mailing list and it is unclear whether all people interested in this subject had the opportunity to read these arguments.
The respondents were not all convinced by these arguments and the legal issue still has not been fully resolved. However, still there is a strong common agreement on the disapproval of account sharing.
The resolve
C acknowledges and respects the opinion of the community. As far as the sharing of this account is concerned, he publicly assures not to repeat it with any of this Apache accounts.
In order to resolve any remaining concerns the following actions were taken by C and S as requested from the Incubator board:
- S has signed and submitted an ICLA to the ASF.
-.
- Good progress on the Twitter API, implementation nearly finished..
We've prepared a bug fix release (1.0.2) which has been submitted for an incubator vote. The 1.0.2 release also includes updated licensing information in compliance with Apache standards. A 1.1 release with proper package and namespace changes is being prepared as well. The 1.1 release will also include experimental code for a c and python binding.
Our problem with finding a home for our continuous build continues. Various plans have been proposed and failed due to lack of a Windows-friendly c# build environment. While we will continue for awhile to host this build at Cisco, we need to find a more neutral and open place to a bit more forgiving. constructed interfaces of matrix and vector.
- We implemented sparse/dense matrix-matrix multiplication and dot products.
- We implemented shell and user can use shell to manage matrices.
- We start implementation of the sparse matrix and sparse graph which is a graph with sparse matrix.:
- The corporate CCLA has been received by ASF.
- Initial code contribution has been contributed.
The following is planned for next reporting period:
- Contributed code to be built.
- API Java doc to be built and put onto website.
- Development of reference implementation (RI) of Kato API.
- Development of working T have got a new committer who is Mark Struberg.
- We released the M1 version
- We published our new site via Maven
Belows are the next steps for coming days;
- We will release the M2 version.
- We will create additional documentation in the project web site.
We will implement additional examples that show the usage of the OpenWebBeans
- We will continue to attract new committers into the project.
Pivot
Pivot is an open-source platform for building rich internet applications in Java.
Pivot was accepted into incubation on the 26 January 2009.
The Pivot community missed the last report, largely due to after acceptance a period of 'no action' ensued. The Pivot project has now taken off. One initial committer is lost in action and has been removed from the initial committer list, as well as the couple of patches that he supplied has been reverted. The remaining 4 committers have submitted CLAs, accounts has been created, authorization setup, Jira has been created, Confluence space has been created, and we are soon to do the initial codebase submission. All activities of setting up the podling has been tracked in
RAT
After a long quiet period, there seems to have been a definite change of momentum. A major stumbling block has been the absence of released version of the codebase after the move to Apache. Once this has happened, it should be possible to start on some more interesting topics.
Preparation of a 0.6 release ongoing (and looking good). Hopefully due in April.
The scan code that generates (by auditing the distribution directories) is probably just about good enough for wider distribution and use by other projects at Apache. This will be targeted for release before May.
Discussions are ongoing about a Google SoC originating in Harmony but more naturally in scope at RAT
Top Issues Before Graduation:
- ATM RAT is too small for a TLP but not clearly in scope for any existing TLPs
- Regain momentum. it's
Stonehenge continues to make progress. There is now code committed for Ruby, PHP, Axis2/Java and .NET. We are working on the wiki documentation on how to get started and run the samples. Sun are working on an implementation for Metro and we hope to get some contribution from Apache CXF too. Discussion and mailing lists are slowly getting into place and the SVN and JIRA are all in place and being used.
Main Activities:
- .NET Stock Trader code contributed
- Java and PHP Stock Trader code contributed
- New tree structure for all contributions created
- All existing code moved from contrib to trunk
- new committers from SUN Microsystems identified and came online
- Goals and exit criteria of Milestone 1 release being defined | http://wiki.apache.org/incubator/March2009?highlight=OpenSocial | CC-MAIN-2014-42 | refinedweb | 1,453 | 61.56 |
: Top, Next: Overview, Prev: (dir), Up: (dir) GNU . File: make.info, Node: Overview, Next: Introduction, Prev: Top, Up: Top. * Menu: * Preparing:: Preparing and Running Make * Reading:: On Reading this Text * Bugs:: Problems and Bugs File: make.info, Node: Preparing, Next: Reading, Prev: Overview, Up: Overview Preparing and Running Make ==========================. *Note How to Run `make': Running. File: make.info, Node: Reading, Next: Bugs, Prev: Preparing, Up: Overview 1.1 How to Read This Manual ===========================, *Note An Introduction to Makefiles: Introduction, all of which is introductory. If you are familiar with other `make' programs, see *Note Features of GNU `make': Features, which lists the enhancements GNU `make' has, and *Note Incompatibilities and Missing Features: Missing, which explains the few things GNU `make' lacks that others have. For a quick summary, see *Note Options Summary::, *Note Quick Reference::, and *Note Special Targets::. File: make.info, Node: Bugs, Prev: Reading, Up: Overview 1.2 Problems and Bugs ===================== `make --version'. Be sure also to include the type of machine and operating system you are using. One way to obtain this information is by looking at the final lines of output from the command `make --help'. File: make.info, Node: Introduction, Next: Makefiles, Prev: Overview, Up: Top 2 *Note. * Menu: * File: make.info, Node: Rule Introduction, Next: Simple Makefile, Prev: Introduction, Up: Introduction 2.1 What a Rule Looks Like ========================== A simple makefile consists of "rules" with the following shape: TARGET ... : PREREQUISITES ... COMMAND ... ... A "target" is usually the name of a file that is generated by a program; examples of targets are executable or object files. A target can also be the name of an action to carry out, such as `clean' (*note Phony Targets::). A "prerequisite" . *Note Writing Rules: Rules. A makefile may contain other text besides rules, but a simple makefile need only contain rules. Rules may look somewhat more complicated than shown in this template, but all fit the pattern more or less. File: make.info, Node: Simple Makefile, Next: How Make Works, Prev: Rule Introduction, Up: Introduction 2.2 A Simple Makefile ===================== prerequisites are files such as `main.c' and `defs.h'. In fact, each `.o' file is both a target and a prerequisite. Commands include `cc -c main.c' and "phony targets". *Note Phony Targets::, for information about this kind of target. *Note Errors in Commands: Errors, to see how to cause `make' to ignore errors from `rm' or any other command. File: make.info, Node: How Make Works, Next: Variables Simplify, Prev: Simple Makefile, Up: Introduction 2.3 How `make' Processes a Makefile =================================== By default, `make' starts with the first target (not targets whose names start with `.'). This is called the "default goal". ("Goals" are the targets that `make' strives ultimately to update. You can override this behavior using the command line (*note Arguments to Specify the Goals: Goals.) or with the `.DEFAULT_GOAL' special variable (*note Other Special Variables:'. File: make.info, Node: Variables Simplify, Next: make Deduces, Prev: How Make Works, Up: Introduction 2.4 Variables Make Makefiles Simpler ==================================== (*note How to Use Variables: Using)' (*note How to Use Variables: Using) File: make.info, Node: make Deduces, Next: Combine By Prerequisite, Prev: Variables Simplify, Up: Introduction 2.5 Letting `make' Ded. *Note Using Implicit Rules: Implicit Rules. When a `.c' file is used automatically in this way, it is also automatically added to the list of prerequisites. We can therefore omit the `.c' files from the prerequisites, *Note Phony Targets::, and *Note Errors in Commands: Errors.) Because implicit rules are so convenient, they are important. You will see them used frequently. File: make.info, Node: Combine By Prerequisite, Next: Cleanup, Prev: make Deduces, Up: Introduction 2.6 Another Style of Makefile =============================. File: make.info, Node: Cleanup, Prev: Combine By Prerequisite, Up: Introduction 2.7 Rules for Cleaning the Directory ==================================== *Note Phony Targets::, and *Note Errors in Commands: Errors.) `make' with no arguments. In order to make the rule run, we have to type `make clean'. *Note How to Run `make': Running. File: make.info, Node: Makefiles, Next: Rules, Prev: Introduction, Up: Top 3 Writing Makefiles ******************* The information that tells `make' how to recompile a system comes from reading a data base called the . File: make.info, Node: Makefile Contents, Next: Makefile Names, Prev: Makefiles, Up: Makefiles 3.1, called the "prerequisites" of the target, and may also give commands to use to create or update the targets. *Note Writing Rules: Rules. * An "implicit rule" says when and how to remake a class of files based on their names. It describes how a target may depend on a file with a name similar to the target and gives commands to create or update such a target. *Note Using Implicit Rules: Implicit Rules. * A "variable definition" is a line that specifies a text string value for a variable that can be substituted into the text later. The simple makefile example shows a variable definition for `objects' as a list of all object files (*note Variables Make Makefiles Simpler: Variables Simplify.). * A "directive" is a command for `make' to do something special while reading the makefile. These include: * Reading another makefile (*note Including Other Makefiles: Include.). * Deciding (based on the values of variables) whether to use or ignore a part of the makefile (*note Conditional Parts of Makefiles: Conditionals.). * Defining a variable from a verbatim string containing multiple lines (*note Defining Variables Verbatim: Defining.). * `#' in a line of a makefile starts a `#', escape it with a backslash (e.g., `\#'). command script text, depending on the context in which the variable is evaluated. File: make.info, Node: Makefile Names, Next: Include, Prev: Makefile Contents, Up: Makefiles 3.2 What Name to Give Your Makefile ===================================. *Note Using Implicit Rules:'. File: make.info, Node: Include, Next: MAKEFILES Variable, Prev: Makefile Names, Up: Makefiles 3.3 Including Other Makefiles =============================. *Note How to Use Variables: Using (*note Setting Variables: Setting.) or pattern rules (*note Defining and Redefining Pattern'. *Note Automatic Prerequisites::. If the specified name does not start with a slash, and the file is not found in the current directory, several other directories are searched. First, any directories you have specified with the `-I' or `--include-dir' option are searched (*note Summary of Options: Options Summary.).. *Note How Makefiles Are Remade: Remaking Makefiles. acts like `include' in every way except that there is no error (not even a warning) if any of the FILENAMES do not exist. For compatibility with some other `make' implementations, `sinclude' is another name for `-include'. ---------- Footnotes ---------- (1) GNU Make compiled for MS-DOS and MS-Windows behaves as if PREFIX has been defined to be the root of the DJGPP tree hierarchy. File: make.info, Node: MAKEFILES Variable, Next: MAKEFILE_LIST Variable, Prev: Include, Up: Makefiles 3 (*note' (*note (*note. *Note Including Other Makefiles: Include. File: make.info, Node: MAKEFILE_LIST Variable, Next: Special Variables, Prev: MAKEFILES Variable, Up: Makefiles 3.5 The Variable *Note Text Functions::, for more information on the `word' and `words' functions used above. *Note The Two Flavors of Variables: Flavors, for more information on simply-expanded (`:=') variable definitions. File: make.info, Node: Special Variables, Next: Remaking Makefiles, Prev: MAKEFILE_LIST Variable, Up: Makefiles 3.6 Other Special Variables =========================== GNU `make' also supports other special variables. Unless otherwise documented here, these values lose their special properties if they are set by a makefile or on the command line. `.DEFAULT_GOAL' Sets the default goal to be used if no targets were specified on the command line (*note Arguments to Specify the Goals: illegal and will result in an error. `MAKE_RESTARTS' This variable is set only if this instance of `make' has restarted (*note How Makefiles Are Remade: Remaking Makefiles.): it will contain the number of times this instance has restarted. Note this is not the same as recursion (counted by the `MAKELEVEL' variable). You should not set, modify, or export this variable. `.VARIABLES' Expands to a list of the _names_ of all global variables defined so far. This includes variables which have empty values, as well as built-in variables (*note Variables Used by Implicit Rules: Implicit Variables.),: `archives' Supports `ar' (archive) files using special filename syntax. *Note Using `make' to Update Archive Files: Archives. `check-symlink' Supports the `-L' (`--check-symlink-times') flag. *Note Summary of Options: Options Summary. `else-if' Supports "else if" non-nested conditionals. *Note Syntax of Conditionals: Conditional Syntax. `jobserver' Supports "job server" enhanced parallel builds. *Note Parallel Execution: Parallel. `second-expansion' Supports secondary expansion of prerequisite lists. `order-only' Supports order-only prerequisites. *Note Types of Prerequisites: Prerequisite Types. `target-specific' Supports target-specific and pattern-specific variable assignments. *Note Target-specific Variable Values: Target-specific. `.INCLUDE_DIRS' Expands to a list of directories that `make' searches for included makefiles (*note Including Other Makefiles: Include.). File: make.info, Node: Remaking Makefiles, Next: Overriding Makefiles, Prev: Special Variables, Up: Makefiles 3.7 How (*note (*note Using Empty Commands: Empty Commands.). If the makefiles specify a double-colon rule to remake a file with commands but no prerequisites, that file will always be remade (*note; *note (*note (*note'. File: make.info, Node: Overriding Makefiles, Next: Reading Makefiles, Prev: Remaking Makefiles, Up: Makefiles 3.8 Overriding Part of Another Make. *Note Pattern Rules::, for more information on pattern rules. For example, if you have a makefile called `Makefile' that says how to make the target `foo' (and other targets), you can write a makefile called `GNUmakefile' that contains: foo: frobnicate > foo %: force @$(MAKE) -f Makefile $@ force: ;! File: make.info, Node: Reading Makefiles, Next: Secondary Expansion, Prev: Overriding Makefiles, Up: Makefiles 3.9 How `make' Reads. Variable. File: make.info, Node: Secondary Expansion, Prev: Reading Makefiles, Up: Makefiles 3.10 Secondary Expansion ======================== In the previous section we learned that GNU `make' works in two distinct phases: a read-in phase and a target-update phase (*note How `make' Reads a Makefile: Reading Makefiles.). static command script. command scripts.' respectively. Rules undergo secondary expansion in makefile order, except that the rule with the command script *Note Implicit Rule Search Algorithm:. File: make.info, Node: Rules, Next: Commands, Prev: Makefiles, Up: Top 4 Writing. (*Note Defining and Redefining Pattern Rules: Pattern Rules.) Therefore, we usually write the makefile so that the first rule is the one for compiling the entire program or all the programs described by the makefile (often with a target called `all'). *Note Arguments to Specify the Goals:. File: make.info, Node: Rule Example, Next: Rule Syntax, Prev: Rules, Up: Rules 4.1 Rule Example ================: * How to decide whether `foo.o' is out of date: it is out of date if it does not exist, or if either `foo.c' or `defs.h' is more recent than it. * How to update the file `foo.o': by running `cc' as stated. The command does not explicitly mention `defs.h', but we presume that `foo.c' includes it, and that that is why `defs.h' was added to the prerequisites. File: make.info, Node: Rule Syntax, Next: Prerequisite Types, Prev: Rule Example, Up: Rules 4.2 Rule Syntax =============== In general, a rule looks like this: TARGETS : PREREQUISITES COMMAND ... or like this: TARGETS : PREREQUISITES ; COMMAND COMMAND ... The TARGETS are file names, separated by spaces. Wildcard characters may be used (*note Using Wildcard Characters in File Names: Wildcards.) and a name of the form `A(M)' represents member M in archive file A (*note Archive Members as Targets: Archive Members.). Usually there is only one target per rule, but occasionally there is a reason to have more (*note Multiple Targets in a Rule: Multiple Targets.). The. *Note Writing the Commands in Rules: Commands. Because dollar signs are used to start `make' variable references, if you really want a dollar sign in a target or prerequisite you must write two of them, `$$' (*note How to Use Variables: Using Variables.). If you have enabled secondary expansion (*note Secondary Expansion::) and you want a literal dollar sign in the prerequisites lise, you must actually write _four_ dollar signs (`$$$$'). (*note (*note Writing the Commands in Rules: Commands.). File: make.info, Node: Prerequisite Types, Next: Wildcards, Prev: Rule Syntax, Up: Rules 4.3 Types of Prerequisites ========================== There are actually two different types of prerequisites understood by GNU `make': normal prerequisites such as described in the previous section, and ). File: make.info, Node: Wildcards, Next: Directory Search, Prev: Prerequisite Types, Up: Rules 4.4 Using Wildcard Characters in File Names =========================================== commands'. * Menu: * Wildcard Examples:: Several examples * Wildcard Pitfall:: Problems to avoid. * Wildcard Function:: How to cause wildcard expansion where it does not normally take place. File: make.info, Node: Wildcard Examples, Next: Wildcard Pitfall, Prev: Wildcards, Up: Wildcards 4 *Note Empty Target Files to Record Events: Empty Targets. (The automatic variable `$?' is used to print only those files that have changed; see *Note) *Note Wildcard Function::. File: make.info, Node: Wildcard Pitfall, Next: Wildcard Function, Prev: Wildcard Examples, Up: Wildcards 4.4.2 Pitfalls of Using Wildcards ---------------------------------. *Note The Function `wildcard': Wildcard Function.. File: make.info, Node: Wildcard Function, Prev: Wildcard Pitfall, Up: Wildcards 4 (*note'. *Note Functions for String Substitution and Analysis: Text Functions.). *Note The Two Flavors of Variables: Flavors, for an explanation of `:=', which is a variant of `='.) File: make.info, Node: Directory Search, Next: Phony Targets, Prev: Wildcards, Up: Rules 4. File: make.info, Node: General Search, Next: Selective Search, Prev: Directory Search, Up: Directory Search 4.5. *Note Writing Shell Commands with Directory Search: Commands'. File: make.info, Node: Selective Search, Next: Search Algorithm, Prev: General Search, Up: Directory Search 4.5.2 The `vpath' Directive ---------------------------; *note Defining and Redefining Pattern'. File: make.info, Node: Search Algorithm, Next: Commands/Search, Prev: Selective Search, Up: Directory Search 4.5.3 How Directory Searches are: 1. If a target file does not exist at the path specified in the makefile, directory search is performed. 2. If the directory search is successful, that path is kept and this file is tentatively stored as the target. 3. All prerequisites of this target are examined using this same method. 4. After processing the prerequisites, the target may or may not need to be rebuilt: a. If the target does _not_ need to be rebuilt, the path to the file found during directory search is used for any prerequisite lists which contain this target. In short, if `make' doesn't need to rebuild the target then you use the path found via directory search. b. If the target _does_ need to be rebuilt (is out-of-date), the pathname found during directory search is _thrown away_, and the target is rebuilt using the file name specified in the makefile. In short, if `make' must. File: make.info, Node: Commands/Search, Next: Implicit/Search, Prev: Search Algorithm, Up: Directory Search 4.5.4 Writing Shell Commands with Directory Search -------------------------------------------------- `$^' (*note Automatic Variables::). For instance, the value of `$^' is a list of all the prerequisites; *note $@ File: make.info, Node: Implicit/Search, Next: Libraries/Search, Prev: Commands/Search, Up: Directory Search 4.5.5 Directory Search and Implicit Rules ----------------------------------------- The search through the directories specified in `VPATH' or with `vpath' also happens during consideration of implicit rules (*note Using Implicit Rules:. File: make.info, Node: Libraries/Search, Prev: Implicit/Search, Up: Directory Search 4.5.6 Directory Search for Link Libraries ----------------------------------------- foo : foo.c -lcurses cc $^ -o $@. File: make.info, Node: Phony Targets, Next: Force Targets, Prev: Directory Search, Up: Rules 4.6' (*note Special Built-in Target Names: Special Targets.) (*note Another example of the usefulness of phony targets is in conjunction with recursive invocations of `make' (for more information, see *Note Recursive Use of `make': Recursion.). (*note Parallel Execution: (*note Arguments to Specify the Goals:'). Phoniness is not inherited: the prerequisites of a phony target are not themselves phony, unless explicitly declared to be so. When one phony target is a prerequisite File: make.info, Node: Force Targets, Next: Empty Targets, Prev: Phony Targets, Up: Rules 4.7. *Note Phony Targets::. File: make.info, Node: Empty Targets, Next: Special Targets, Prev: Force Targets, Up: Rules 4.8 Empty Target Files to Record Events ======================================= (*note Automatic Variables::). File: make.info, Node: Special Targets, Next: Multiple Targets, Prev: Empty Targets, Up: Rules 4.9 Special Built-in Target Names =================================. *Note Phony Targets: Phony Targets. `.SUFFIXES' The prerequisites of the special target `.SUFFIXES' are the list of suffixes to be used in checking for suffix rules. *Note Old-Fashioned Suffix Rules: Suffix Rules. `.DEFAULT' The commands specified for `.DEFAULT' are used for any target for which no rules are found (either explicit rules or implicit rules). *Note Last Resort::. If `.DEFAULT' commands are specified, every file mentioned as a prerequisite, but not as a target in a rule, will have these commands executed on its behalf. *Note Implicit Rule Search Algorithm: Implicit Rule Search. `. *Note Chains of Implicit Rules: Chained Rules. `.INTERMEDIATE' with no prerequisites has no effect. `.SECONDARY' The targets which `.SECONDARY' depends on are treated as intermediate files, except that they are never automatically deleted. *Note Chains of Implicit Rules: Chained. *Note Secondary Expansion: Secondary Expansion. The prerequisites of the special target `.SUFFIXES' are the list of suffixes to be used in checking for suffix rules. *Note Old-Fashioned Suffix Rules: Suffix Rules. `.DELETE_ON_ERROR' If `.DELETE_ON_ERROR' is mentioned as a target anywhere in the makefile, then `make' will delete the target of a rule if it has changed and its commands exit with a nonzero exit status, just as it does when it receives a signal. *Note Errors in Commands: Errors. `. *Note Errors in Commands: Errors. `: .LOW_RESOLUTION_TIME: dst dst: src cp -p src dst Since `cp -p' discards the subsecond. *Note Command Echoing: Echoing. If you want to silence all commands for a particular run of `make', use the `-s' or `--silent' option (*note Options Summary::). `.EXPORT_ALL_VARIABLES' Simply by being mentioned as a target, this tells `make' to export all variables to child processes by default. *Note Communicating Variables to a Sub-`make': Variables/Recursion. ` `.'. *Note Old-Fashioned Suffix Rules: Suffix Rules. File: make.info, Node: Multiple Targets, Next: Multiple Rules, Prev: Special Targets, Up: Rules 4.10 (*note Automatic Variables::). For example:'. *Note Functions for String Substitution and Analysis: Text Functions,". *Note Static Pattern Rules: Static Pattern. File: make.info, Node: Multiple Rules, Next: Static Pattern, Prev: Multiple Targets, Up: Rules 4.11 Multiple Rules for One Target ================================== commands which are defined in different parts of your makefile; you can use "double-colon rules" (*note' (*note Overriding Variables: Overriding.). *note Using Implicit Rules: Implicit Rules.). File: make.info, Node: Static Pattern, Next: Double-Colon, Prev: Multiple Rules, Up: Rules 4.12 Static Pattern_. * Menu: * Static Usage:: The syntax of static pattern rules. * Static versus Implicit:: When are they better than implicit rules? File: make.info, Node: Static Usage, Next: Static versus Implicit, Prev: Static Pattern, Up: Static Pattern 4.12.1 Syntax of Static Pattern Rules ------------------------------------- Here is the syntax of a static pattern rule: TARGETS ...: TARGET-PATTERN: PREREQ-PATTERNS ... COMMANDS ... The TARGETS list specifies the targets that the rule applies to. The targets can contain wildcard characters, just like the targets of ordinary rules (*note Using Wildcard Characters in File Names: Wildcards.). all: $(objects) $(objects): %.o: %.c $(CC) -c $(CFLAGS) $< -o $@ Here `$<' is the automatic variable that holds the name of the prerequisite and `$@' is the automatic variable that holds the name of the target; see *Note Automatic Variables::. Each target specified must match the target pattern; a warning is issued for each target that does not. If you have a list of files, only some of which will match the pattern, you can use the `filter' function to remove nonmatching file names (*note Functions for String Substitution and Analysis: Text Functions.):'. File: make.info, Node: Static versus Implicit, Prev: Static Usage, Up: Static Pattern 4.12.2 Static Pattern Rules versus Implicit Rules ------------------------------------------------- A static pattern rule has much in common with an implicit rule defined as a pattern rule (*note Defining and Redefining Pattern: *. File: make.info, Node: Double-Colon, Next: Automatic Prerequisites, Prev: Static Pattern, Up: Rules 4.13 Double-Colon. *Note Using Implicit Rules: Implicit Rules. File: make.info, Node: Automatic Prerequisites, Prev: Double-Colon, Up: Rules; *note Chains of Implicit Rules: Chained (*note Include::). In GNU `make', the feature of remaking makefiles makes this practice obsolete--you need never tell `make' explicitly to regenerate the prerequisites, because it always regenerates any makefile that is out of date. *Note $@.$$$$ *Note. *Note Options Controlling the Preprocessor: (gcc.info)Preprocessor Options,. ::. Note that the `.d' files contain target definitions; you should be sure to place the `include' directive _after_ the first, default goal in your makefiles or run the risk of having a random object file become the default goal. *Note How Make Works::. File: make.info, Node: Commands, Next: Using Variables, Prev: Rules, Up: Top 5 Writing the Commands in Rules ******************************* `/bin/sh' unless the makefile specifies otherwise. *Note Command Execution: Execution. * Menu: *. File: make.info, Node: Command Syntax, Next: Echoing, Prev: Commands, Up: Commands 5.1 Command Syntax ================== Makefiles have the unusual property that there are really two distinct syntaxes in one file. Most of the makefile uses `make' syntax (*note Writing Makefiles: Makefiles.). However, commands are meant to be interpreted by the shell and so they are written using shell syntax. The : * A blank line that begins with a tab is not blank: it's an empty command (*note Empty Commands::). * A comment in a command line is not a `make' comment; it will be passed to the shell as-is. Whether the shell treats it as a comment or not depends on your shell. * A variable definition in a "rule context" which is indented by a tab as the first character on the line, will be considered a command line, not a `make' variable definition, and passed to the shell. * A conditional expression (`ifdef', `ifeq', etc. *note Syntax of Conditionals: Conditional Syntax.) in a "rule context" which is indented by a tab as the first character on the line, will be considered a command line and be passed to the shell. * Menu: * Splitting Lines:: Breaking long command lines for readability. * Variables in Commands:: Using `make' variables in commands. File: make.info, Node: Splitting Lines, Next: Variables in Commands, Prev: Command Syntax, Up: Command Syntax 5.1.1 Splitting Command Lines ----------------------------- One of the few ways in which run one shell with a command script command. (*note Target-specific Variable Values: Target-specific.) to obtain a tighter correspondence between the variable and the command that uses it. File: make.info, Node: Variables in Commands, Prev: Splitting Lines, Up: Command Syntax 5.1.2 Using Variables in Commands --------------------------------- The other way in which `make' processes commands is by expanding any variable references in them (*note Basics of Variable References: Reference.). File: make.info, Node: Echoing, Next: Execution, Prev: Command Syntax, Up: Commands 5.2 Command Echoing ===================. *Note Summary of Options: Options Summary. (*note Special Built-in Target Names: Special Targets.). `.SILENT' is essentially obsolete since `@' is more flexible. File: make.info, Node: Execution, Next: Parallel, Prev: Echoing, Up: Commands 5.3 Command Execution ===================== When it is time to execute commands to update a target, they are executed by invoking a new subshell for each command line. (In practice, `make' may take shortcuts that do not affect the results.) *Please note:* this implies that setting shell variables and invoking shell commands such as `cd' that set a context local to each process will not affect the following command lines.(1) If you want to use `cd' to affect the next statement, put both statements in a single command). * Menu: * Choosing the Shell:: How `make' chooses the shell used to run commands. ---------- Footnotes ---------- (1) On MS-DOS, the value of current working directory is *global*, so changing it _will_ affect the following command lines on those systems. File: make.info, Node: Choosing the Shell, Prev: Execution, Up: Execution 5.3.1 Choosing the Shell ------------------------ The program used as the shell is taken from the variable `SHELL'. If this variable is not set in your makefile, the program `/bin/sh' is used as the shell. Unlike most variables, the variable `SHELL' is never set from the environment. This is because the `SHELL' environment variable is used to specify your personal choice of shell program for interactive use. It would be very bad for personal choices like this to affect the functioning of makefiles. *Note Variables from the Environment: Environment. Furthermore, when you do set `SHELL' in your makefile that value is _not_ exported in the environment to commands that `make' invokes. Instead, the value inherited from the user's environment, if any, is exported. You can override this behavior by explicitly exporting `SHELL' (*note Communicating Variables to a Sub-`make': Variables/Recursion.), forcing it to be passed in the environment to commands. DOS and Windows ...................................: 1. In the precise place pointed to by the value of `SHELL'. For example, if the makefile specifies `SHELL = /bin/sh', `make' will look in the directory `/bin' on the current drive. 2. In the current directory. 3. In each of the directories in the `PATH' variable, `SHELL = /bin/sh' (as many Unix makefiles do), will work on MS-DOS unaltered if you have e.g. `sh.exe' installed in some directory along your `PATH'. File: make.info, Node: Parallel, Next: Errors, Prev: Execution, Up: Commands 5. `make' invocations raises issues. For more information on this, see 5.5 Errors in Commands ====================== prerequisites.. *Note Summary of Options: Options Summary. command is killed by a signal; *note Interrupts::.. File: make.info, Node: Interrupts, Next: Recursion, Prev: Errors, Up: Commands 5.6 Interrupting or Killing . File: make.info, Node: Recursion, Next: Sequences, Prev: Interrupts, Up: Commands 5.7 Recursive Use of (*note Summary of Options: Options Summary.): `.PHONY' (for more discussion on when this is useful, see *Note). *, Prev: Recursion, Up: Recursion 5.7.1 How the `MAKE' Variable. *Note Instead of Executing the Commands: Instead of Execution. This special feature is only enabled if the `MAKE' variable appears directly in the command script: it does not apply if the `MAKE' variable is referenced through expansion of another variable. In the latter case you must use the `+' token to get these special effects. Choosing the Shell::. The special variable `MAKEFLAGS' is always exported (unless you unexport it). `MAKEFILES' is exported if you set it to anything. `make' automatically passes down variable values that were defined on the command line, by putting them in the `MAKEFLAGS' variable. 5.7.3 Communicating Options to a Sub-. 5.7.4 The `--print-directory'-`make's. `make' will not automatically turn on `-w' if you also use `-s', which says to be silent, or if you use `--no-print-directory' to explicitly disable it. File: make.info, Node: Sequences, Next: Empty Commands, Prev: Recursion, Up: Commands 5.8 Defining Canned Command Sequences =====================================. *Note Defining Variables Verbatim: Defining, (*note Basics of Variable References: Reference.). (*note Using Implicit Rules:. *Note Writing the Commands in Rules: Commands.. (*Note Command Echoing: Echoing, for a full explanation of `@'.) File: make.info, Node: Empty Commands, Prev: Sequences, Up: Commands 5.9 Using Empty Commands ========================; *note Implicit Rules:: and *note Defining Last-Resort Default Rules: Last Resort.).. *Note Phony Targets: Phony Targets, for a better way to do this. File: make.info, Node: Using Variables, Next: Conditionals, Prev: Commands, Up: Top 6 How to Use Variables **********************' (*note Communicating Variables to a Sub-`make': Variables/Recursion.). (*note Overriding Variables: Overriding.). A few variables have names that are a single punctuation character or just a few characters. These are the "automatic variables", and they have particular specialized uses. *Note. File: make.info, Node: Reference, Next: Flavors, Prev: Using Variables, Up: Using Variables 6.1 Basics of Variable References ================================= (*note Automatic Variables::). File: make.info, Node: Flavors, Next: Advanced, Prev: Reference, Up: Using Variables 6.2 `=' (*note Setting Variables: Setting.) or by the `define' directive (*note Defining Variables Verbatim: Defining.). (*note Functions for Transforming Text: Functions.) `:=' (*note Setting Variables: Setting.).. (*Note The `shell' Function: Shell Function.) This example also shows use of the variable `MAKELEVEL', which is changed when it is passed down from level to level. (*Note Communicating Variables to a Sub-`make': Variables/Recursion, (*note Functions for Transforming Text: Functions.). (*note The `origin' Function: Origin Function.): ifeq ($(origin FOO), undefined) FOO = bar endif Note that a variable set to an empty value is still defined, so `?=' will not set that variable. File: make.info, Node: Advanced, Next: Values, Prev: Flavors, Up: Using Variables 6.3 Advanced Features for Reference to Variables ================================================ This section describes some advanced features you can use to reference variables in more flexible ways. * Menu: * Substitution Refs:: Referencing a variable with substitutions on the value. * Computed Names:: Computing the name of the variable to refer to. File: make.info, Node: Substitution Refs, Next: Computed Names, Prev: Advanced, Up: Advanced 6.3.1 Substitution References -----------------------------'. *Note Setting Variables: Setting. A substitution reference is actually an abbreviation for use of the `patsubst' expansion function (*note Functions for String Substitution and Analysis: Text Functions.).))'. *Note Functions for String Substitution and Analysis: Text Functions, for a description of the `patsubst' function. For example: foo := a.o b.o c.o bar := $(foo:%.o=%.c) sets `bar' to `a.c b.c c.c'. File: make.info, Node: Computed Names, Prev: Substitution Refs, Up: Advanced 6.3.2 Computed Variable Names ----------------------------- (*note Functions for Transforming Text: Functions.), just like any other reference. For example, using the `subst' function (*note Functions for String Substitution and Analysis: Text Functions.):" (*note The Two Flavors of Variables: Flavors.), though both are used together in complex ways when doing makefile programming. File: make.info, Node: Values, Next: Setting, Prev: Advanced, Up: Using Variables 6.4 How Variables Get Their Values ================================== Variables can get values in several different ways: * You can specify an overriding value when you run `make'. *Note Overriding Variables: Overriding. * You can specify a value in the makefile, either with an assignment (*note Setting Variables: Setting.) or with a verbatim definition (*note Defining Variables Verbatim: Defining.). * Variables in the environment become `make' variables. *Note Variables from the Environment: Environment. * Several "automatic" variables are given new values for each rule. Each of these has a single conventional use. *Note Automatic Variables::. * Several variables have constant initial values. *Note Variables Used by Implicit Rules: Implicit Variables. File: make.info, Node: Setting, Next: Appending, Prev: Values, Up: Using Variables 6.5 Setting Variables =====================. *Note The Two Flavors of Variables: Flavors. (*note Variables Used by Implicit Rules: Implicit Variables.). Several special variables are set automatically to a new value for each rule; these are called the "automatic" variables (*note Automatic Variables::). If you'd like a variable to be set to a value only if it's not already set, then you can use the shorthand operator `?=' instead of `='. These two settings of the variable `FOO' are identical (*note The `origin' Function: Origin Function.): FOO ?= bar and ifeq ($(origin FOO), undefined) FOO = bar endif File: make.info, Node: Appending, Next: Override Directive, Prev: Setting, Up: Using Variables 6.6 Appending More Text to. *Note The Two Flavors of Variables: Flavors, *Note Setting Variables: Setting, (*note The Two Flavors of Variables: Flavors.).; *note Catalogue of Implicit Rules: Catalogue of. File: make.info, Node: Override Directive, Next: Defining, Prev: Appending, Up: Using Variables 6.7 The `override' Directive ============================ If a variable has been set with a command argument (*note Overriding Variables: Overriding.), *Note Appending More Text to Variables: Appending. *Note Defining Variables Verbatim: Defining. File: make.info, Node: Defining, Next: Environment, Prev: Override Directive, Up: Using Variables 6.8 Defining Variables Verbatim =============================== Another way to set the value of a variable is to use the `define' directive. This directive has an unusual syntax which allows newline characters to be included in the value, which is convenient for defining both canned sequences of commands (*note Defining Canned Command Sequences: Sequences.), and also sections of makefile syntax to use with `eval' (*note Eval Function::). (*note The Two Flavors of Variables: Flavors.). The variable name may contain function and variable references, which are expanded when the directive is read to find the actual variable name to use. You may nest `define' directives: `make' will keep track of nested directives and report an error if they are not all properly closed with `endef'. Note that lines beginning with tab characters are considered part of a command script, so any `define' or `endef' strings appearing on such a line will not be considered `make' operators. command script,. *Note Command Execution: Execution. If you want variable definitions made with `define' to take precedence over command-line variable definitions, you can use the `override' directive together with `define': override define two-lines foo $(bar) endef *Note The `override' Directive: Override Directive. File: make.info, Node: Environment, Next: Target-specific, Prev: Defining, Up: Using Variables 6.9 Variables from the Environment ================================== `-e' flag is specified, then values from the environment override assignments in the makefile. *Note Summary of Options: Options Summary. command script, variables defined in the makefile are placed into the environment of that command. This allows you to pass values to sub-`make' invocations (*note Recursive Use of `make': Recursion.). By default, only variables that came from the environment or the command line are passed to recursive invocations. You can use the `export' directive to pass other variables. *Note Communicating Variables to a Sub-`make': Variables/Recursion, *Note Choosing the Shell::. File: make.info, Node: Target-specific, Next: Pattern-specific, Prev: Environment, Up: Using Variables 6.10 Target-specific Variable Values ==================================== Variable values in `make' are usually global; that is, they are the same regardless of where they are evaluated (unless they're reset, of course). One exception to that is automatic variables (*note or like this: TARGET ... : export VARIABLE-ASSIGNMENT Multiple TARGET values create a target-specific variable value for each member of the target list individually. The VARIABLE-ASSIGNMENT can be any valid form of assignment; recursive (`='), static (`:='), appending (`+='), or conditional (`?='). `-g' in the command script for `prog', but it will also set `CFLAGS' to `-g' in the command scripts that create `prog.o', `foo.o', and . File: make.info, Node: Pattern-specific, Prev: Target-specific, Up: Using Variables 6.11 Pattern-specific Variable Values ===================================== In addition to target-specific variable values (*note Target-specific Variable Values: Target-specific.), GNU : PATTERN ... : VARIABLE-ASSIGNMENT or like this: PATTERN ... : override `-O' for all targets matching the pattern `%.o'. File: make.info, Node: Conditionals, Next: Functions, Prev: Using Variables, Up: Top 7 Conditional Parts of Makefiles ********************************. * Menu: * Conditional Example:: Example of a conditional * Conditional Syntax:: The syntax of conditionals. * Testing Flags:: Conditionals that test flags. File: make.info, Node: Conditional Example, Next: Conditional Syntax, Prev: Conditionals, Up: Conditionals 7.1 Example of a Conditional ============================) File: make.info, Node: Conditional Syntax, Next: Testing Flags, Prev: Conditional Example, Up: Conditionals 7.2 Syntax of Conditionals ========================== TEXT-IF-ONE-IS-TRUE else CONDITIONAL-DIRECTIVE TEXT-IF-TRUE else TEXT-IF (*note (*note Automatic Variables::). To prevent intolerable confusion, it is not permitted to start a conditional in one makefile and end it in another. However, you may write an `include' directive within a conditional, provided you do not attempt to terminate the conditional inside the included file. File: make.info, Node: Testing Flags, Prev: Conditional Syntax, Up: Conditionals 7.3 Conditionals that Test Flags ================================ You can write a conditional that tests `make' command flags such as `-t' by using the variable `MAKEFLAGS' together with the `findstring' function (*note Functions for String Substitution and Analysis: Text Functions.).. *Note Recursive Use of `make': Recursion. File: make.info, Node: Functions, Next: Running, Prev: Conditionals, Up: Top 8 Functions for Transforming Text ********************************* . File: make.info, Node: Syntax of Functions, Next: Text Functions, Prev: Functions, Up: Functions 8.1 Function Call Syntax ========================. File: make.info, Node: Text Functions, Next: File Name Functions, Prev: Syntax of Functions, Up: Functions 8.2 Functions for String Substitution and Analysis ================================================== `fEEt on the strEEt'. `$(patsubst PATTERN,REPLACEMENT,TEXT)' Finds whitespace-separated words in TEXT that match PATTERN and replaces them with REPLACEMENT. Here PATTERN may contain a `%' which acts as a wildcard, matching any number of any characters within a word. If REPLACEMENT also contains a `%', the `%' is replaced by the text that matched the `%' in PATTERN. Only the first `%' in the PATTERN and REPLACEMENT is treated this way; any subsequent `%' is unchanged. `%' (*note Substitution References: Substitution Refs.), `$ (*note Conditionals::). `a' and `' (the empty string), respectively. *Note Testing Flags::, for a practical application of `findstring'. `$(filter PATTERN...,TEXT)' Returns all whitespace-separated words in TEXT that _do_ match any of the PATTERN words, removing any words that _do not_ match. The patterns are written using `%', `mains': $(filter-out $(mains),$(objects)) `$(sort LIST)' Sorts the words of LIST in lexical order, removing duplicate words. The output is a list of words separated by single spaces. Thus, $(sort foo bar lose) returns the value (*note `VPATH' Search Path for All Prerequisites: General Search.). (*note The `override' Directive: Override Directive.). File: make.info, Node: File Name Functions, Next: Conditional Functions, Prev: Text Functions, Up: Functions 8.3 Functions for File Names ============================ `./'. For example, $(dir src/foo.c hacks) produces the result . *Note Using Wildcard Characters in File Names: Wildcards. `$. File: make.info, Node: Conditional Functions, Next: Foreach Function, Prev: File Name Functions, Up: Functions 8.4 Functions for Conditionals ==============================' (*note Syntax of Conditionals: Conditional Syntax.).. File: make.info, Node: Foreach Function, Next: Call Function, Prev: Conditional Functions, Up: Functions 8.5 The `foreach' Function ==========================. *Note The Two Flavors of Variables: Flavors.. File: make.info, Node: Call Function, Next: Value Function, Prev: Foreach Function, Up: Functions 8.6 The `call' Function ======================='. File: make.info, Node: Value Function, Next: Eval Function, Prev: Call Function, Up: Functions 8.7 The `value' Function ======================== (*note Eval Function::). File: make.info, Node: Eval Function, Next: Origin Function, Prev: Value Function, Up: Functions 8.8 The `eval' Function ======================= (*note) File: make.info, Node: Origin Function, Next: Flavor Function, Prev: Eval Function, Up: Functions 8.9 The `origin' Function =========================: `undefined' if VARIABLE was never defined. `default' if VARIABLE has a default definition, as is usual with `CC' and so on. '. *Note Functions for String Substitution and Analysis: Text Functions. File: make.info, Node: Flavor Function, Next: Shell Function, Prev: Origin Function, Up: Functions 8.10 The `flavor' Function ========================== The `flavor' function is unlike most other functions (and like `origin' function) in that it does not operate on the values of variables; it tells you something _about_ a variable. Specifically, it tells you the flavor of a variable (*note The Two Flavors of Variables: Flavors.). The syntax of the `flavor' function is: $(flavor that identifies the flavor of the variable VARIABLE: `undefined' if VARIABLE was never defined. `recursive' if VARIABLE is a recursively expanded variable. `simple' if VARIABLE is a simply expanded variable. File: make.info, Node: Shell Function, Next: Make Control Functions, Prev: Flavor Function, Up: Functions 8.11 The `shell' Function ========================= The `shell' function is unlike any other function other than the `wildcard' function (*note The Function `wildcard': Wildcard Function.) in that it communicates with the world outside of `make'. The `shell' function performs the same function that backquotes (``') (*note How `make' Reads a Makefile: Reading Makefiles.). Because this function involves spawning a new shell, you should carefully consider the performance implications of using the `shell' function within recursively expanded variables vs. simply expanded variables (*note The Two Flavors of Variables: Flavors.).)' (as long as at least one `.c' file exists). File: make.info, Node: Make Control Functions, Prev: Shell Function, Up: Functions 8.12 Functions That Control Make ================================ command script. File: make.info, Node: Running, Next: Implicit Rules, Prev: Functions, Up: Top 9 How to Run `-q' flag and `make' determines that some target is not already up to date. *Note Instead of Executing the Commands: Instead of Execution. * File: make.info, Node: Makefile Arguments, Next: Goals, Prev: Running, Up: Running 9.1 Arguments to Specify the Makefile ===================================== (*note Writing Makefiles: Makefiles.). File: make.info, Node: Goals, Next: Instead of Execution, Prev: Makefile Arguments, Up: Running 9.2 Arguments to Specify the Goals ================================== (*note Other Special Variables: (::, for a detailed list of all the standard target names which GNU software packages use. `all' Make all the top-level targets the makefile knows about. `clean' Delete all files that are normally created by running `make'. `mostlyclean' Like `clean', but may refrain from deleting a few files that people normally don't want to recompile. For example, the `mostlyclean' target for GCC does not delete `libgcc.a', because recompiling it is rarely necessary and takes a lot of time. `distclean' `realclean' `clobber' Any of these targets might be defined to delete _more_ files than `clean' does. For example, this would delete configuration files or links that you would normally create as preparation for compilation, even if the makefile itself cannot create these files. `install' Copy the executable file into a directory that users typically search for commands; copy any auxiliary files that the executable uses into the directories where it will look for them. `print' Print listings of the source files that have changed. `tar' Create a tar file of the source files. `shar' Create a shell archive (shar file) of the source files. `dist' Create a distribution file of the source files. This might be a tar file, or a shar file, or a compressed version of one of the above, or even more than one of the above. `TAGS' Update a tags table for this program. `check' `test' Perform self tests on the program this makefile builds. File: make.info, Node: Instead of Execution, Next: Avoiding Compilation, Prev: Goals, Up: Running 9.3 Instead of Executing the Commands ===================================== The makefile tells `make' how to tell whether a target is up to date, and how to update each target. But updating the targets is not always what you want. Certain options specify other activities for `make'. `-n' `--just-print' `--dry-run' `--recon' "No-op". The activity is to print what commands would be used to make the targets up to date, but not actually execute them. `-t' `--touch' "Touch". The activity is to mark the targets as up to date without actually changing them. In other words, `make' pretends to compile the targets but does not really change their contents. `-q' `--question' "Question". The activity is to find out silently whether the targets are up to date already; but execute no commands in either case. In other words, neither compilation nor output will occur. `-W FILE' `--what-if=FILE' `--assume-new=FILE' `--new-file=FILE' .) The `-W' flag provides two features: * If you also use the `-n' or `-q' flag, you can see what `make' would do if you were to modify some files. * Without the `-n' or `-q' flag, when `make' is actually executing commands, the `-W' flag can direct `make' to act as if some files had been modified, without actually modifying the files. Note that the options `-p' and `-v' allow you to obtain other information about `make' or about the makefiles in use (*note Summary of Options: Options Summary.). File: make.info, Node: Avoiding Compilation, Next: Overriding, Prev: Instead of Execution, Up: Running 9.4 Avoiding Recompilation of Some: 1. Use the command `make' to recompile the source files that really need recompilation, ensuring that the object files are up-to-date before you begin. 2. Make the changes in the header files. 3. Use the command `make -t' to mark all the object files as up to date. The next time you run " ( 9.5 Overriding Variables ========================. *Note Variables Used by Implicit Rules: Implicit Variables,' (*note The `override' Directive: Override Directive.). File: make.info, Node: Testing, Next: Options Summary, Prev: Overriding, Up: Running 9.6 Testing the Compilation of a Program ======================================== (*note Summary of Options: Options Summary.).. File: make.info, Node: Options Summary, Prev: Testing, Up: Running 9.7 Summary of Options ====================== Here' (*note Other Special Variables: Special Variables.) is set to a number greater than 0 this option is disabled when considering whether to remake makefiles (*note How Makefiles Are Remade: Remaking Makefiles.). ` (makefile)' By default, the above messages are not enabled while trying to remake the makefiles. This option enables messages while rebuilding makefiles, too. Note that the `all' option does enable this option. This option also enables `basic' messages. `: Parallel, for more information on how commands. . ` -qp'. To print the data base of predefined rules and variables, use `make -p -f /dev/null'. The data base output contains filename and linenumber information for command and variable definitions, so it can be a useful debugging tool in complex environments. `-q' `--question' "Question mode". Do not run any commands, or print anything; just return an exit status that is zero if the specified targets are already up to date, one if any remaking is required, or two if an error is encountered. .). You can still define your own, of course. The `-R' option also automatically enables the `-r' option (see above), since it doesn't make sense to have implicit rules without any definitions for the variables that they use. `-s' `--silent' `--quiet' Silent operation; do not print the commands as they are executed. Option. `'. 10 Using Implicit Rules ***********************. File: make.info, Node: Using Implicit, Next: Catalogue of Rules, Prev: Implicit Rules, Up: Implicit Rules 10.1 Using Implicit prerequisites (the source files). You would want to write a rule for . *Note Catalogue of Implicit Rules: Catalogue. *Note Chains of Implicit Rules: Chained Rules. In general, `make' searches for an implicit rule for each target, and for each double-colon rule, that has no commands. A file that is mentioned only as a prerequisite is considered a target whose rule specifies nothing, so implicit rule search happens for it. *Note Implicit Rule Search Algorithm: Implicit Rule Search, (*note Catalogue of Implicit Rules: Catalogue of Rules.). If you do not want an implicit rule to be used for a target that has no commands, you can give that target empty commands by writing a semicolon (*note Defining Empty Commands: Empty Commands.). File: make.info, Node: Catalogue of Rules, Next: Implicit Variables, Prev: Using Implicit, Up: Implicit Rules 10.2 Catalogue of Implicit Rules ================================ Here is a catalogue of predefined implicit rules which are always available unless the makefile explicitly overrides or cancels them. *Note Canceling Implicit Rules: Canceling Rules, for information on canceling or overriding an implicit rule. The `-r' or `- `make -p' in a directory with no makefile. Not all of these rules will always be defined, even when the `', `.r', `.y', `.l', `. *Note Old-Fashioned Suffix Rules: Suffix Rules, for full details on suffix rules. `$. Yacc for C programs `N.c' is made automatically from `N.y' by running Yacc with the command `$(YACC) $(YFLAGS)'. Lex for C programs `N.c' is made automatically from `N.l' by running Lex. The actual command is `$(LEX) $(LFLAGS)'. Lex for Ratfor programs `N.r' is made automatically from `N' will not be extracted from RCS if it already exists, even if the RCS file is newer. The rules for RCS are terminal (*note Match-Anything Pattern Rules: Match-Anything Rules.), so RCS files cannot be generated from another source; they must actually exist. SCCS Any file `N' is extracted if necessary from an SCCS file named either `s.N' or `SCCS/s.N'. The precise command used is `$(GET) $(GFLAGS)'. The rules for SCCS are terminal (*note Match-Anything Pattern Rules: Match-Anything' (*note Directory Search::). $@'. File: make.info, Node: Implicit Variables, Next: Chained Rules, Prev: Catalogue of Rules, Up: Implicit Rules 10.3 Variables Used by Implicit Rules ===================================== The commands `-R' or `--no-builtin-variables' option. `make' for your environment. To see the complete list of predefined variables for your instance of GNU `make' you can run `make -p' in a directory with no makefiles. Here is a table of some of the more common variables used as names of programs in built-in rules: makefiles. `AR' Archive-maintaining program; default `ar'. `AS' Program for compiling assembly files; default `as'. `CC' Program for compiling C programs; default `cc'. `CO' Program for checking out files from RCS; default `co'. source code; default `lex'. `YACC' Program to use to turn Yacc grammars into source code; default `yacc'. `LINT' Program to use to run lint on source code; default `lint'. `M2C' Program to use to compile Modula-2 source code; default `m2c'. `PC' Program for compiling Pascal programs; default `pc'. '. . File: make.info, Node: Chained Rules, Next: Pattern Rules, Prev: Implicit Variables, Up: Implicit Rules 10.4 Chains of Implicit Rules ============================= `rm `%.o') as a prerequisite of the special target `.PRECIOUS' to preserve intermediate files made by implicit rules whose target patterns match that file's name; see *Note search for an implicit rule chain.. | http://opensource.apple.com/source/gnumake/gnumake-126.2/make/doc/make.info-1 | CC-MAIN-2015-14 | refinedweb | 8,101 | 58.58 |
flutter_gherkin
A fully featured Gherkin parser and test runner. Works with Flutter and Dart 2.
This implementation of the Gherkin tries to follow as closely as possible other implementations of Gherkin and specifically Cucumber in it's various forms.
Available as a Dart package
# Comment Feature: Addition @tag Scenario: 1 + 0 Given I start with 1 When I add 0 Then I end up with 1 Scenario: 1 + 1 Given I start with 1 When I add 1 Then I end up with 2
Note - Package upgrades
This package will soon have a major release to support null-safety and then another major release to support running tests using the integration_test package and
WidgetTester. We will still maintain compatibility for running tests using flutter_driver and do our best so that switching over to using the integration_test package will be seamless. For this to happen we have had to refactor large chunks of the code base so unfortunately there will be some unavoidable breaking changes.
Table of Contents
- Getting Started
- Configuration
- Flutter specific configuration options
- Features Files
- Hooks
- Attachments
- Reporting
- Flutter
Getting Started
See docs.cucumber.io/gherkin/ for information on the Gherkin syntax and Behaviour Driven Development (BDD).
See example readme for a quick start guide to running the example features and app.
The first step is to create a version of your app that has flutter driver enabled so that it can be automated. A good guide how to do this is show here. However in short, create a folder called
test_driver and within that create a file called
app.dart and paste in the below code.
import '../lib/main.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_driver/driver_extension.dart'; void main() { // This line enables the extension enableFlutterDriverExtension(); // Call the `main()` function of your app or call `runApp` with any widget you // are interested in testing. runApp(MyApp()); }
All this code does is enable the Flutter driver extension which is required to be able to automate the app and then runs your application.
To get started with BDD in Flutter the first step is to write a feature file and a test scenario within that.
First create a folder called
test_driver (this is inline with the current integration test as we will need to use the Flutter driver to automate the app). Within the folder create a folder called
features , then create a file called
counter.feature .
Feature: Counter The counter should be incremented when the button is pressed. Scenario: Counter increases when the button is pressed Given I expect the "counter" to be "0" When I tap the "increment" button 10 times Then I expect the "counter" to be "10"
Now we have created a scenario we need to implement the steps within. Steps are just classes that extends from the base step definition class or any of its variations
Given ,
Then ,
When ,
And ,
But .
Granted the example is a little contrived but is serves to illustrate the process.
This library has a couple of built in step definitions for convenience. The first step uses the built in step, however the second step
When I tap the "increment" button 10 times is a custom step and has to be implemented. To implement a step we have to create a simple step definition class.
import 'package:flutter_driver/flutter_driver.dart'; import 'package:flutter_gherkin/flutter_gherkin.dart'; import 'package:gherkin/gherkin.dart'; StepDefinitionGeneric TapButtonNTimesStep() { return when2<String, int, FlutterWorld>( 'I tap the {string} button {int} times', (key, count, context) async { final locator = find.byValueKey(key); for (var i = 0; i < count; i += 1) { await FlutterDriverUtils.tap(context.world.driver, locator); } }, ); }
As you can see the
when2 method is invoked specifying two input parameters. The third type
FlutterWorld is a special world context object that allow access from the context object to the Flutter driver that allows you to interact with your app. If you did not need a custom world object or strongly typed parameters you can omit the type arguments completely.
The input parameters are retrieved via the pattern regex from well know parameter types
{string} and
{int} explained below. They are just special syntax to indicate you are expecting a string and an integer at those points in the step text. Therefore, when the step to execute is
When I tap the "increment" button 10 times the parameters "increment" and 10 will be passed into the step as the correct types. Note that in the pattern you can use any regex capture group to indicate any input parameter. For example the regex
RegExp(r"When I tap the {string} (button|icon) {int} times")
indicates 3 parameters and would match to either of the below step text.
When I tap the "increment" button 10 times // passes 3 parameters "increment", "button" & 10 When I tap the "plus" icon 2 times // passes 3 parameters "plus", "icon" & 2
It is worth noting that this library does not rely on mirrors (reflection) for many reasons but most prominently for ease of maintenance and to fall inline with the principles of Flutter not allowing reflection. All in all this make for a much easier to understand and maintain code base as well as much easier debugging for the user. The downside is that we have to be slightly more explicit by providing instances of custom code such as step definition, hook, reporters and custom parameters.
Now that we have a testable app, a feature file and a custom step definition we need to create a class that will call this library and actually run the tests. Create a file called
app_test.dart and put the below code in.') ] // you can include the "StdoutReporter()" without the message level parameter for verbose log information ..hooks = [HookExample()] ..stepDefinitions = [TapButtonNTimesStep(), GivenIPickAColour()] ..customStepParameterDefinitions = [ColourParameter()] ..restartAppBetweenScenarios = true ..targetAppPath = "test_driver/app.dart"; // ..tagExpression = "@smoke" // uncomment to see an example of running scenarios based on tag expressions return GherkinRunner().execute(config); }
This code simple creates a configuration object and calls this library which will then promptly parse your feature files and run the tests. The configuration file is important and explained in further detail below. However, all that is happening is a
RegExp is provide which specifies the path to one or more feature files, it sets the reporters to the
ProgressReporter report which prints the result of scenarios and steps to the standard output (console). The
TestRunSummaryReporter prints a summary of the run once all tests have been executed. Finally it specifies the path to the testable app created above
test_driver/app.dart . This is important as it instructions the library which app to run the tests against.
Finally to actually run the tests run the below on the command line:
dart test_driver/app_test.dart
To debug tests see Debugging.
Note: You might need to ensure dart is accessible by adding it to your path variable.
Configuration
The configuration is an important piece of the puzzle in this library as it specifies not only what to run but classes to run against in the form of steps, hooks and reporters. Unlike other implementation this library does not rely on reflection so need to be explicitly told classes to use.
The parameters below can be specified in your configuration file:
features
Required
An iterable of
Pattern that specify the location(s) of
*.feature files to run. See api.dart.dev/stable/2.12.4/dart-core/Pattern-class.html
tagExpression
Defaults to
null .
An infix boolean expression which defines the features and scenarios to run based of their tags. See Tags.
order
Defaults to
ExecutionOrder.random
The order by which scenarios will be run. Running an a random order may highlight any inter-test dependencies that should be fixed. Running with
ExecutionOrder.sorted processes the feature files in
filename order.
stepDefinitions
Defaults to
Iterable<StepDefinitionBase>
Place instances of any custom step definition classes
Given ,
Then ,
When ,
And ,
But that match to any custom steps defined in your feature files.
import 'dart:async'; import 'package:flutter_gherkin/flutter_gherkin.dart'; import 'package:gherkin()] ..restartAppBetweenScenarios = true ..targetAppPath = "test_driver/app.dart"; return GherkinRunner().execute(config); }
defaultLanguage
Defaults to
This specifies the default language the feature files are written in. See for supported languages.
Note that this can be overridden in the feature itself by the use of a language block.
# |
# language: fr Fonctionnalité: Counter The counter should be incremented when the button is pressed. @smoke Scénario: Counter increases when the button is pressed Etant donné que I pick the colour red Et I expect the "counter" to be "0" Quand I tap the "increment" button 10 times Alors I expect the "counter" to be "10"
customStepParameterDefinitions
Defaults to
CustomParameter<dynamic> .
Place instances of any custom step parameters that you have defined. These will be matched up to steps when scenarios are run and their result passed to the executable step. See Custom Parameters.
import 'dart:async'; import 'package:flutter_gherkin/flutter_gherkin.dart'; import 'package:gherkin/gherkin.dart'; import 'steps/given_I_pick_a_colour_step.dart'; import 'steps/tap_button_n_times_step.dart'; import 'steps/colour_parameter); }
hooks
Hooks are custom bits of code that can be run at certain points with the test run such as before or after a scenario. Place instances of any custom
Hook class instance in this collection. They will then be run at the defined points with the test run.
attachments
Attachment are pieces of data you can attach to a running scenario. This could be simple bits of textual data or even image like a screenshot. These attachments can then be used by reporters to provide more contextual information. For example when a step fails some contextual information could be attached to the scenario which is then used by a reporter to display why the step failed.
Attachments would typically be attached via a
Hook for example
onAfterStep .
import 'package:gherkin/gherkin.dart'; class AttachScreenshotOnFailedStepHook extends Hook { /// Run after a step has executed @override Future<void> onAfterStep(World world, String step, StepResult stepResult) async { if (stepResult.result == StepExecutionResult.fail) { world.attach('Some info.','text/plain'); world.attach('{"some", "JSON"}}', 'application/json'); } } }
screenshot
To take a screenshot on a step failing you can used the pre-defined hook
AttachScreenshotOnFailedStepHook and include it in the hook configuration of the tests config. This hook will take a screenshot and add it as an attachment to the scenario. If the
JsonReporter is being used the screenshot will be embedded in the report which can be used to generate a HTML report which will ultimately display the screenshot under the failed step.') ] ..hooks = [HookExample(), AttachScreenshotOnFailedStepHook()] ..stepDefinitions = [TapButtonNTimesStep(), GivenIPickAColour()] ..customStepParameterDefinitions = [ColourParameter()] ..restartAppBetweenScenarios = true ..targetAppPath = "test_driver/app.dart"; return GherkinRunner().execute(config); }
reporters
Reporters are classes that are able to report on the status of the test run. This could be a simple as merely logging scenario result to the console. There are a number of built-in reporter:
StdoutReporter: Logs all messages from the test run to the standard output (console).
ProgressReporter: Logs the progress of the test run marking each step with a scenario as either passed, skipped or failed.
JsonReporter- creates a JSON file with the results of the test run which can then be used by '.' to create a HTML report. You can pass in the file path of the json file to be created.
You should provide at least one reporter in the configuration otherwise it'll be hard to know what is going on.
Note: Feel free to PR new reporters!
import 'dart:async'; import 'package:flutter_gherkin/flutter_gherkin.dart'; import 'steps/colour_parameter); }
createWorld
Defaults to
null .
While it is not recommended so share state between steps within the same scenario we all in fact live in the real world and thus at time may need to share certain information such as login credentials etc for future steps to use. The world context object is created once per scenario and then destroyed at the end of each scenario. This configuration property allows you to specify a custom
World class to create which can then be accessed in your step classes.
import 'dart:async'; import 'package:flutter_gherkin/flutter()] ..createWorld = (TestConfiguration config) async => await createMyWorldInstance(config) ..restartAppBetweenScenarios = true ..targetAppPath = "test_driver/app.dart"; return GherkinRunner().execute(config); }
logFlutterProcessOutput
Defaults to
false
If
true the output from the flutter process is logged to the stdout / stderr streams. Useful when debugging app build or start failures
flutterBuildTimeout
Defaults to
90 seconds
Specifies the period of time to wait for the Flutter build to complete and the app to be installed and in a state to be tested. Slower machines may need longer than the default 90 seconds to complete this process.
onBeforeFlutterDriverConnect
An async method that is called before an attempt by Flutter driver to connect to the app under test
onAfterFlutterDriverConnect
An async method that is called after a successful attempt by Flutter driver to connect to the app under test
flutterDriverMaxConnectionAttempts
Defaults to
3
Specifies the number of Flutter driver connection attempts to a running app before the test is aborted
flutterDriverReconnectionDelay
Defaults to
2 seconds
Specifies the amount of time to wait after a failed Flutter driver connection attempt to the running app
Flutter specific configuration options
The
FlutterTestConfiguration will automatically create some default Flutter options such as well know step definitions, the Flutter world context object which provides access to a Flutter driver instance as well as the ability to restart you application under test between scenarios. Most of the time you should use this configuration object if you are testing Flutter applications.
restartAppBetweenScenarios
Defaults to
true .
To avoid tests starting on an app changed by a previous test it is suggested that the Flutter application under test be restarted between each scenario. While this will increase the execution time slightly it will limit tests failing because they run against an app changed by a previous test. Note in more complex application it may also be necessary to use the
AfterScenario hook to reset the application to a base state a test can run on. Logging out for example if restarting an application will present a lock screen etc. This now performs a hot reload of the application which resets the state and drastically reduces the time to run the tests.
targetAppPath
Defaults to
lib/test_driver/app.dart
This should point to the testable application that enables the Flutter driver extensions and thus is able to be automated. This application wil be started when the test run is started and restarted if the
restartAppBetweenScenarios configuration property is set to true.
build
Defaults to
true
This optional argument lets you specify if the target application should be built prior to running the first test. This defaults to
true
keepAppRunningAfterTests
Defaults to
false
This optional argument will keep the Flutter application running when done testing. This defaults to
false
buildFlavor
Defaults to empty string
This optional argument lets you specify which flutter flavor you want to test against. Flutter's flavor has similar concept with
Android Build Variants or
iOS Scheme Configuration . This flavoring flutter documentation has complete guide on both flutter and android/ios side.
buildMode
Defaults to
BuildMode.Debug
This optional argument lets you specify which build mode you prefer while compiling your app. Flutter Gherkin supports
--debug and
--profile modes. Check Flutter's build modes documentation for more details.
dartDefineArgs
Defaults to
[]
--dart-define args to pass into the build parameters. Include the name and value for each. For example,
--dart-define=MY_VAR="true" becomes
['MY_VAR="true"']
targetDeviceId
Defaults to empty string
This optional argument lets you specify device target id as
flutter run --device-id command. To show list of connected devices, run
flutter devices . If you only have one device connected, no need to provide this argument.
runningAppProtocolEndpointUri
An observatory url that the test runner can connect to instead of creating a new running instance of the target application
The url takes the form of and usually printed to stdout in the form
Connecting to service protocol:
You will have to add the
--verbose flag to the command to start your flutter app to see this output and ensure
enableFlutterDriverExtension() is called by the running app
Features Files
Steps Definitions
Step definitions are the coded representation of a textual step in a feature file. Each step starts with either
Given ,
Then ,
When ,
And or
But . It is worth noting that all steps are actually the same but semantically different. The keyword is not taken into account when matching a step. Therefore the two below steps are actually treated the same and will result in the same step definition being invoked.
Note: Step definitions (in this implementation) are allowed up to 5 input parameters. If you find yourself needing more than this you might want to consider making your step more isolated or using a
Table parameter.
Given there are 6 kangaroos Then there are 6 kangaroos
However, the domain language you choose will influence what keyword works best in each context. For more information docs.cucumber.io/gherkin/reference/#steps.
Given
Given steps are used to describe the initial state of a system. The execution of a
Given step will usually put the system into well defined state.
To implement a
Given step you can inherit from the
Given
class.
Given Bob has logged in
Would be implemented like so:
import 'package:gherkin/gherkin.dart'; StepDefinitionGeneric GivenWellKnownUserIsLoggedIn() { return given1( RegExp(r'(Bob|Mary|Emma|Jon) has logged in'), (wellKnownUsername, context) async { // implement your code }, ); }
If you need to have more than one Given in a block it is often best to use the additional keywords
And or
But .
Given Bob has logged in And opened the dashboard
Then
Then steps are used to describe an expected outcome, or result. They would typically have an assertion in which can pass or fail.
Then I expect 10 apples
Would be implemented like so:
import 'package:gherkin/gherkin.dart'; StepDefinitionGeneric ThenExpectAppleCount() { return then1( 'I expect {int} apple(s)', (count, context) async { // example code final actualCount = await _getActualCount(); context.expectMatch(actualCount, count); }, ); }
Expects Assertions
Caveat: The
expect library currently only works within the library's own
test function blocks; so using it with a
Then step will cause an error. Therefore, the
expectMatch or
expectA or
this.expect or
context.expect methods have been added which mimic the underlying functionality of
except in that they assert that the give is true. The
Matcher within Dart's test library still work and can be used as expected.
Step Timeout
By default a step will timeout if it exceed the
defaultTimeout parameter in the configuration file. In some cases you want have a step that is longer or shorter running and in the case you can optionally proved a custom timeout to that step. To do this pass in a
Duration object in the step's call to
super .
For example, the below sets the step's timeout to 10 seconds.
import 'package:flutter_driver/flutter_driver.dart'; import 'package:flutter_gherkin/flutter_gherkin.dart'; import 'package:gherkin/gherkin.dart'; StepDefinitionGeneric TapButtonNTimesStep() { return given2<String, int, FlutterWorld>( 'I tap the {string} button {int} times', (key, count, context) async { final locator = find.byValueKey(key); for (var i = 0; i < count; i += 1) { await FlutterDriverUtils.tap(context.world.driver, locator); } }, ); }
Multiline Strings
Multiline strings can follow a step and will be give to the step it proceeds as the final argument. To denote a multiline string the pre and postfix can either be third double or single quotes
""" ... """ or
''' ... ''' .
For example:
Given I provide the following "review" comment """ Some long review comment. That can span multiple lines Skip lines Maybe even include some numbers 1 2 3 """
The matching step definition would then be:
import 'package:gherkin/gherkin.dart'; StepDefinitionGeneric GivenTheMultiLineComment() { return given1( 'I provide the following {string} comment', (comment, context) async { // implement step }, ); }
Data tables
import 'package:gherkin/gherkin.dart'; /// This step expects a multiline string proceeding it /// /// For example: /// /// `When I add the users` /// | Firstname | Surname | Age | Gender | /// | Woody | Johnson | 28 | Male | /// | Edith | Summers | 23 | Female | /// | Megan | Hill | 83 | Female | StepDefinitionGeneric WhenIAddTheUsers() { return when1( 'I add the users', (Table dataTable, context) async { for (var row in dataTable.rows) { // do something with row row.columns.forEach((columnValue) => print(columnValue)); } // or get the table as a map (column values keyed by the header) final columns = dataTable.asMap(); final personOne = columns.elementAt(0); final personOneName = personOne["Firstname"]; print('Name of first user: `$personOneName` '); }, ); }
Well known step parameters
In addition to being able to define a step's own parameters (by using regex capturing groups) there are some well known parameter types you can include that will automatically match and convert the parameter into the correct type before passing it to you step definition. (see docs.cucumber.io/cucumber/cucumber-expressions/#parameter-types).
In most scenarios theses parameters will be enough for you to write quite advanced step definitions.
Note that you can combine there well known parameters in any step. For example
Given I {word} {int} worm(s) would match
Given I "see" 6 worms and also match
Given I "eat" 1 worm
Pluralization
As the aim of a feature is to convey human readable tests it is often desirable to optionally have some word pluralized so you can use the special pluralization syntax to do simple pluralization of some words in your step definition. For example:
The step string
Given I see {int} worm(s) has the pluralization syntax on the word "worm" and thus would be matched to both
Given I see 1 worm and
Given I see 4 worms .
Custom Parameters
While the well know step parameter will be sufficient in most cases there are time when you would want to defined a custom parameter that might be used across more than or step definition or convert into a custom type.
The below custom parameter defines a regex that matches the words "red", "green" or "blue". The matches word is passed into the function which is then able to convert the string into a Color object. The name of the custom parameter is used to identity the parameter within the step text. In the below example the word "colour" is used. This is combined with the pre / post prefixes (which default to "{" and "}") to match to the custom parameter.
import 'package:gherkin/gherkin.dart'; enum Colour { red, green, blue } class ColourParameter extends CustomParameter<Colour> { ColourParameter() : super("colour", RegExp(r"(red|green|blue)", caseSensitive: true), (c) { switch (c.toLowerCase()) { case "red": return Colour.red; case "green": return Colour.green; case "blue": return Colour.blue; } }); }
The step definition would then use this custom parameter like so:
import 'package:gherkin/gherkin.dart'; import 'colour_parameter.dart'; StepDefinitionGeneric GivenIAddTheUsers() { return given1<Colour>( 'I pick the colour {colour}', (colour, _) async { print("The picked colour was: '$colour'"); }, ); }
This customer parameter would be used like this:
Given I pick the colour red . When the step is invoked the word "red" would matched and passed to the custom parameter to convert it into a
Colour enum which is then finally passed to the step definition code as a
Colour object.
World Context (per test scenario shared state)
Assertions
Tags are a great way of organizing your features and marking them with filterable information. Tags can be uses to filter the scenarios that are run. For instance you might have a set of smoke tests to run on every check-in as the full test suite is only ran once a day. You could also use an
@ignore or
@todo tag to ignore certain scenarios that might not be ready to run yet.
You can filter the scenarios by providing a tag expression to your configuration file. Tag expression are simple infix expressions such as:
@smoke
@smoke and @perf
@billing or @onboarding
@smoke and not @ignore
You can even us brackets to ensure the order of precedence
@smoke and not (@ignore or @todo)
You can use the usual boolean statement "and", "or", "not"
Also see docs.cucumber.io/cucumber/api/#tags
Languages
In order to allow features to be written in a number of languages, you can now write the keywords in languages other than English. To improve readability and flow, some languages may have more than one translation for any given keyword. See for a list of supported languages.
You can set the default language of feature files in your project via the configuration setting see defaultLanguage
For example these two features are the same the keywords are just written in different languages. Note the
# language: de
on the second feature. English is the default language.
Feature: Calculator Tests the addition of two numbers Scenario Outline: Add two numbers Given the numbers <number_one> and <number_two> When they are added Then the expected result is <result> Examples: | number_one | number_two | result | | 12 | 5 | 17 | | 20 | 5 | 25 | | 20937 | 1 | 20938 | | 20.937 | -1.937 | 19 |
# |
Please note the language data is take and attributed to the cucumber project
Hooks
A hook is a point in the execution that custom code can be run. Hooks can be run at the below points in the test run.
- Before any tests run
- After all the tests have run
- Before each scenario
- After each scenario
To create a hook is easy. Just inherit from
Hook and override the method(s) that signifies the point in the process you want to run code at. Note that not all methods need to be override, just the points at which you want to run custom code.
import 'package:gherkin/gherkin.dart'; class HookExample extends Hook { /// The priority to assign to this hook. /// Higher priority gets run first so a priority of 10 is run before a priority of 2 @override int get priority => 1; /// Run before any scenario in a test run have executed @override Future<void> onBeforeRun(TestConfiguration config) async { print("before run hook"); } /// Run after all scenarios in a test run have completed @override Future<void> onAfterRun(TestConfiguration config) async { print("after run hook"); } /// Run before a scenario and it steps are executed @override Future<void> onBeforeScenario( TestConfiguration config, String scenario) async { print("running hook before scenario '$scenario'"); } /// Run after a scenario has executed @override Future<void> onAfterScenario( TestConfiguration config, String scenario) async { print("running hook after scenario '$scenario'"); } }
Finally ensure the hook is added to the hook collection in your configuration file.
import 'dart:async'; import 'package:flutter_gherkin/flutter_gherkin.dart'; import 'package:gherkin/gherkin.dart'; import 'hooks/hook_example.dart'; import 'steps/given_I_pick_a_colour_step.dart'; import 'steps/tap_button_n_times_step.dart'; Future<void> main() { final config = FlutterTestConfiguration() ..features = [RegExp('features/*.*.feature')] ..reporters = [ProgressReporter()] ..hooks = [HookExample()] ..stepDefinitions = [TapButtonNTimesStep(), GivenIPickAColour()] ..restartAppBetweenScenarios = true ..targetAppPath = "test_driver/app.dart"; return GherkinRunner().execute(config); }
Reporting
A reporter is a class that is able to report on the progress of the test run. In it simplest form it could just print messages to the console or be used to tell a build server such as TeamCity of the progress of the test run. The library has a number of built in reporters.
StdoutReporter- prints all messages from the test run to the console.
ProgressReporter- prints the result of each scenario and step to the console - colours the output.
TestRunSummaryReporter- prints the results and duration of the test run once the run has completed - colours the output.
JsonReporter- creates a JSON file with the results of the test run which can then be used by '.' to create a HTML report. You can pass in the file path of the json file to be created.
FlutterDriverReporter- prints the output from Flutter Driver. Flutter driver logs all messages to the stderr stream by default so most CI servers would mark the process as failed if anything is logged to the stderr stream (even if the Flutter driver logs are only info messages). This reporter ensures the log messages are output to the most appropriate stream depending on their log level.
You can create your own custom reporter by inheriting from the base
Reporter class and overriding the one or many of the methods to direct the output message. The
Reporter defines the following methods that can be overridden. All methods must return a
Future<void> and can be async.
onTestRunStarted
onTestRunFinished
onFeatureStarted
onFeatureFinished
onScenarioStarted
onScenarioFinished
onStepStarted
onStepFinished
onException
disposeOnce you have created your custom reporter don't forget to add it to the
reportersconfiguration file property.
Note: PR's of new reporters are always welcome.
Flutter
Restarting the app before each test
By default to ensure your app is in a consistent state at the start of each test the app is shut-down and restarted. This behaviour can be turned off by setting the
restartAppBetweenScenarios flag in your configuration object. Although in more complex scenarios you might want to handle the app reset behaviour yourself; possibly via hooks.
You might additionally want to do some clean-up of your app after each test by implementing an
onAfterScenario hook.
Flutter World
Pre-defined Steps
For convenience the library defines a number of pre-defined steps so you can get going much quicker without having to implement lots of step classes. The pre-defined steps are:
Flutter Driver Utilities
For convenience the library provides a static
FlutterDriverUtils class that abstracts away some common Flutter driver functionality like tapping a button, getting and entering text, checking if an element is present or absent, waiting for a condition to become true. See lib/src/flutter/utils/driver_utils.dart.
Debugging
In VSCode simply add add this block to your launch.json file (if you testable app is called
app_test.dart and within the
test_driver folder, if not replace that with the correct file path). Don't forget to put a break point somewhere!
{ "name": "Debug Features Tests", "request": "launch", "type": "dart", "program": "test_driver/app_test.dart", "flutterMode": "debug" }
After which the file will most likely look like this
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: "version": "0.2.0", "configurations": [ { "name": "Flutter", "request": "launch", "type": "dart" }, { "name": "Debug Features Tests", "request": "launch", "type": "dart", "program": "test_driver/app_test.dart", "flutterMode": "debug" } ] }
Debugging the app under test
Setting the configuration property
runningAppProtocolEndpointUri to the service protocol endpoint (found in stdout when an app has
--verbose logging turned on) will ensure that the existing app is connected to rather than starting a new instance of the app.
NOTE: ensure the app you are trying to connect to calls
enableFlutterDriverExtension() when it starts up otherwise the Flutter Driver will not be able to connect to it.
Also ensure that the
--verbose flag is set when starting the app to test, this will then log the service protocol endpoint out to the console which is the uri you will need to set this property to. It usually takes the form of
Connecting to service protocol: so set the
runningAppProtocolEndpointUri to and then start the tests.
Interactive debugging
One way to configure your test environment is to run the app under test in a separate terminal and run the gherkin in a different terminal. With this approach you can hot reload the app by entering
R in the app terminal and run the steps repeatedly in the other terminal with out incurring the cost of the app start up.
For the app under test, in this case
lib/main_test.dart, it should look similar to this:
import 'package:flutter/material.dart'; import 'package:flutter_driver/driver_extension.dart'; void main() { enableFlutterDriverExtension(); runApp();
When you start this from the terminal, run like this:
flutter run -t lib/main_test.dart --verbose
As stated above, with the
--verbose flag, you will want to find the service protocol endpoint.
You should see similar output as this:
..... Connecting to service protocol: ..... Flutter run key commands. [ +2 ms] r Hot reload. 🔥🔥🔥 [ +1 ms] R Hot restart. [ ] h Repeat this help message. [ ] d Detach (terminate "flutter run" but leave application running). [ ] c Clear the screen [ ] q Quit (terminate the application on the device). [ ] An Observatory debugger and profiler on iPhone 8 Plus is available at: [ ] Running with unsound null safety [ ] For more information see
To run the gherkin tests, first update the
test_driver/app_test.dart to something similar to this:
import 'dart:async'; import 'dart:io'; import 'package:flutter_gherkin/flutter_gherkin.dart'; import 'package:gherkin/gherkin.dart'; Future<void> main(List<String> args) async { if (args.isEmpty) { print('please pass in the uri'); exit(1); } final Iterable<StepDefinitionGeneric<World>> steps = []; final config = FlutterTestConfiguration.DEFAULT( steps, featurePath: 'features//**.feature', targetAppPath: 'test_driver/app.dart', ) ..restartAppBetweenScenarios = false ..targetAppWorkingDirectory = '../' ..runningAppProtocolEndpointUri = args[0]; return GherkinRunner().execute(config); }
Start a new terminal and navigate to the
test_driver directory.
Notice the
app_test.dart expects a parameter. This is to ease the changing uri which will occur each time the app under test is started. If you use the
R command, the
uri does not change.
You can copy the
uri from the terminal window of the app under test.
Run the command
dart app_test.dart <uri>. As an example, the app under test has this line:
Connecting to service protocol:
so you would copy and paste it as such:
dart app_test.dart.
As you make changes in the app under test, just
R (reload). In the test window you can rerun the tests and update the Scenarios quickly and easily. | https://pub.dev/documentation/flutter_gherkin/latest/ | CC-MAIN-2021-21 | refinedweb | 5,494 | 53.92 |
In include/linux/shm.h we find:
/* shm_mode upper byte flags */
#define SHM_DEST 01000 /* segment will be destroyed on last detach
*/
#define SHM_LOCKED 02000 /* segment will not be swapped */
#define SHM_HUGETLB 04000 /* segment will use huge TLB pages */
#ifdef CONFIG_SSI
#define SHM_LOCK_DEST 10000 /* obj locked for destroy */
#endif /* CONFIG_SSI */
The definition of SHM_LOCK_DEST is obviously wrong.
Hello everybody from Abidjan, Cote d'Ivoire. (Message sent via EDGE
connection on mobile phone).
------------------------------------------------------------------------------
Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day
trial. Simplify your report design, integration and deployment - and focus
on
what you do best, core application coding. Discover what's new with
Crystal Reports now. | http://article.gmane.org/gmane.linux.cluster.ssic.devel/6037 | CC-MAIN-2018-13 | refinedweb | 109 | 54.02 |
If
When run under 2.4, I want this result
$ ~/bin/python2.4 tern.py must use python 2.5 or greater
and not this result:
$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax
(Channeling for a coworker.)
You can test using
eval:
try: eval("1 if True else 2") except SyntaxError: # doesn't have ternary
Also,
with is available in Python 2.5, just add
from __future__ import with_statement.
EDIT: to get control early enough, you could split it into different
.py files and check compatibility in the main file before importing (e.g. in
__init__.py in a package):
# __init__.py # Check compatibility try: eval("1 if True else 2") except SyntaxError: raise ImportError("requires ternary support") # import from another module from impl import *
Have a wrapper around your program that does the following.
import sys req_version = (2,5) cur_version = sys.version_info if cur_version >= req_version: import myApp myApp.run() else: print "Your Python interpreter is too old. Please consider upgrading."
You can also consider using
sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.
And there might be more elegant ways to do this.
Try
import platform platform.python_version()
Should give you a string like “2.3.1”. If this is not exactly waht you want there is a rich set of data available through the “platform” build-in. What you want should be in there somewhere.
Probably the best way to do do this version comparison is to use the
sys.hexversion. This is important because comparing version tuples will not give you the desired result in all python versions.
import sys if sys.hexversion < 0x02060000: print "yep!" else: print "oops!"
import sys # prints whether python is version 3 or not python_version = sys.version_info.major if python_version == 3: print("is python 3") else: print("not python 3")
Answer from Nykakin at AskUbuntu:
You can also check Python version from code itself using
platform module from standard library.
There are two functions:
platform.python_version()(returns string).
platform.python_version_tuple()(returns tuple).
The Python code
Create a file for example:
version.py)
Easy method to check version:
import platform print(platform.python_version()) print(platform.python_version_tuple())
You can also use the
eval method:
try: eval("1 if True else 2") except SyntaxError: raise ImportError("requires ternary support")
Run the Python file in a command line:
$ python version.py 2.7.11 ('2', '7', '11')
The output of Python with CGI via a WAMP Server on Windows 10:
Helpful resources
Although the question is:
How do I get control early enough to issue an error message and exit?
The question that I answer is:
How do I get control early enough to issue an error message before starting the app?
I can answer it a lot differently then the other posts.
Seems answers so far are trying to solve your question from within Python.
I say, do version checking before launching Python. I see your path is Linux or unix.
However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn’t be too hard.
Here is the DOS script with version 2.7:
@ECHO OFF REM see FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul IF NOT ErrorLevel 1 GOTO Python27 ECHO must use python2.7 or greater GOTO EOF :Python27 python.exe tern.py GOTO EOF :EOF
This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn’t end your app to an exception due to different version syntax rules. That’s three less possible security points of access.
The “FOR /F” line is the key.
FOR /F “tokens=1,2” %%G IN (‘”python.exe -V 2>&1″‘) DO ECHO %%H | find “2.7” > Nul
For multiple python version check check out url:
And my hack version:[MS script; Python version check prelaunch of Python module]
Sets became part of the core language in Python 2.4, in order to stay backwards compatible. I did this back then, which will work for you as well:
if sys.version_info < (2, 4): from sets import Set as set
As noted above, syntax errors occur at compile time, not at run time. While Python is an “interpreted language”, Python code is not actually directly interpreted; it’s compiled to byte code, which is then interpreted. There is a compile step that happens when a module is imported (if there is no already-compiled version available in the form of a .pyc or .pyd file) and that’s when you’re getting your error, not (quite exactly) when your code is running.
You can put off the compile step and make it happen at run time for a single line of code, if you want to, by using eval, as noted above, but I personally prefer to avoid doing that, because it causes Python to perform potentially unnecessary run-time compilation, for one thing, and for another, it creates what to me feels like code clutter. (If you want, you can generate code that generates code that generates code – and have an absolutely fabulous time modifying and debugging that in 6 months from now.) So what I would recommend instead is something more like this:
import sys if sys.hexversion < 0x02060000: from my_module_2_5 import thisFunc, thatFunc, theOtherFunc else: from my_module import thisFunc, thatFunc, theOtherFunc
.. which I would do even if I only had one function that used newer syntax and it was very short. (In fact I would take every reasonable measure to minimize the number and size of such functions. I might even write a function like ifTrueAElseB(cond, a, b) with that single line of syntax in it.)
Another thing that might be worth pointing out (that I’m a little amazed no one has pointed out yet) is that while earlier versions of Python did not support code like
value = 'yes' if MyVarIsTrue else 'no'
..it did support code like
value = MyVarIsTrue and 'yes' or 'no'
That was the old way of writing ternary expressions. I don’t have Python 3 installed yet, but as far as I know, that “old” way still works to this day, so you can decide for yourself whether or not it’s worth it to conditionally use the new syntax, if you need to support the use of older versions of Python.
Put the following at the very top of your file:
import sys if float(sys.version.split()[0][:3]) < 2.7: print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting." exit(1)
Then continue on with the normal Python code:
import ... import ... other code...
import sys sys.version
will be getting answer like this
‘2.7.6 (default, Oct 26 2016, 20:30:19) \n[GCC 4.8.4]’
here 2.7.6 is version
I think the best way is to test for functionality rather than versions. In some cases, this is trivial, not so in others.
eg:
try : # Do stuff except : # Features weren't found. # Do stuff for older versions.
As long as you’re specific in enough in using the try/except blocks, you can cover most of your bases.
I just found this question after a quick search whilst trying to solve the problem myself and I’ve come up with a hybrid based on a few of the suggestions above.
I like DevPlayer’s idea of using a wrapper script, but the downside is that you end up maintaining multiple wrappers for different OSes, so I decided to write the wrapper in python, but use the same basic “grab the version by running the exe” logic and came up with this.
I think it should work for 2.5 and onwards. I’ve tested it on 2.66, 2.7.0 and 3.1.2 on Linux and 2.6.1 on OS X so far.
import sys, subprocess args = [sys.executable,"--version"] output, error = subprocess.Popen(args ,stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate() print("The version is: '%s'" %error.decode(sys.stdout.encoding).strip("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ,.+ \n") )
Yes, I know the final decode/strip line is horrible, but I just wanted to quickly grab the version number. I’m going to refine that.
This works well enough for me for now, but if anyone can improve it (or tell me why it’s a terrible idea) that’d be cool too.
You can check with
sys.hexversion or
sys.version_info.
sys.hexversion isn’t very human-friendly because it’s a hexadecimal number.
sys.version_info is a tuple, so it’s more human-friendly.
Check for Python 3.6 or newer with
sys.hexversion:
import sys, time if sys.hexversion < 0x30600F0: print("You need Python 3.6 or greater.") for _ in range(1, 5): time.sleep(1) exit()
Check for Python 3.6 or newer with
sys.version_info:
import sys, time if sys.version_info[0] < 3 and sys.version_info[1] < 6: print("You need Python 3.6 or greater.") for _ in range(1, 5): time.sleep(1) exit()
sys.version_info is more human-friendly, but takes more characters. I would reccomend
sys.hexversion, even though it is less human-friendly.
I hope this helped you!
How about this:
import sys def testPyVer(reqver): if float(sys.version[:3]) >= reqver: return 1 else: return 0 #blah blah blah, more code if testPyVer(3.0) == 1: #do stuff else: #print python requirement, exit statement
The problem is quite simple. You checked if the version was less than 2.4, not less than or equal to. So if the Python version is 2.4, it’s not less than 2.4.
What you should have had was:
if sys.version_info **<=** (2, 4):
, not
if sys.version_info < (2, 4): | https://exceptionshub.com/how-can-i-check-for-python-version-in-a-program-that-uses-new-language-features.html | CC-MAIN-2018-22 | refinedweb | 1,676 | 77.03 |
Did you know this was valid C++
#include <iostream>
using std::cout;
using std::endl;
int main ()
{
bool b = false;
cout << b << endl;
b++;
cout << b << endl;
b++;
cout << b << endl;
return 0;
}
You can call increment on false to get true, and increment on true to get ... true.And if you replace ++ with -- , that's not valid C++.
I only found this out just today; it's been slated to be deprecated in C++17 (link) Enjoy while you can!
WHAT? I thought for sure (bool)++ was negate. This is like Javascript-level stupidity.
Is that compiler dependent?
[edit] Also, side note: Lots of people I know are surprised that you can multiply strings in some (read: good) languages. It just means repeat. Which is insanely useful when you need to do something like:
print "text header\n" + "-"*80 + "\n"
As well as other formatting I can't recall off the top my head. I love learning about stuff like that where you go "Where has this been all my life?"
-----sig:“Programs should be written for people to read, and only incidentally for machines to execute.” - Structure and Interpretation of Computer Programs"Political Correctness is fascism disguised as manners" --George Carlin
Is b++ just the same as b = true? Anyone tested it or looked at the assembly?
By the way, negation would be b ^= 1. Unless C++ disallows it, of course
---Smokin' Guns - spaghetti western FPS action
a = 0
b = 1
a++ = 0 //nope
b++ = 1 //nope
++a = 1 //nope
++b = 1 //nope
!a = 1 //yes
!b = 0 //yes
a^1 = 1 //yes
b^1 = 0 //yes
1 - (bool)a*-1 = 1 //yes
1 - (bool)b*-1 = 0 //yes... lols
With the postfix operators you have to increment and print them in two different statements, otherwise you get the original value
But it looks like bools are limited to be either 0 or 1. I guess b + 1 would be 1?
By the way, what compiler version did you use?
What possible reason would you have to increment a bool anyway? Either set it to true or false, anything else is madness. Using ischar() as a number base makes about as much sense.
They all watch too much MSNBC... they get ideas.
Well, looking at it from C it makes sense - there bool is the same as int and anything except zero means true. So if x is 1 and you do x++ it gets 2, which is still true.
It is stupid that they allowed ++ for bool in C++, but so are 1000 other things in C++, so I don't see anything special here
--"Either help out or stop whining" - Evert
I forgot to mention I'm running GCC. I don't recall the version, it's in the newer (maybe experimental?) branch which is necessary for proper c++14 (or whatever) support. I don't recall which, it's been a long time since I had to install it.
Well, looking at it from C it makes sense
Why not x-- then?
As it is, you can flip false to true, or true to true, but not true to false. I would think the operators should be symmetrical, or not at all.
--Streaming KrampusHack 2020 LIVE on Twitch - (status: ⭕️ OFFLINE) -)AllegroFlare • allegro.cc markdown • Allegro logo
So if x is 1 and you do x++ it gets 2, which is still true.
But why would you do that with a bool, as opposed to some sort of stack pointer or ring buffer? Not to mention the wraparound, which is admittedly huge.
By the way, what compiler version did you use?
I used MSVC, clang and gcc (not sure of the latest versions but all recent)
I suppose if you view bool as a one-bit arithmetic type then incrementing true is an overflow and that results in undefined behaviour - so the value could be anything.
And I suppose if you incremented something N times and decremented it N times you might expect to be back where you started, which can't be guaranteed for bool so they disabled '--'.
Maybe there was some reason for it back when they wrote the spec and maybe it just slipped through the net?
[edit] The fact that it's post increment gives it one possible use, though it's not hard to find alternatives:
void printlist(int n) {
bool comma = false;
for (int i = 0; i < n; ++i) {
if (comma++) {
cout << ',';
}
cout << i;
}
}
The original example was here using C++ ranged for statement which makes a bit more sense.
I really don't understand why they added a separate function for just that use case, though...
I'm of the opinion that if a sensible meaning can be defined for an operator then it should be. I like being able to make code terse and operators are the best way to achieve that from the language or a global library. I don't see this as a problem at all, as long as the results are defined. If anything, it's a WTF to me that you cannot decrement. It's no surprise to most of us that a boolean type is typically represented by a 0/^0/!0 byte or bit. And we all understand what the result would be of incrementing those. It may not entirely make sense logically, but at the same time a useful meaning can be applied to and derived suppose if you view bool as a one-bit arithmetic type then incrementing true is an overflow and that results in undefined behaviour - so the value could be anything.
But we have tons of defined overflow scenarios. Unsigned overflows, signed overflows, float overflows. It seems strange they would just leave that one alone.
My opinion--and it's about as valuable as that--is that the more things that "don't immediately make sense" the more a programmer has to keep in his mind at all times while programming. And the more balls a programmer has to juggle at once, the more likely you hit create an error.
I'm sure there's some brain function / sign-of-intelligence that corresponds to how many ideas a person can have in their brain at one time. And the more taken up by the programming language, the less available for comprehending the task at hand. Which is why many people solve complex problems outside of code... by solving the problem separated from implementing that problem, you free up some "slots" in your brain to help take a "too big to fit" problem and hopefully fit it.
[edit] The fact that it's post increment gives it one possible use, though it's not hard to find alternatives:
Actually, have you tested for an error in that code? What happens if you increment a bool 65536 times? Does it eventually wrap a 8/16/32/64-bit integer around to zero?
I compiled this as C++ in VS 2015, no optimizations:
void incbool(bool b)
{
b++;
}
And got this:
?incbool@@YAX_N@Z (void __cdecl incbool(bool)):
00000000: 55 push ebp
00000001: 8B EC mov ebp,esp
00000003: 51 push ecx
00000004: 8A 45 08 mov al,byte ptr [ebp+8]
00000007: 88 45 FF mov byte ptr [ebp-1],al
0000000A: C6 45 08 01 mov byte ptr [ebp+8],1
0000000E: 8B E5 mov esp,ebp
00000010: 5D pop ebp
00000011: C3 ret
It's just copied, and then set to true.
All 4 of gcc, clang, g++, clang++ produce the same asm output for C/C++ code (simply moving the value 1 into the variable). So actually C's ++ operator behaves the same on a bool as C++'s.
Yeah, I get get same result in VS 2015. Only the name mangling of the function changes, the assembly is otherwise identical. I guess VS finally supports C99 bool, then.
Well, looking at it from C it makes sense - there bool is the same as int and anything except zero means true. So if x is 1 and you do x++ it gets 2, which is still true.
And this, boys and girls, is why you should never use bitwise operators when you should use logical operators.
Case in point:
Here, if bools are treated like ints, the two if()s will behave differently. However, you could create a StrictBool class that behaves like a bool should. All operators will be overloaded with versions that use C++'s 'explicit' keyword with StrictBool-paramaters to prevent implicit casting, and there will be non-explicit versions of the operators that for each paramater, regardless of it's type, do something like value = (paramater?true:false) . In this case, both if()'s in the above code will be equivalent if the functions return StrictBools.
--Don't let the illegitimates turn you into carbon.
Yeah
{"name":"636x460design_01.jpg","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/4\/8\/48bed991ae72aac26032315a4ba6c62b.jpg","w":636,"h":460,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/4\/8\/48bed991ae72aac26032315a4ba6c62b"}
I ran some rudimentary (uncomprehensive) tests for performance between either several bool types or bitwise on an int.
Bitwise was a bit slower.
...
No, but actually it was a bit slower. Only by about ~7% or something, though.
Isn't it the case that the compiler ensures that bools always have a 0 or a 1 stored in their memory location?
I think Visual Studio warns if an int is implicitly cast to bool, and the wording of the warning suggests that there will be a performance hit from the operation of constraining its value.
--Bruce "entheh" Perry [ Web site | DUMB | Set Up Us The Bomb !!! | Balls ]Programming should be fun. That's why I hate C and C++.The brxybrytl has you.
Since ++ just copies it and sets it to true, then there's no reason not to include -- to copy and set to false.
Note: my actual position is that the operators should not be used at all on bool.
All of that's probably true
Since ++ just copies it and sets it to true, then there's no reason not to include -- to copy and set to false.
It doesn't even need to copy, just set.
It has to copy, that's the whole point of postincrement.
Fuck Matthew Leverton, just fuck him. | https://www.allegro.cc/forums/thread/615840 | CC-MAIN-2021-39 | refinedweb | 1,718 | 71.24 |
Here at SBO we love our food trucks. Even in the dead of winter we can be found waiting in line for our chicken and rice while enduring wind chills of 20°F and below. When we are not outside freezing our butts off, we can be found at our desks communicating with each other through HipChat, our preferred team chat software. On most days, the question of which Boston Food Truck awaits us comes up. I decided it would be fun to find a way to get HipChat to tell us each day what we want to know before we even ask.
HipChat automation basics
HipChat has a nice API available. To take advantage of it, you will need a group admin account on HipChat. The first step is to create an API Auth Token —a fairly simple process that is explained on the site. For our purposes, it will need to be of type ‘Notification.’ Its label can be what ever you like; I chose FTotD: Food Truck of the Day. (It will be useful to make an admin token as well for testing this next part, but in the end, we want the notification token.)
Now we need to test out the authentication by getting the HipChat API to give us a list of the rooms. HipChat kindly supplies some sample code for us in many languages. We write lots of Python code at SBO, so I chose to write my script in Python. Here is the code that will get us started:
import urllib2 url = "" request = urllib2.Request(url) response = urllib2.urlopen(request) print response.read()
If you put your admin token in the code where indicated, you should get back a list of the rooms as well as the id values for each room. (It would be useful at this point to create a room to test your code. Once you have that ready, re-run this script and take note of the room you just made.)
We want to be able to send messages to HipChat, so we will first need to change the method from rooms/list to room/message in the URL above. The rooms/message method has a few required parameters that we will need to pass along such as room_id, from, and message. There are two others that I chose to change form their default values: notify and color. Add or change the following lines in the script, add your own specific values for the all-caps text, and give it a shot:
room = "YOUR ROOM NUMBER" token = "YOUR AUTH TOKEN" sender = "BostonFoodTruck" color = "purple" notify = "1" message = "Test Message" url = ""+room+"&auth_token="+token+"&from="+sender+"&message="+message+"&color="+color+"&notify="+notify
If all went well, you should have gotten a response that said “sent” and a message in your newly created room.
What’s for lunch?
Now that we have mastered sending a message to a room in HipChat, we need to make it interesting. The City of Boston provides a nice online app to help you figure out which food truck will be stopping by your neighborhood on which days. Check it out! This is great for a human user, but getting a script to extract the info we need from here will not be easy. The good news is that they have a mobile version of this page here that’s marked up as a simple table. I chose to use the Python urllib and urlopen methods to grab all the info off this page:
import urllib url_file = urllib.urlopen("") file_lines = url_file.readlines()
I added that last line to break the file up into an array of lines so that later I can search through them and reference them with simple indexing. If you look at the markup code for the table on the city of Boston webpage, you will see that each line in the table looks something like this:
Ultimately we want to get the URL out of the second line above, but we need to make sure it comes form the right part of the table. The last three lines help make that easy. All we need to do is search for a set of lines that contain my location, (25) Innovation District, Seaport Blvd at Thompson, the meal of interest (lunch), and the day of the week. But before we can do the search, we need to determine which day of the week it is. Luckily, Python will just handle this for us:
import datetime now = datetime.datetime.now() dotw = now.strftime("%A") # For example, "Thursday" meal = "Lunch" location = "(25) Innovation District, Seaport Blvd at Thompson"
Putting that right after the file_lines declaration should set us up well to extract the information we seek. The trick here is to reference the right lines as we loop though all the file lines and cut out the html code so that we are only left with the URL to the web page of the food truck we want.
i = 0 for line in file_lines: if location in line and meal in file_lines[i-1] and dotw in file_lines[i-2]: truck_url = file_lines[i-3].rsplit('href="',1)[1].rsplit('">',1)[0] i += 1
[Ed. For a more complicated HTML parsing problem we definitely recommend using a real XML/HTML parser like our perennial favorite lxml, but the sooner Matt could write this bot, the sooner we could get lunch. – Liza]
At this point we have the URL for the truck and we only need to add a line for the message as such:
message = truck_url
If you run your script now you should get a message in your room that tells you the URL for today’s truck at your location. But that is pretty boring, especially since HipChat expects an HTML-encoded message by default. We can send out a message that looks good and will do something if you click on it. For this I choose to use the main logo from each of the food truck’s websites that stop by our office and their menu page if they had one. Since all the webpages are written differently, there was no elegant way to code this, I simply had to copy the URLs for every page and put them directly into my code. The last block of code looks like this:
if truck_url == "": message = "<a href=''> <img height='100' src=''/></a>" elif truck_url == "": message = "<a href=''> <img height='100' src=''/></a>" elif truck_url == "": message = "<a href=''> <img height='100' src=''/></a>" elif truck_url == "": message = "<a href=''> <img height='100' src=''/></a>" elif truck_url == "": message = "<a href=''> <img height='100' src=''/></a>" else: message = truck_url
While the food trucks that show up here do not typically change from week to week, I added the last condition just in case. If I see a plain URL pop up one day I will have to add a new condition to make up for the new truck. One final line is needed to make the message safe for passing through a URL:
message = urllib.quote(message)
At this point you should be able to run this and see a message pop up in your test room with what ever info you put in your message. At this point, the Python script is complete, you will just need to edit it to put have the right notification token and room ID.
The next trick will be to get the script to run at a certain time each day and on the days that are important to you. For that we will use cron. I want my script to run Monday through Friday at noon. Log in to your favorite unix machine that is on all the time. Run the command ‘crontab -e’. If it is your first time, it will ask you which editor you use, choose your favorite. Read the info it gives you and at the end add a line like this:
00 12 * * 1-5 /path/to/your/script.py
the way that will read to cron is, run this command “/path/to/your/script.py” any month of the year, any day of the month, Monday – Friday, at the 12th hour, on the 00 minute. You will need to add:
#!/usr/bin/env python
as the first line in your Python script and make the file executable. Last thing to do is wait and enjoy the results.
Well, there you have it, a Python script that will look up food truck info and post it to HipChat five days a week. | https://www.safaribooksonline.com/blog/2013/02/08/food-truck-culture-meets-hipchat-culture/ | CC-MAIN-2017-13 | refinedweb | 1,433 | 76.25 |
javax.servlet.SingleThreadModel is a marker interface available to servlet developers that pushes responsibility for thread safety onto the servlet engine. Essentially, if your servlet implements SingleThreadModel, the servlet engine creates a separate servlet instance for each concurrent request using the servlet. SingleThreadModel does not even guarantee thread safety, since the resulting servlet instances can still access classes and data at the same time. However, SingleThreadModel does guarantee that more resources will be used than are needed, as maintaining the multiple instances has some cost to the servlet engine.
Instead of using SingleThreadModel, concentrate on writing a thread-safe multi-threaded servlet. See Section 10.4.2 for details on writing efficient thread-safe code. Writing your servlet with big synchronized blocks may be highly thread-safe but won't scale. For example, the following rather extreme implementation synchronizes the entire servlet activity:
public class MyVeryThreadSafeServlet extends HttpServlet { ... public void doGet(HttpServletRequest req, HttpServletResponse res) throws ... { synchronized(this) { //Everything happens in the synchronized block so that //we have a thread-safe servlet ... } } ...
With this servlet implementation, every HTTP request processed by this servlet would have to go through the same synchronized monitor from start to finish, so only one request could be processed at a time, regardless of how many threads you spawned for this servlet. Other concurrent requests would wait until the current request was processed before starting execution. If your servlet received an average of one request per second and the processing took an average of half a second, then this implementation is adequate.
However, if your servlet received an average of one request per second and the processing took an average of two seconds, then your servlet can process an average of only one request every two secondsi.e., half the requests. This is independent of the CPU capability of the server. You could have plenty of spare CPU power; indeed, if you had eight CPUs, this implementation would leave seven of them mostly idle. The result is that the server listen queue would fill up quickly, and your servlet (actually, the TCP stack) would simply reject half the connections. To sum up:
Don't use SingleThreadModel.
Make the servlet thread-safe.
Try to minimize the amount of time spent in synchronized code while still maintaining a thread-safe servlet.
Use as many servlet threads as are needed to handle the request throughput.
Where a limited number of services must be distributed among the servlet threads (for example, database connections), use resource pools (such as database connection pools) to provide optimal service distribution.
The larger the request service time, the greater the number of threads you need to maintain adequate response times for a given rate of requests. | http://etutorials.org/Programming/Java+performance+tuning/Chapter+17.+Tuning+Servlets+and+JSPs/17.1+Dont+Use+SingleThreadModel/ | CC-MAIN-2018-30 | refinedweb | 451 | 53.81 |
Windows SharePoint Services (WSS) sites provide a focused space for users to share
information to achieve a goal or complete a process. Often these sites are customized
by an organization so they meet the exact needs of the type of collaboration
the group of users is trying to perform. Usually each site represents a specific
instance of the process and has the appropriate lists and libraries to store
the necessary information. Though the site services the needs of the group for specific instance of the process, it does very little for the user
who may be involved in many of these sites.
Even though each site has the same type of content, the user would be burdened with
accessing each site during the day to make content changes. So, a good solution
would be to consolidate the content from these similar sites into a single tool
for the user. There the user could maintain the content for all of the sites
and periodically save her changes back to the corresponding lists in SharePoint
sites. Ideally the tool would also provide this information in a way that supports
visualization techniques such as charting. In this article we will detail how
as a developer, you can extend Microsoft Excel to construct such a tool. Actually,
we will provide the list data available to the user event if the user is offline
and not able to reach the SharePoint sites.
Some real world examples
Many organizations use SharePoint as a type of case-management system. Case Management, in general terms, means that there is a documented process for which the organization
manages many instances. For example, any time a military base gets notified of
a distinguished visitor, there is a documented process of what types of actions
need to be taken, documents completed, etc. Yet the base could easily have many
instances of this process for different visitors at different times. The result
is many SharePoint sites. The idea of case management can apply to many other
scenarios: A software-consulting shop would provide a development life cycle
with many specific project instances actively running. A marketing team would
have a collaboration site for each of its campaigns.
Example Overview
Our example sets out to address the scenario in which a user is facing with the challenge
of maintaining the same type of content on many sites. For our example we have
decided to use a list that contains information about the projects. For that
I’ve created a Project Task list provided in SharePoint Site and added couple
of more columns. For every project we will store title, project number, start
date, due date and budget. For the deployment of this project list we will create
a list definition using SharePoint Solution Generator provided with Visual Studio
2008 Extensions for Window SharePoint Services.
With our example of multiple sites with Projects lists, we will develop an application
that gets the information form these different sites into a single place for
our user. For that we will customize a Microsoft Excel workbook using custom
.NET code. When the user opens the spreadsheet, an action pane will open alongside
the document, allowing the user to register the different SharePoint sites and
lists she wishes to maintain in the tool. Each registration of site is considered
as connection. Internally, in the site’s list we will store the connection name,
list’s name, site URL that contains the list and the time of the last modification
made to this site’s list. This information will help us communicate with the
site through web services and synchronize its data. The synchronization interface
provided in the tool enables the user to retrieve all the list items for each
of their connections. Internally, the solution will store this data in a DataSet
while displaying it in a consolidated view for the use – as a single Excel worksheet. Then
the user will be able to use that worksheet to modify any projects list item,
delete project items, or add new project items. By clicking the Synchronize Now
button, all the changes made by user are committed to the original SharePoint
sites’ lists.
By creating the customized solution on top of Microsoft Excel workbook, we get some
additional functionality that improves our tool for the user who is maintaining
all of the content, like, displaying data in worksheet, the user can sort and
filter the data. Though this is provided in the list’s web part, the worksheet
enables the user do to these actions across all the data from all the sites.
The most important is, our internal DataSet is saved with the workbook, so the
list item data is available to the user event if the user is not connected to
the site and is offline. This offline editing capability does provide a powerful
alternative to navigate each site and making the changes online.
Example Walkthrough
This walkthrough will guide the major elements of the solution. First, we will explain
how a list definition is provided to our SharePoint environment to make sure
that each site we want to maintain project information has same projects list.
Then we will focus on the construction and development of the tool to allow a
user to maintain project information from multiple sites, even offline. The tool
will be constructed by extending Microsoft Excel and the walkthrough will guide
you the major phases of development. The walkthrough also will explain the designing
of a DataSet that will store the list information, the development strategy of
detecting network availability and the implementation of action panes to host
our tool’s custom interface. Then we will detail how to synchronize the data
between the DataSet and lists in SharePoint sites.
Note: To implement the solution, your development machine needs the following:
.NET Framework 3.5
Visual Studio .NET 2008
Visual Studio Tools for Office 2007
Office 2007 with primary interop assemblies
Creating the Projects List Definition
Before setting concentration on Excel spreadsheet, we want to take care of the issue
of providing SharePoint sites with the capability to maintain information on
projects. It is important that each site that store project information has the
unique schema. There are two ways to do so: We could create a list template or
a list definition. A list template is typically what an end user would create
by using the web interface to set up the list and then use its “Save as Template”
action in the list’s settings. The result is a file with an STP extension that
is stored in site collection’s List Template Gallery. This STP file is stored
in content database and also includes the customizations that the user made as
well as a reference to the original list definition type. But this opens up some
maintenance concerns and really doesn’t solve the need of a new enterprise-wide
type of list.
List definitions, are stored on the file system and contain a schema XML file that
defines the fields in the list. View information, styles and the forms the user
interacts with are also a part of the list definition. As creating list definition
is considered as a developer task, it is not in so much practice because of the
awkward syntax of XML and CAML (Collaborative Application Markup Language). In
this example we will show you how to get the benefits of having your list as
a definition with the ease of building a template.
The first step is to select a team site you for development and to create a Projects
Task list named Projects. Add some extra columns as shown below using the list’s
Settings administration screen.
Project Number of type Text
Budget of type Currency with two decimal places.
With the list created and modified, we will use the SharePoint Solution Generator
tool included in the Visual Studio 2008 Extensions for Window SharePoint Services
package. This tool needs to be installed on the WSS or MOSS server since it accesses
the object model directly. You can download this from.
Once installed and successfully launched, it looks list the below image.
The SharePoint Solution Generator will create a list definition from an existing
SharePoint list. Follow the below steps through the wizard:
1. Select List Definition and click Next.
2. Select the SharePoint web that contains the Projects list you have created.
3. You will see the set of lists contained within the site. Find your Projects list
and check it and click Next.
4. The Solution Generator creates a visual Studio Project that contains the definition.
This step asks you to name and select the location. Name the solution ProjectsListDef.
The default location is in a SharePoint Definitions folder of your My Documents
folder. Below image shows these options.
5.
6. Click Next.
7. On the last screen, click Finish. The SharePoint Solution Generator will capture
the list as a definition.
While still working on your MOSS server, open the new created project. There are
two settings that need attention. On is in Debug that of project’s properties.
Make sure that start action is set to Start Browser with URL and its value is
a valid SharePoint web application in your development environment. For second
setting, open the ListDefinition.xml file from Project folder from Solution Explorer.
Change the value of the Type attribute to 1001. We want this to be a unique number
so that we can tell Projects lists apart from other site lists.
You can now right click on the project and choose Deploy. Visual Studio will perform
many tasks, including defining your list definition as a SharePoint feature and
then packaging it as a solution to be deployed into you environment.
Once the deployment is done, it can be activated in sites within that web application.
You should delete the Projects list you created in your development site; it
is not an instance of the definition you just deployed. Use the following instructions
to activate the Projects feature, which will make your list definition available.
1. Go to Site Settings.
2. Click on the Site Feature link in the Site Administration group.
3. Find the Projects feature and click the Activate button, if the feature is not
activated.
As the below image shows, once the feature is activated you will see a new Projects
list type on Create page under Custom Lists group. Any site administrator can
now choose to maintain projects. We will be able to identity these lists by their
type and each list will be the same schema. Make sure you have at least two team
sites that have the Projects feature enabled and have instances of the list definition.
Creating the Excel Document Project
Creating an Excel smart document project in Visual Studio is very easy by the project
types VSTO adds. Simply start Visual Studio and select to create a new project.
Under the Visual C# language node, expand the Office node and locate the Excel
Workbook or Excel 2007 Workbook project template. Name the project and solution
MaintainProjectsOffline. Once you click Ok, the VSTO Project wizard will ask
you if you want to create a new Excel workbook or import an existing one. For
this example, however, create a new document named Projects. Once the new project
is created, you solution will already have a few files by default. These are
visible in the Solution Explorer window of Visual Studio. There will be a Projects.xlsx
node that when expanded, will have files for each of the sheets in the Excel
workbook. There are three by default. As we will need only Sheet1, in the Excel
designer, right-click on a worksheet tab to get the delete option and remove
the other worksheets. See how the respective code file is also removed from project.
Now rename the Sheet1 to Projects Sheet, using same way. The designer should
reflect this change and you should see the name appear in parentheses in the
Solution Explorer; however, the code file remains Sheet1.cs. The ThisWorkbook.cs
file has no interface and as it is a class in which code can be written for responding
to events at the document level. In this file, you will find the handlers like
Startup and Shutdown at the workbook scope level.
Designing the DataSet
This tool will allow the user to fetch items in Projects lists from multiple sites
and maintain them within the document. This data will be stored in the document
and made available even if the user is offline. To facilitate this, we will leverage
the smart document’s capability to cache a DataSet in the document. We will use
a single DataSet to store all the required data for solution, including the project
information, the lists that contained that information and some settings information.
Add a new DataSet namd ProjectsData to your solution. Below image show the structure
of the DataSet, which includes a Settings DataTable to store settings information,
a Lists DataTable to store the sources of the data and a Projects DataTable to
store the list information itself.
The Settings DataTable has only two fields: FieldName and FieldValue. The FieldName
column is the table’s primary key. Our solution will use the table to store information
outside the maintained data. For example, a setting would be the one named LastSynchronizationTime,
whose value is the last time the tool successfully synchronized with its lists.
The Lists DataTable stores the locations of the projects lists that the user has
requested to maintain within the tool. This DataTable stores name of the list
in SharePoint Site, a URL to the site, a timestamp of last modification of list
and a string representing the connection name. The connection name is a string
value the user will specify when adding the list to the tool. This connection
name is configured as Primary Key and unique identifier.
The Projects DataTable stores the project information list items. This has a combination
of the connection name and the id of the list item as its primary key. The ListItemID
field is an integer that SharePoint uses internally for list items. We then store
the columns of data in the project list: Title(string), ProjectNumber(String),
StartDate (System.DateTime), EndDate(System.DateTime) and Budget(System.Double).
The Projects DataTable has a relation with its parent Lists DataTable. The relation
is set up between two ConnectionName fields. The ForeightKeyConstraint is configured
to cascade on updates and deletes.
Detecting Internet Connectivity
An important function of any tool that you want to work both online and offline is
its ability to detect connectivity status. In this example, this check is made
within a ConnectionManager class. This class provides an IsOnline() method that
simply returns True if the machine has a valid network connection or False if
it doesn’t. Within this method, the class leverages a PInvoke to a function defined
in the Windows API named InternetGetConnectedState. This is a part of unmanaged
code and contained in wininet library.
public class ConnectionManager
{
[DllImport("wininet", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern bool InternetGetConnectedState(ref long dwflags, long dwReserved);
public static bool IsOnline()
{
long dwflags = 0;
bool WebTest = false;
WebTest = InternetGetConnectedState(ref dwflags, 0L);
return WebTest;
}
}
Constructing the Actions Pane
Microsoft Office 2003 introduced the concept of panes that would display within the
Office application alongside the document. These panes would allow the user to
research information, search or see other data within a SharePoint site. With
Visual Studio Tools for Office you can build two types of panes yourself: Task
Panes are scoped at the application level and can be viewed even if a document
is not open. Actions Panes are used within a specific document. Both can be developed
via .NET user controls.
The code snippet below is from ThisWorkbook.cs. The three user controls are declared
as fields of the workbook. A SetupTaskPane method is called within the workbook’s
startup event handler. This setup method establishes the size and position of
the actions pane within the application. It then instantiates instances of the
controls that will make up our actual action pane’s UI and adds them to the controls
collection of the document’s ActionsPane object.
internal TaskPaneHeader _taskPaneHeader;
internal TaskPaneBody _taskPaneBody;
internal TaskPaneFooter _taskFooter;
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
SetupTaskPane();
}
private void SetupTaskPane()
{
this.Application.CommandBars["Task Pane"].Width = 350;
this.Application.CommandBars["Task Pane"].Position = Microsoft.Office.Core.MsoBarPosition.msoBarLeft;
Globals.Sheet1.Select(true);
_taskPaneHeader = new TaskPaneHeader();
_taskPaneBody = new TaskPaneBody();
_taskFooter = new TaskPaneFooter();
_taskPaneHeader.Dock = DockStyle.Top;
_taskFooter.Dock = DockStyle.Bottom;
this.ActionsPane.Controls.Add(_taskPaneHeader);
this.ActionsPane.Controls.Add(_taskPaneBody);
this.ActionsPane.Controls.Add(_taskFooter);
}
Maintaining the List of Site Connections
The interface that the user will see when opening the tool for the first time allows
her to specify which Projects lists from which sites she wishes to manage in
the spreadsheet. Each list that is maintained is stored with a connection name.
This allows us to uniquely identity lists that may have the same name but were
from different sites. Below image will give view the overview of the control.
The two main actions user can perform are to add or delete a connection. To delete
a connection, we are going to require that the DataSet has no pending changes.
This is so that we can successfully remove the items for that connection and
accept those changes to DataSet without accepting changes the user may have made.
Since we set up the relation to cascade deletions to the child Projects DataTable,
this delete action also removes the associated list items. When the removal is
complete, the changes to the DataSet are committed so that when we sync at some
later time we don’t accidently delete these items from the site.
Adding a new connection to the DataSet involves the user first entering the URL of
the SharePoint site that contains the list she wants to maintain. The URL for
the site should be in the format of.
Once the URL is entered and user clicks the Go button, the site is examined to
find what lists it contains and particularly finding the Projects list definition.
The last step of adding a connection to the DataSet is for the user to select
one of the project lists of the site and to name the connection. When the user
clicks the Add connection button, the selected connection is added to the DataSet.
Until the synchronization is not performed, the items of the list are not seen
in the tool. To identify the newly added list in the DataSet, we set its LastModified
field to DateTime.MinValue.
Implementing the Synchronization UI
The synchronization UI can be brought to forefront by the user clicking the Data
button in the actions pane’s header. The interface persists changes the user
has made to the project list items back to their respective SharePoint sites,
as well as load changes from those lists back into the tool. When the interface
is displayed, the last synchronized time is displayed. The interface also informs
the user of the number of new lists the user added as new connections. These
items need to be retrieved into the tool. Additionally, the interface displays
the number of pending changes the user has made to items and that need to be
saved back to the sites. These statistics are updated whenever the visibility
of the synchronization interface is changed or if the Refresh button is clicked.
This control uses the UpdateSyncStats method to update the values of the number of
new lists and the number of changes. The below code snippet shows the method.
private void UpdateSyncStats()
{
newListsView = new DataView(projectData.Lists);
newListsView.RowFilter = "LastModified='" + DateTime.MinValue.ToString() + "'";
this.lblSyncNewLists.Text = string.Format("{0}: # of new lists to capture", newListsView.Count);
DataTable changedItems = projectData.Projects.GetChanges();
if (changedItems != null)
{
this.lblSyncChanges.Text = string.Format("{0}: # of changes you made to data", changedItems.Rows.Count);
}
else
this.lblSyncChanges.Text = string.Format("{0}: # of changes you made to data", 0);
}
This method determines the number of changes the user has made by calling the GetChanges
method of DataSet’s Projects DataTable. If this method returns a DataTable object,
then there are pending changes which are need to be saved back to SharePoint
sites.
Architecture of the Synchronization Process
The synchronization process is responsible for committing changes, if any, that the
user made to project information in the tool and making those same changes to
the list items in the SharePoint sites. The process must also fetch any list
items that have been modified in the sites’ lists from the last synchronization
time. It is easy to understand the process by viewing the entire process as sequence
of the steps. Below image show the step required for synchronization process.
Our synchronization process first makes sure the tool is not offline. If a connection
is present, it begins to create a batch file for each list to contain the changes
the user made to its list items. This batch contains additions, updates and deletions.
Once the user made changes are persisted back to the sites, the tool looks for
lists that have been modified since the last synchronization. If any are found,
the items for that list are refreshed into the DataSet. After all the changes
have been done, the tool gets the content for the new connections. Finally, the
changes made to the DataSet are committed so that we will be able to identify
changes the user makes from this synchronization point. For detailed code of
this process please download the example.
Associating and displaying the Data on the Spreadsheet
Displaying the DataSet’s data on the spreadsheet requires less code than the synchronization
process. In fact, it requires no code at all. Open the designer of Sheet1. In
Visual Studio’s toolbox, locate the ListObject control in the Excel Controls
group. This control will allow us to bind a range of cell to the Projects DataTable
in the DataSet. Drag it onto the spreadsheet and specify it to occupy the $A$2:$F$2
range. Then use the Properties window to specify a data source. Clicking on the
down arrow of this property should display a dialog. Select the projectsData1
DataSet in the Sheet1 List Instances category. Once that property has been set,
select the Projects DataTable as DataMember property value. The ListObject should
refresh to display the column names for this DataTable. You have now bound the
ListObject control so that it will display the items in the Projects DataTable
of our DataSet. You spreadsheet should look like below.
Using the Tool
Before running the solution, make sure you close the spreadsheet that’s open in Visual
Studio’s designer. Because running the program will launch Excel, which will
open the workbook generated in the bin directory of your project. The same spreadsheet
can’t be open in VS’s designer and in Excel.
For the test, we have at least two team sites with the Projects list definition available
and a few items created already. Click the Start Debugging button in Visual
Studio. This action builds your solution and therefore the workbook. The solution
will open more slowly in this case than normal.
Add the two connections for your sites. Remember that the URL should be in the format. Use the actions pane’s header to display the synchronization
interface. This should tell you that there are two new lists for which you need
to get content. Click the Sync Now button and watch the ListObject populate with
your site’s content. The result should look like below image.
Now make some changes. Change a title or a project number for one row. You can also
highlight one whole new row and right-click to delete it. If you place your cursor
at the bottom of the ListObject where there is an asterisk (*), you can define
a new row. When specifying a new item, you need to enter in a valid connection
name and a unique list-item identifier. Remember that these two fields make up
the primary key. After you have made some changes, click Refresh in the synchronization
interface; it will update to tell you the number of pending changes. Click the
Sync Now button and revisit the lists in the SharePoint sites. Verify that you
changes were persisted.
To see the caching capability, close the Excel. When the application asks you if
you want to save changes, select Yes. By saving the file, you are persisting
the DataSet with the document. Closing the document should end your debug session
in Visual Studio. Use Windows Explorer and navigate to your solution’s bin directory.
Open the Projects.xlsx file to open in Excel. Notice that the data is already
there.
Considering Deployment Options
For document-level projects, an administrator needs to select a deployment model
for distributing the customized document as well as the related code-behind assemblies.
There are three main models characterized by the location of files. Each has
its own benefits and depending on your needs any of them could be used.
The Local/Local deployment mode is one where both the customized document and the
assembly are deployed on the end user’s desktop machine. This model is best suited
when the solution needs to be available regardless of that machine’s network
state.
The Local/Network deployment model involves deploying the document to the user’s
computer but making the assembly available through the network. This could be
accomplished using a network share or a web server. This is the most common deployment
model, as it offers the widest range of benefits. It offers single point of maintenance
for the assembly for solutions where those changes are more likely than updates
to the document. Also, the user can still continue to work when the network is
not available.
The Network/Network deployment model places both the document and the assembly on
a network share or web server. For solutions in which change is frequent this
is ideal since the document and assembly are in a single location for all users.
However, users must need to be connected to the network otherwise the entire
solution is unavailable.
Summary
Hope you have enjoyed the walkthrough and hope this will be helpful to you for your
development task. In this example, we have not considered the collision detection
while synchronizing the changes from DataSet to SharePoint Sites.
Source code
Maintaining offline list content from multiple site in Microsoft Excel | http://www.nullskull.com/a/1519/sharepoint-lists-in-excel-via-vsto.aspx | CC-MAIN-2015-48 | refinedweb | 4,430 | 63.19 |
I dont understand the appearent discrepency in the treatment of the variabe x, y, and z.
Why y isn't treated as x and z?
#include <stdio.h> #include <string.h> int main() { char result[100] = "Philippe Dupont 30"; char x[50]; char y[50]; int z; /*We use sscanf to give a value to the three variables x, y and z. the two first are strings and don't need &.*/ sscanf(result, "%s%s%d", x, y, &z); /*Printing the value of the variables works fine.*/ printf("%s\n", x); printf("%s\n", y); printf("%d\n", z); /*But when I want to print a string in which the variables are, the variable y output is an address, not as for x and z*/ printf("My first name is %s \n my last name is %d \n and I am %d years old\n", x, y, z); return 0; } /*OUTPUT: Philippe Dupont 30 My first name is Philippe my last name is -478321712 and I am 30 years old */ | https://www.daniweb.com/programming/software-development/threads/520976/behevior-of-sscan-function | CC-MAIN-2021-21 | refinedweb | 170 | 83.29 |
A color is normally specified in terms of RGB (red, green and blue) components, but it is also possible to specify HSV (hue, saturation and value) or set a color name (the names are copied from from the X11 color database).
In addition to the RGB value, a QColor also has a pixel value and a validity. The pixel value is used by the underlying window system to refer to a color. It can be thought of as an index into the display hardware's color table.
The validity (isValid()) indicates whether the color is legal at all. For example, a RGB color with RGB values out of range is illegal. For performance reasons, QColor mostly disregards illegal colors. The result of using an invalid color is unspecified and will usually be surprising.
There are 19 predefined QColor objects: white, black, red, darkRed, green, darkGreen, blue, darkBlue, cyan, darkCyan, magenta, darkMagenta, yellow, darkYellow, gray, darkGray, lightGray, color0 and color1, accessible as members of the Qt namespace (ie. Qt::red).
<center>
</center>
The colors color0 (zero pixel value) and color1 (non-zero pixel value) are special colors for drawing in bitmaps. Painting with color0 sets the bitmap bits to 0 (transparent, i.e. background), and painting with color1 sets the bits to 1 (opaque, i.e. foreground).
The QColor class has an efficient, dynamic color allocation strategy. A color is normally allocated the first time it is used (lazy allocation), that is, whenever the pixel() function is called:
<ol type=1>
A color can be set by passing setNamedColor() an RGB string like" #112233", or a color name, e.g. "blue". The names are taken from X11's rgb.txt database but can also be used under Windows. To get a lighter or darker color use light() and dark() respectively. Colors can also be set using setRgb() and setHsv(). The color components can be accessed in one go with rgb() and hsv(), or individually with red(), green() and blue().
Use maxColors() and numBitPlanes() to determine the maximum number of colors and the number of bit planes supported by the underlying window system,
If you need to allocate many colors temporarily, for example in an image viewer application, enterAllocContext(), leaveAllocContext() and destroyAllocContext() will prove useful.:
Here are some examples: Pure red is H=0, S=255, V=255. A dark red, moving slightly towards the magenta, could be H=350 (equivalent to -10), S=255, V=180. A grayish light red could have H about 0 (say 350-359 or 0-10), S about 50-100, and S=255.
Qt returns a hue value of -1 for achromatic colors. If you pass a too-big hue value, Qt forces it into range. Hue 360 or 720 is treated as 0; hue 540 is treated as 180.
See also QPalette, QColorGroup, QApplication::setColorSpec(), Color FAQ, Widget Appearance and Style, Graphics Classes, and Image Processing Classes.
The alpha value of an invalid color is unspecified.
The color is left invalid if any or the arguments are illegal.
The arguments are an RGB value if colorSpec is QColor::Rgb. x (red), y (green), and z (blue). All of them must be in the range 0-255.
The arguments are an HSV value if colorSpec is QColor::Hsv. x (hue) must be -1 for achromatic colors and 0-359 for chromatic colors; y (saturation) and z (value) must both be in the range 0-255.
See also setRgb() and setHsv().
If pixel == 0xffffffff (the default), then the color uses the RGB value in a standard way. If pixel is something else, then the pixel value is set directly to pixel, skipping the normal allocation procedure.
The color is left invalid if name cannot be parsed.
See also setNamedColor().
The color is left invalid if name cannot be parsed.
See also setNamedColor().
Allocating a color means to obtain a pixel value from the RGB specification. The pixel value is an index into the global color table, but should be considered an arbitrary platform-dependent value.
The pixel() function calls alloc() if necessary, so in general you don't need to call this function.
See also enterAllocContext().
The default context is 0.
See also enterAllocContext() and leaveAllocContext().
Returns a darker color if factor is greater than 100. Setting factor to 300 returns a color that has one-third the brightness.
Returns a lighter color if factor is less than 100. We recommend using lighter() for this purpose. If factor is 0 or negative, the return value is unspecified.
(This function converts the current RGB color to HSV, divides V by factor and converts back to RGB.)
See also light().
This function deallocates all colors that were allocated in the specified context. If context == -1, it frees up all colors that the application has allocated. If context == -2, it frees up all colors that the application has allocated, except those in the default context.
The function does nothing for true color displays.
See also enterAllocContext() and alloc().
Example: showimg/showimg.cpp.
Color allocation contexts are useful for programs that need to allocate many colors and throw them away later, like image viewers. The allocation context functions work for true color displays as well as for colormap displays, except that QColor::destroyAllocContext() does nothing for true color.
Example:
QPixmap loadPixmap( QString fileName )
{
static int alloc_context = 0;
if ( alloc_context )
QColor::destroyAllocContext( alloc_context );
alloc_context = QColor::enterAllocContext();
QPixmap pm( fileName );
QColor::leaveAllocContext();
return pm;
}
The example code loads a pixmap from file. It frees up all colors that were allocated the last time loadPixmap() was called.
The initial/default context is 0. Qt keeps a list of colors associated with their allocation contexts. You can call destroyAllocContext() to get rid of all colors that were allocated in a specific context.
Calling enterAllocContext() enters an allocation context. The allocation context lasts until you call leaveAllocContext(). QColor has an internal stack of allocation contexts. Each call to enterAllocContex() must have a corresponding leaveAllocContext().
// context 0 active
int c1 = QColor::enterAllocContext(); // enter context c1
// context c1 active
int c2 = QColor::enterAllocContext(); // enter context c2
// context c2 active
QColor::leaveAllocContext(); // leave context c2
// context c1 active
QColor::leaveAllocContext(); // leave context c1
// context 0 active
// Now, free all colors that were allocated in context c2
QColor::destroyAllocContext( c2 );
You may also want to set the application's color specification. See QApplication::setColorSpec() for more information.
See also leaveAllocContext(), currentAllocContext(), destroyAllocContext(), and QApplication::setColorSpec().
Example: showimg/showimg.cpp.
The hue (which h points to) is set to -1 if the color is achromatic.
Warning: Colors are stored internally as RGB values, so getHSv() may return slightly different values to those set by setHsv().
See also setHsv() and rgb().
See also rgb(), setRgb(), and getHsv().
Example: themes/metal.cpp.
See enterAllocContext() for a detailed explanation.
See also enterAllocContext() and currentAllocContext().
Example: showimg/showimg.cpp.
Returns a lighter color if factor is greater than 100. Setting factor to 150 returns a color that is 50% brighter.
Returns a darker color if factor is less than 100. We recommend using dark() for this purpose. If factor is 0 or negative, the return value is unspecified.
(This function converts the current RGB color to HSV, multiplies V by factor, and converts the result back to RGB.)
See also dark().
Otherwise returns -1. Use numBitPlanes() to calculate the available colors in that case.
See also setNamedColor().
Example: chart/setdataform.cpp.
The returned value.
Returns the pixel value for screen screen.
This value is used by the underlying window system to refer to a color. It can be thought of as an index into the display hardware's color table, but the value is an arbitrary 32-bit value.
The return type QRgb is equivalent to unsigned int.
For an invalid color, the alpha value of the returned color is unspecified.
See also setRgb(), hsv(), qRed(), qBlue(), qGreen(), and isValid().
If s or v are not in the range 0-255, or h is < -1, the color is not changed.
Warning: Colors are stored internally as RGB values, so getHSv() may return slightly different values to those set by setHsv().
See also hsv() and setRgb().
The color is invalid if name cannot be parsed.
See also rgb() and setHsv().
Sets the RGB value to rgb..
Returns a gray value 0..255 from the given rgb colour.
See also qRgb() and QColor::green().
See also qRgb() and QColor::red().
The return type QRgb is equivalent to unsigned int.
See also qRgba(), qRed(), qGreen(), and qBlue().
The return type QRgba is equivalent to unsigned int.
See also qRgb(), qRed(), qGreen(), and qBlue(). | http://www.linuxmanpages.com/man3/qcolor.3qt.php | crawl-003 | refinedweb | 1,425 | 58.89 |
Diego Nehab wrote:
Hi,i was looking for a way to create lua stand alone with luasocket as a single binary. my search has returned nil so far. any pointers or links would be most helpful.There are two independent issues to that. One is how to get require"foo" to find a package "foo" that was linked statically to the executable, instead of trying to load it from the disk. The standard way to do this is via the Lua package proposal, by means of the package.preload table. Placing a function in package.preload["foo"] will instruct require"foo" to use that function as the loader instead of trying to find it automatically by other means. The other issue is how to get the many Lua modules in LuaSocket to get linked statically to your executable. For that, you should use luac and bin2c, both available from the Lua distribution.Once you are familiar with these two issues, it's just a matter of placing all the loaders into package.preload during the initialization of your binary.Regards, Diego.
I have done this as I have commented before and there was a problem where socket.lua did a require("lsocket"). This meant that if you pre loadedthe C library :- lsocket which actually imports into the "socket" namespace then the lua code is never loaded. My fix to this was to import the C functions into
the "lsocket" namespace and assign the functions socket.<x> = lsocket.<x> when the socket lua module is loaded. Has the behaviour of the compat-5.1 module changed so that this no longer is a problem? /Brian | http://lua-users.org/lists/lua-l/2005-05/msg00398.html | CC-MAIN-2020-16 | refinedweb | 274 | 74.69 |
>
I am trying to make a reflection probe render once every second, and blend between the old render and the new one. See how it looks like in Zelda BOTW:
.
I am currently only able to render once every second, but not blend between the old and new cubemap. It instantly swaps to the new one. I found the ReflectionProbe.BlendCubemap function but have had no success with it. Most attempts I make crash Unity, and since there are a grand total of zero examples of it being used online I have a hard time even figuring out if it is the way to go.
I am hoping not to have to rely on blending the cubemaps inside the shader since I want this to work on all objects with all kinds of materials, not just certain ones which are blend-approved...
Here's some of the code I've tried, which in my mind should probably work. All it does is render a new reflection every second with no blending. But as I said there isn't really that much information available about this stuff so I have a hard time to figure out what I am doing wrong.
public class PlayerReflectionProbe : MonoBehaviour
{
private float timer;
public float updateTime = 1f;
private ReflectionProbe thisProbe;
public Texture oldCubemap;
public Texture newCubemap;
private RenderTexture finalCubemap;
public float blend = 0.5f;
public RenderTexture render;
void Awake()
{
// Set up reflection probe component.
if (thisProbe == null)
{
thisProbe = GetComponent<ReflectionProbe>();
}
// Set up final texture diplayed by render probe.
render = new RenderTexture(128, 128, 0);
render.dimension = UnityEngine.Rendering.TextureDimension.Cube;
render.useMipMap = true;
thisProbe.customBakedTexture = render;
}
// Update is called once per frame
void Update()
{
// Blend between old and new.
ReflectionProbe.BlendCubemap(oldCubemap, newCubemap, blend, render);
// Assign final render to probe ???
thisProbe.customBakedTexture = render;
// Update blend
blend -= Time.deltaTime;
if (blend <= 0f)
blend = 1f;
// Render new once every second, and save old render.
timer += Time.deltaTime;
if (timer >= updateTime)
{
oldCubemap = thisProbe.texture;
thisProbe.RenderProbe();
newCubemap = thisProbe.texture;
timer = 0f;
}
}
}
Any help at all.
Standard shader looks incorrect on mobile (weird colors)
1
Answer
Textures different between editor and device
1
Answer
Reflection probes and legacy shaders?
0
Answers
how to do color separation in specular reflections
1
Answer
Self-Illum Fresnel Reflective Bumped Specular issue
0
Answers | https://answers.unity.com/questions/1553065/blend-cubemaps-in-reflection-probe.html | CC-MAIN-2019-18 | refinedweb | 380 | 56.96 |
Need help on Macro that prompts for number of rows to select
Many times I have the need to take a large file with many rows and split it into multiple files - the number of lines can vary. I would like to have a macro that when I run it it will select a prompted number of lines that I can then copy/delete.
Generally the macro would:
- Do Edit - Begin/End Select starting the block select.
- Present the dialog box for Cntl-G where I can specify the line number to go to.
- Execute the Cntl-G jumping me to the specified line number.
- Do Edit - Begin End Select ending the block select.
- Macro ends.
I can record a macro that does the above except the next time I run the macro, it used the number of lines I typed in for the Cntl-G command without displaying the prompt.
Thanks in advance for any guidance.
- Claudia Frank last edited by
edit the shortcuts.xml and put the following line into the place needed
<Action type="2" message="0" wParam="43004" lParam="0" sParam="" />
This should do the trick to let you see the goto dialog.
Cheers
Claudia
That didn’t quit work - it did give me the “goto” dialog, but it didn’t do the block select.
Here is the macro I recorded:
<Macro name=“Block Select” Ctrl=“no” Alt=“no” Shift=“no” Key=“0”>
<Action type=“2” message=“0” wParam=“42020” lParam=“0”
<Action type=“0” message=“2024” wParam=“5000” lParam=“0”
<Action type=“2” message=“0” wParam=“42020” lParam=“0”
/Macro>
- Claudia Frank last edited by Claudia Frank
Looks like the macro doesn’t wait for the dialog to end but continues with the other statements.
Can you split the macro in two parts or is it only those 3 steps to do, namely
begin select - move cursor - end select?
Cheers
Claudia
- Scott Sumner last edited by
Macros don’t always work as the user intends. Suggest you try a scripting language? For example, Pythonscript…here’s
SelectFromCurrentLineToADestinationLIne.pywhich I think meets your spec:
def SFCL2ADL__main(): line1 = editor.lineFromPosition(editor.getCurrentPos()) line_count = editor.getLineCount() user_input = notepad.prompt( 'Enter line # from 1 to {}:'.format(line_count), 'Select from line {} to a specified line'.format(line1 + 1), '') try: line2 = int(user_input) - 1 except: return if not (0 <= line2 <= line_count - 1): return pos1 = editor.positionFromLine(line1 + (1 if line2 < line1 else 0)) pos2 = editor.positionFromLine(line2 + (0 if line2 < line1 else 1)) editor.setSelection(pos2, pos1) SFCL2ADL__main()
Additionally, if you want the destination line to be visible when you are done, add this new line between the
pos2 =...line and the
editor.setSelection(...line:
editor.gotoLine(line2)
Thanks Scott. However, I’ll admit now I’m super dumb on how to have Notepad++ run the script. I copied the script and saved in the file name you had in the Notepad++ directory. I then tried Menu/Run and pointed to that file - W10 opened that file up in “Code Writer”- I don’t think that is what was supposed to happen.
Scripting languages aren’t built in; they’re plugins. Get the Pythonscript plugin via the Plugin Manager. Once installed, select Plugins -> Pythonscript -> New Script. Give it a name (suggest: SelectFromCurrentLineToADestinationLIne.py) and a new file will open up with that name. Paste the contents from earlier in there and save the file. Then choose Plugins -> Pythonscript -> Scripts and choose the script which will cause it to execute in the current file. That script selection method is just for testing everything is working. When you determine that it is, you can bind it to a keycombo of your choosing (via the Plugins -> Pythonscript -> Configuration menu). If you run into trouble, just ask here again.
Thanks Scott for such detailed instructions. I followed them and it worked like a champ. However, when I did add the line to display the destination line, the script appeared to do nothing - so I removed it and it worked again.
- Scott Sumner last edited by
Did you add it at the same indent level as the lines around it?
... pos2 = editor.positionFromLine(line2 + (0 if line2 < line1 else 1)) editor.gotoLine(line2) editor.setSelection(pos2, pos1) ...
After running the script is there any information (in the form of “errors”) shown in this window?: Plugins -> Pythonscript -> Show Console
Is your file long enough to not all fit on screen at the same time, and your destination line specified is not on-screen when the script is run?
Yes I have it at the same indent level, the file has 23K lines, and yes I do get an error in the console window:
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
Initialisation took 313ms
Ready.
File “C:\Users\JohnMurray\AppData\Roaming\Notepad++\plugins\Config\PythonScript\scripts\SelectFromCurrentLineToADestinationLIne.py”, line 13
editor.gotoLine(line2)
^
IndentationError: unexpected indent
So very likely is that you have a “tab character” in there. If you turn visible-whitespace on (View (menu) -> Show Symbol -> Show White Space and TAB), I would think you would see something like this:
See that long arrow…highlighted in yellow for me (wouldn’t be yellow for you)…that’s going to be the problem. If you go in and delete that arrow, and then put 4 spaces at the beginning of that line, I think that will solve it.
Of course, I could be wrong…
You were right - that took care of it - and everything works perfectly now. Thanks a bunch Scott for hanging in there with me. | https://community.notepad-plus-plus.org/topic/16045/need-help-on-macro-that-prompts-for-number-of-rows-to-select | CC-MAIN-2019-43 | refinedweb | 933 | 64.71 |
Service Calls
Various components allow calling services when a certain event occurs. The most common one is calling a service when an automation trigger happens. But a service can also be called from a script or via the Amazon Echo.
The configuration options to call a config are the same between all components and are described on this page.
Examples on this page will be given as part of an automation component configuration but different approaches can be used for other components too.
Use the
service developer tool in the frontend to discover available services.
The basics
Call the service
homeassistant.turn_on on the entity
group.living_room. This will turn all members of
group.living_room on. You can also omit
entity_id and it will turn on all possible entities.
service: homeassistant.turn_on entity_id: group.living_room
Passing data to the service call
You can also specify other parameters beside the entity to target. For example, the light turn on service allows specifying the brightness.
service: light.turn_on entity_id: group.living_room data: brightness: 120 rgb_color: [255, 0, 0]
Use templates to decide which service to call
You can use templating support to dynamically choose which service to call. For example, you can call a certain service based on if a light is on.
service_template: > {% if states.sensor.temperature.state | float > 15 %} switch.turn_on {% else %} switch.turn_off {% endif %} entity_id: switch.ac
Using the Services Developer Tool
You can use the Services Developer Tool to test data to pass in a service call. For example, you may test turning on or off a ‘group’ (See [groups] for more info)
To turn a group on or off, pass the following info:
Domain:
homeassistant
Service:
turn_on
Service Data:
{ "entity_id": "group.kitchen" }
Use templates to determine the attributes
Templates can also be used for the data that you pass to the service call.
service: thermostat.set_temperature data_template: entity_id: > {% if is_state('device_tracker.paulus', 'home') %} thermostat.upstairs {% else %} thermostat.downstairs {% endif %} temperature: {{ 22 - distance(states.device_tracker.paulus) }} | https://home-assistant.io/docs/scripts/service-calls/ | CC-MAIN-2018-13 | refinedweb | 328 | 51.55 |
I have a python script added to a toolbox in ArcGIS Pro 2.8. I need to terminate early if certain conditions are met but I need the script to complete successfully and not error. I am trying to use sys.exit(0) and it says the script run succeeded in messages. However the History pane is showing it as a Red ! as if it failed which is blocking me from publishing as a web tool. Is there a better way to exit early?
Solved! Go to Solution.
I just figured it out. I was able to just use return to move me back to def main.
""" def main(): tbx = Toolbox() tool = ExposureTool() tool.execute(tool.getParameterInfo(),None) if __name__ == '__main__': main() """
Could you provide the code?
Here is that specific part as the entire code is rather large. What I am trying to do is create a tool that will be published but I do not want people seeing the syntax used for the input. So I need the tool to successfully run by using some placeholder text rather than valid json the tool would need to fully execute.
def execute(self, parameters, messages): """The source code of the tool.""" # setting up needed pieces messages = [] contact_lists = [] email_list = [] # setting up logging LOG_FILENAME = sys.path[0] + "\\logging_AmicaGP." + dt.now().strftime("%Y%m%d%H%M%S%f") + ".txt" logging.basicConfig(filename=LOG_FILENAME, format='%(asctime)s %(levelname)s %(message)s', level=10) with open(LOG_FILENAME, 'w'): pass arcpy.AddMessage("log file: " + LOG_FILENAME) logging.debug('This is a LOG file for AMICA GP tool') arcpy.Delete_management("in_memory") json_in = parameters[0].valueAsText if json_in == 'Input Feature': logging.debug('Setting up discrete input for publishing purposes') sys.exit(0)
Not sure this will work, but have you tried wrapping the json_in process into a try/except and in the except block log the debug message and exit?
Instead of sys.exit() can you try quit() ?
import time for x in range(0,10): if x == 9: print(f'{x} Quit in 5 seconds') time.sleep(5) quit()
Quit() is giving me the same result as sys.Exit()
I just figured it out. I was able to just use return to move me back to def main.
""" def main(): tbx = Toolbox() tool = ExposureTool() tool.execute(tool.getParameterInfo(),None) if __name__ == '__main__': main() """ | https://community.esri.com/t5/python-questions/exit-not-allowing-script-to-show-in-pro/td-p/1078645 | CC-MAIN-2022-27 | refinedweb | 386 | 60.92 |
User_talk: Rabbit8888
On 01:45, 24 August 2007
KnowItSome said:
You will perhaps want to move thisto your own namespace so that it will not be deleted. I would suggest moving it to this red link, which will become blue once you open it and edit and save. User:Rabbit8888/Articles
On 01:30, 30 August 2007
KnowItSome said:
It has been six days. I have deleted the above article. Here is your content, in case you want to post this on your new page in your own userspace. Fake Fire on Club Penguin Create A Yellow Light
On 02:23, 29 November 2007
KnowItSome said:
On 02:27, 29 November 2007
Rabbit8888 said:
???
Rabit8888,
Hey there. I noticed you placed a speedy delete on a page about video gaming? I didn't see why the page was at all deserving of a speedy deletion, or any deletion for that matter, so I rolled it back.
Also, I redirected your personal welcome template welcomer to the standard welcome. I did this since personal welcomes belong in the user namespace, not in the main template namespace. But also because your template had animated graphics, which we do not allow on welcome messages. Hope you are OK with that.
I would recommend just using the standard {{welcome}} template. :) It is the easiest and is always up to date with correct info.
Brilliant patrolling! Keep it up :)
On 05:27, 18 December 2007
67.173.80.133 said:
Hi ... you've had my MySQL page locked since yesterday ... are you really editing, or is it accidental? Thanks, sharimo1.
Hi Rabbit8888,
I have.
Please remember that you can refresh {{inuse}} tags by following the instructions on the tag itself if you plan to continue editing the article in the near future.
Thanks,
Martyn
Please read the Writer's Guide, so that you can write articles with correct wikiHow format. Thanks!
When you NFD an article, please put that in the Edit Summary, too. Thanks!
On 20:07, 18 February 2008
98.207.43.189 said:
Minesweeper hack: It does? It doesn't work for me. :(
On 08:53, 17 March 2008
213.42.21.59 said:
yo bro!
can you teach me how to do it??
On 02:01, 9 September 2008
OMJ_imtherebiggestfan said:
Hey do you like bunnies i dont????????????i think their evil and im afraid of them seorously no joke.
Nope, I wasn't forgotten I was welcomed when I joined, ages over, over a year...or 2. Haha, I delete all the messages on my talk page sooner or later.
Benny
Lol, fun :P Wo0t indeed. I didn't think anyone actually read my user page..:O *shocked* I still update it...but I didn't think anyone cared lol.
Thanks
Benny
On 21:30, 31 January 2009
72.39.72.125 said:
you took credit for the page "how to make dog poo" when we wrote it!!!!
We all are... And also tired of having the jokesters act all indignant afterward, as if this is a site where anything goes... Oh well, ever onward. And thanks for patrolling - it is much appreciated.
On 21:48, 31 January 2009
Sam & Ashley said:
We made the edit because we wanted credit for the article we created it before we created an account. so it was our article
On 21:53, 31 January 2009
Sam & Ashley said:
what do you mean by vadal attack?
On 21:55, 31 January 2009
Sam & Ashley said:
ok thank you we will be sure to be careful
Hi,
I know you're trying to help, but when the "inuse" tag is on an article, as was the case for Connect Two Hard Drives to On Computer and Transfer All Info to the Other that I was working on, making additional edits only serves to break up the editing process when I tried to perform a "save" operation.
The "inuse" tag is put up specifically to prevent others from making changes until the person that placed it, is through. In the future, if you could just wait for the tag to come down before making your edits, it would be most appreciated.
Thanks!
I double back up the above comment. Try to see how you'd feel if someone edited an article you were starting while you were still working on it... Anyway, thanks for the help around wikiHow. Cheers!
Recruit Contest! Spread the Word!
excuse me?
i mean "runaway". never heard the term. And by the way, did it take you over 1 hr to read my page?
On 00:25, 9 February 2009
Paramore_punk15 said:
SHUT UP IM NEW
I'm sorry, I was not vandalizing -.-. Please only issue warnings to users who warrant them.
~ SK
You might want to look around and do a little investigation before placing warning templates on actual users (as opposed to anons). There is usually a reason (USUALLY) for what they did. Always TRY to remember good faith.
Welcome to the RuneScape Formatting project!
I was just showing you the edit you made
Thanks. I am feeling more furious than humorous right now. Catch you later.
On 01:46, February 10, 2009
Tracy de Moines said:
Rabbit,
I noticed you welcomed Insane_Monkey one week ago. You should know that he's been here since 2007.
~ Tracy de Moines 01:46, 10 February 2009 (GMT)
Hello,
I noticed you've been posting random and irrelevant comments on discussion pages. You may have done this as a test or in error as you were learning how wikiHow works. However, this creates extra work for our patrollers.
A discussion page is a place to converse about an article's content. Some typical topics include:
- Is this article accurate?
- Is this article helpful or useful?
- Is the content appropriate for wikiHow?
- Does this page follow our Writer's Guide?
Feel free to contact me, an admin, or the Help Team with any questions.
Please stick around and try to edit more constructively!
I promise i will not let out any of the info that you said i shouldn't.
Hi Rabbit! If you see anymore edits where registered users under 13 post personal information (including their age), please link to them on the wikiHow:Admin Notice Board. (The template you used is mainly for unregistered users.) Do continue to remove the info, and just link to an old revision at the notice board. Unfortunately, under US law we have to block underage users like Bells458 on wikiHow. :(
Thanks,
I agree with you on the put flash games on psp featured article
On 06:12, 4 May 2009
Donkeybones said:
Sorry, but I'm kind of new here. What is the RC list, and what do you mean by flooding it? And if I am flooding it, how do I stop?
If RC should happen to stand for "recommended changes," I'm not recommending any changes to anybody's pages with any regularity, although I'm making a lot of changes on my own page, but these are usually minor edits. (Maybe I just have to be sure to check the "minor edit" box each time, and use the preview feature more.)
Am I on the right track? If so, please accept my apologies and thanks for pointing this out to me. Please advise.
Thanks,
Don
On 06:21, 4 May 2009
Donkeybones said:
OK -- guess I have to use the preview and minor edits function more. Thanks. Don.
Thanks for your edits on Get a Girlfriend.
On 10:22, 17 June 2009
118.90.21.205 said:
i don't know what your talking about sorry. if i ever did something in some way like you described, that wasn't me. as for well, the editing, i did not edit anything. maybe, it's commenting you were refering to. and actually i found mine to be the fairest and some of the most intelligent posted on here. so i don't see if you have a problem. also mr. moderator, 5 or so of my comments were deleted, care to explain why that might be?
that which has seemingly angered me to the last degree, someone deleting my post. whoever the culprit is deserves to be kicked multiple times and then banned. my comments were genuine and constructive, undoubtedly if everyone heeded them the world would be a better place.
I have a great idea for you. | http://www.wikihow.com/User_talk:Rabbit8888 | crawl-002 | refinedweb | 1,404 | 75.1 |
Talk:Proposed features/orchard
Contents
Areas, and nodes
I notice that the tag is only proposed for areas. It seems common practice for other area specific tags to also include nodes as an option. Making the tag also applicable to nodes (and encouraging renderers to support it) would allow the tag to be used in cases where the extent is unknown. Importing GeoNET Names Server (GNS) data is one example of when node-tagging would be valuable, since GNS data only consists of points. Aside from this, I like the proposal. --DanHomerick 18:57, 28 September 2009 (UTC)
- Yes, I don't see why it couldn't be used as a node. --Pieren 19:53, 28 September 2009 (UTC)
Ok with me: in Turkey for example where ever is water you find such orchards which may be quite inhomogeneous areas without fences indicating parcel boundaries and growing grapes, apricots, apples, walnuts, pistachio as well as salads and vegetable near one another. These I would not call landuse=farm or landuse=allotments so landuse=orchard is useful. --katpatuka 05:16, 29 September 2009 (UTC)
- Maybe the syntax landuse=orchard + trees:apple_trees=yes + trees:apricot_trees=yes + trees:olive_trees=yes should be applied. Thus, the renderers could render at least the orchard, but a search engine could find apple trees, olive trees...FrViPofm 09:16, 29 September 2009 (UTC)
Trees or fruits
As not all fruits grow on trees, I would prefer fruits=apples instead of trees=apples. Then we can use fruit=vine for vineyard. --Lulu-Ann 08:18, 29 September 2009 (UTC)
- I think you mean fruit=grapes rather then vine. You're perhaps thinking of vines=grapes for a reason why trees isn't a suitable word. Although technically, a vineyard isn't an orchard and I think there is already an existing tag for it. --EdLoach 08:21, 29 September 2009 (UTC)
- Because the aim is to map what is on the ground, because all trees are cultivated not only for fruits (branches, sap or resin, truffle...), as fruits are on trees only for a short period whereas trees remains (even without leaves), trees sounds better. The produce=latex/apple/truffle/coconut/cork tag can also be added, with other effets on rendering, or the vine=meursault/cabernet/muscat on a landuse=vineyard. It could be interserting to have such information on doing a map of "truffle production area". I add the tag as an option on the proposal.FrViPofm 08:55, 29 September 2009 (UTC)
- what are the fields/plantations/orchards for strawberries, cranberries, raspberries, blackberries, bilberries, gooseberries called in English? Aren't they orchards? According to wikipedia:en they are (as they include shrubs in the definition): -- Dieterdreist 10:40, 29 September 2009 (UTC)
I like the general idea but would limit the use of 'orchard' to cases where the plant is 'woody' and more than a shrub (i.e. a tree) and where the main purpose of growing the plant is for the production of its fruit for use - directly or indirectly - as food or drink. Bear in mind that nuts are a kind of 'fruit'. My definition would deliberately exclude: willow plantations for wicker (the commercial product is not the fruit of the willow but its branches - and the use of the product is not food/drink related). I would also exclude the production of 'soft fruit' (e.g. strawberries, cranberries, blueberries - and probably also raspeberries, gooseberries, blackcurrants, etc. - even though the plants are in some cases woody shrubs or sub-shrubs they are not trees and fields planted with these 'soft fruit' crops are normally referred to as a fruit-farm) - thus I am really restricting 'orchard' in my mind to the production of 'hard fruit' - with vineyards a bit of a borderline case - and of such enormous importance to the sum total of human happiness to require a special tag 'vineyard' of their own (:>) On balance I am inclined to express a 'yes' opinion, which I will do on the main page. Mikh43 12:33, 15 October 2009 (UTC)
- I understand what you mean. But it seems that 'orchard' by extension is also used for non-trees plantations as it is said on Wikipedia : "A fruit garden is generally synonymous with an orchard, although it is set on a smaller non-commercial scale and may emphasize berry shrubs in preference to fruit trees.". This is probably a question of local practices and we should not restrict the use of orchard if it is called like that locally. And more important is the combination with a second key providing more details about the fruits coming from there. -- Pieren 13:43, 15 October 2009 (UTC)
Meadow orchard (de:Streuobstwiese)
I'd like to see a differentiation of Orchards and Meadow orchards (less intense, traditional form of cultivating fruit). A definition could be this: -- Dieterdreist 10:40, 29 September 2009 (UTC)
- There was an idea to have the cultivation method in a tag here: Talk:Tag:landuse=farm. How about cultivation_method=extensive? I guess that would fit. --Lulu-Ann 12:17, 29 September 2009 (UTC)
Farm
So, given this is a type of farm, why don't you just use landuse=farm as the base tag and then add extra tags to tell what they're growing? These orchards are all tagged as farms over here. --Eimai 11:19, 29 September 2009 (UTC)
- I agree, this sounds like a much better idea. -- Gustavf 11:42, 29 September 2009 (UTC)
- +1 from me. --Lulu-Ann 12:13, 29 September 2009 (UTC)
- No. Orchard is not always owned by farmers or for intensive production and resale. Many (small) orchards in my country belong to families who are not farmers. Or do you include garden in your landuse=farm ? As I said above, I would keep farm for non permanent produce and take a specific landuse for other permanent features --Pieren 13:50, 29 September 2009 (UTC)
- Well, get rid of landuse=farm then anyway because it's completely useless then, as it's obviously used for the wrong things so far if one takes your definition. As it stands now it's being used for everything where people are either growing things or keeping animals, which isn't part of someones private garden (which includes allotments), and isn't a forest. So that's one tag easily covering half the country over here. If you're now going to specialize all that, then please go back to the drawing board instead of patching things with just one new tag like orchard and basically saying that half of the country is now mistagged as farm.
- Not very easy of course given the "landuse" tag is already in use now and it would be the obvious tag for it, but be creative :-). May I suggest you look into the legend of our NGI/IGN maps of 1:10000 over here, which are a great source to get an idea for what's needed. [1] and click "Bodemgebruik", it has Dutch, French, German and English definitions. Looks like they have a nice new possible tag name as well: "soil covering". --Eimai 15:41, 29 September 2009 (UTC)
- Very interesting link ! I thing it is what we are doing with the WikiProject Corine Land Cover/Tagging scheme. You can start translating this page for the next CLC import in Belgium ;-) Lot of item are near! FrViPofm 16:04, 29 September 2009 (UTC)
- I disagree. An orchard is not necessarily a farm. They are two different things. The only common point would be that people are growing "stuff" on it. There was an abandoned orchard a few years ago a few hundred meter from my home where people used to get their fruits. It was owned by the town and tendered by people who wanted it. In addition, a farm is looking very different from an orchard. It is an integral part of how the land looks. It would confuse things. If you follow that logic, then you will want to remove the vineyard from OSM too since they are farm land. --Melaskia 13:59, 29 September 2009
- I have tested the tag on a part of land in my neighbourhood. A little orchard with apple trees. But the owner is not a farmer, he is retired, but was a famour pastry-cook. His orchard gave him apple for apple pies known by every body in Besançon. Now with an other retired man he press the apple and produce a juce for the children. It is not a farm, but it is an orchard.
- Ok, we can tag all the ground used by farmer as landuse=farm. But waht with landuse=meadow? what with landuse=vineyard ? As I can see in the landuse=farm page, the aim of the tag was to fill large part of landscape, at the scale of a village, even more... The talk page suggested that it seemed impossible to tag with accuracy wide spaces... Today with the Corine Land Cover projet we are able to map a whole country with details up to 25 ha, with great knowledge of the ground and vegetation.
- Yes, we still can map everything with farm. But I have worked with other good maps (IGN 1/25000°) with more acuracy than farm. I have worked in agruculture (owning 400 sheeps) an I know that a field, a meadow, a vineyard, an orchard are things different, worked differently, looking differently in the landscape. A pity the use of landuse=farm. landuse=farmland is less confusing. I would rather use landuse=field for worked ground (annually), landuse=meadow for pluri-annual or natural meadow, surface of grass (but not the landuse=pasture ! The whole Sahara is pastured extensively !). But not farm! In a short time, we will get 3 tags on OSM : natural=wood, landuse=farm, landuse=redidential. Those who have propoted such a tag have never worked outside ! FrViPofm 14:07, 29 September 2009 (UTC)
- If using landuse=farm + farming=orchard (or something similar), you will not loose detail and you will still have data that are easily used by those not interested in the details. The vineyard tagging was probably a mistake, that is no reason to do the same mistake twice. I also fail to see that something stops being a farm if the owner retires or dies. -- Gustavf 06:24, 30 September 2009 (UTC)
- What is not interested in the details ? Is it having 2 basic tags nature=forest/water landuse=farm/residential ? No I think (and I'm not alone: see the talk page) that landuse=farm was a mistake. What about a meadow ? Is it farm ? Is it nature ? The aim of creating this value was to find someting saying 'we are not in the wild, but we are not in the city'. But someting poor for those tagging from motorway (see the discussion page).
- For those not interested, the existence of the landuse or nature would be enough. Let other enrich the semantic of OSM, for those interested. Have a look to the map beeing build by the actual mass import of Corine. You will see the interest.
- I like the idea of tree tagging 'mm=nn + nn=oo' and also the syntax 'mm:nn=oo' namespace like, and I would promote it to make the tagging more semantic. But it is not aplyable every where. An orchard is not always owned by an alive farmer, and should we not map it in this case ? OSM is not a way to record if the owner is an alive farmer. OSM is not a demographic map ;-) FrViPofm 08:01, 30 September 2009 (UTC)
- So landuse=farm was a mistake. I can agree with that, but you do not correct that mistake by making antother mistake.
- Say, i want to make a Norwegian map with focus on what is usual and important in Norway. I would end up with 5-10 different renderings for skiing related ways, and probably one or two for farming related landuses and no special rule for orchards or vineyards. If I choose to render the whole world, a rule for landuse=farm + farming=orchard would be rendered and the map users would get a general idea of what that land is. Your beloved landuse=orchard, on the other hand, would show up a blank, unmapped space. Why do you want to force as many renderers as possible to have as many special rules as possible? What information is lost with landuse=farm + farming=orchard (or landuse=forest + farming=orchard, if that would be more suitable)? -- Gustavf 10:06, 30 September 2009 (UTC)
- We don't create tags for the renderers but to identify what we see on the ground. When I see an orchard, I cannot say if it belongs to a farmer or not. But I can say "it's an orchard !". We started to specialize this type of landuse with vineyard and I think it is not a mistake since such plantations are permanent and useful information. If we follow this principle of putting everything into subcategories, why are we continuing to use landuse=residential/commercial/industrial/retail/etc.. as It could be easily replaced by landuse=buildings+buildings=residential/commercial/industrial/retail/etc. I'm just wondering why we have a concept of key:value for the tags if we always have to create a key:category + category:value. My guess is that people against this value are just thinking about the renderers, not for the best and easy way to represent the world. --Pieren 11:52, 30 September 2009 (UTC)
- Like I said above, the landuse tag has become a mess anyway. Sometimes it says what there is on the ground, sometimes it says what it is used for, and often it's not clear which of the two applies. Resulting in discussions like this. It can only be solved by rethinking the whole concept or discussions like this will appear over and over again. --Eimai 12:22, 30 September 2009 (UTC)
- Ok, Gustavf, I understand your preoccupation. How to render simply the complexity of the world? But, they are few things I have leart since I map on OSM. One is Relations are not categories, an other is We don't map for the rendering (and Pieren, above, told me that several times ;-).
- I agree that the way of tagging on OSM is far from simple, far from being semanticaly consitent, and I would have predered namespace-like tagging. But its the way that OSM has grown. On the french list we have had a discussion on the landuse=military with landuse=forest, how to resolve the multi-use. That is: how to map the complexity ? And the complexity is orchards (and also vineyard and vegetable garden) are not always farmlands. I gave an example for the orchard, I can give also examples of vineyard that are not of farms, in big cities. Will we have other blanks because, for simplicity, we can't map orchards that are not of farms? Yes, the tagging must be consistent and a consistent tagging would prepare the work for renderers (it is the aim of the Proposed features, tagwatch shows that exists inconsitent tagging !). No, the tagging must not be subjected to the rendering. In your case, you can set the renderer to render orchards and vineyard as farmland. It would be lazyness and lack of accuracy to map orchards and vineyards and vegetable gardens as farmland. And taking your example, I would have to create a new value for the landuse for orchards, vineyards, vegetable gardens that are not in a residential, that are not of a farm, because landuse=forest is not suitable, because farming=orchard is a non-sense in those cases, (it's not farming), because farming is not in the namespace of residential ? You would encounter the same problem: too much first level tags or you would create more inconsitent tagging with landuse=everything, farming=whatever, (the french expression République bananière should be tagged landuse=military + farming=banana + admin_level=2 ;-). Yes, being simple is difficult and OSM has to strength its semantic, but the work of the rendering is not the work of the mapping and tagging. FrViPofm 12:48, 30 September 2009 (UTC)
- Understanding what tagging for the renderer means is a very good start. It does not mean "pelase make data difficult to use for the renderer". -- Gustavf 13:30, 30 September 2009 (UTC)
- We understand what means "not tagging for the renderer" but here you try to categorize/simplify tags in landuse=farm when it is not required with the idea behind that it will make the rendering job easier because it will be rendered immediately and without any modification. I would add a new statement "don't create tag subcategories to make your new value rendered immediately when it is not a subcategory". -- Pieren 14:01, 30 September 2009 (UTC)
- I agree. The question then is if an orchard also is farmland. I think most Norwegian farmers (coming from a farm myself) would say that apples is a crop, even if the plants live somewhat longer than other multi year crops common in Norway (strawberries, for example). I can certainly see that this is can be different in other countries/languages/cultures. -- Gustavf 15:33, 30 September 2009 (UTC)
Tree nursery
I don't understand what a tree nursery is doing under orchard. In all the other mentioned examples, when the harvest takes place the trees stay. When you "harvest" trees from a tree nursery the trees themselves are removed. Not to mention that I don't think in normal language usage, a tree nursery would be called an orchard. Also in the topographic maps produced by (for???) the Dutch government tree nurseries and orchards have a different symbol. --Cartinus 01:07, 30 September 2009 (UTC)
- I've put the tree nurcery because it was a question on the plantage talk page... I've not made my mind about it. In a way tree nurcery has to see with trees for orchards (or gardens). In an other way, you are right, the whole plant is gathered. But usualy the small trees are in place for 2-3 years and the piece of land is a tree nurcery for several years. I thought also that it would never be a tag for this too specific landuse, so it could be a special value of orchard. Have you suggestions of other tagging, example of rendering in the topo maps? The landuse=orchard + trees=nurcery can have its specific rendering... FrViPofm 13:18, 30 September 2009 (UTC)
- A tree nursery is not an orchard, so it can't be a subtag. It needs its own landuse tag then. An orchard is for harvesting the fruit, a tree nursery is for "harvesting" the whole tree. I doubt those two are ever combined... --Eimai 13:35, 30 September 2009 (UTC)
- I agree with Eimai, a tree nursery is not an orchard and is not necessary about fruit trees. It should be removed from the proposal to avoid confusion. --Pieren 13:53, 30 September 2009 (UTC)
- I agree too. Additionnally, about nurseries, I believe we should rather talk about "plants nurseries", as they often (I believe) grow not only trees, but other kinds of vegetals. --Leblatt 20:55, 30 September 2009 (UTC)
- If nobody want nurcery as subtag of orchard, I will remove it ( I will say it is rejected ). Let us way tomorrow...
- But the concept of orchard, in OSM, will necessary be wider than in the Devonshire... We must take in account tree production that is not fruit, even if it is not in the original concept ! The aerial view [2] shows oak plantations for truffles. Some would object that oaks are not orchard : we don't gather the fruit, the acorn. But [3] showing peach trees, and a walk through such plantations convinces that, in term of landuse (planted trees in lines, worked ground, network of tracks), they are very similar. I have no reference of oaks plantation for cork in Portugal. If somebody find an areal view... FrViPofm 22:02, 30 September 2009 (UTC)
- Ok, we could consider tree plantations for cork and truffle as part of this landuse. But it shouldn't be listed in the main definition because "culture of any kind of trees" is too vague. But we could mention these as special cases to be considered in the middle of the proposal. -- Pieren 14:29, 1 October 2009 (UTC)
Reword the definition of orchard
As said above, orchard is not a tree nursery. I think we should reword the whole definition of the tag, e.g. remove the terms "culture of trees" which is ambigus. We should be much closer to the wikipedia definition of orchard which is the common understanding of this word :
"An orchard is an intentional planting of trees or shrubs maintained for food production. Orchards comprise fruit or nut-producing trees grown for commercial production. This tag can also apply to a fruit garden, generally synonymous with an orchard, although it is set on a smaller non-commercial scale and may emphasize berry shrubs in preference to fruit trees." (based on [4])
--Pieren 11:42, 1 October 2009 (UTC)
Post vote modification not acceptable
The proposal has been modified after people started voting (And at least after I voted)
- landuse=orchard + trees=apple_trees
was changed to :
- landuse=orchard + tree=apple OR trees=apple_trees
Where was it discussed that there should be an OR ? have all voters been warned ? or is this just an error I can revert ? sletuffe 12:38, 24 October 2009 (UTC) | https://wiki.openstreetmap.org/wiki/Talk:Proposed_features/orchard | CC-MAIN-2019-13 | refinedweb | 3,616 | 70.84 |
This is the second and final post on building analytics at CircleCI. This post picks up where the last left off, and specifically deals with the in-house implementations I came up with to deal with the problem(s) from Part 1.
The third-party platforms we had decided on (Segment, Amplitude, and Looker) solved the issues of combining demographic (persistent) and behavioral (event-specific) data and of creating org funnels. We solved the problem of data integrity–created by a poor integration with our previous analytics provider–by rewriting our integration code when switching to our new provider, Segment. The only other main issue this combination of platforms did not help alleviate was data cohesion and consistency. As a result, this became my main focus during implementation.
A consistent taxonomy, free of duplicate events, is the bedrock of a robust behavioral analytics infrastructure. Having this foundation increases ease of understanding, making it easier to understand and use the data effectively, which ultimately accelerates analysis and adoption rates.
So, it was my job to build a platform that would ensure developers named events in a way that was not only clear to users, but also wouldn’t accidentally create analogous or duplicate events. However, equally as important, the taxonomy had to make it simple for developers to add new events. Because when event creation became too difficult, it is seen as burden on productivity, and is not added to the development workflow.
Event Schema and Taxonomy
There are two main pieces of behavioral analytics, and therefore two places I needed focus on ensuring consistency: event names and event data.
Event Names
Without an authoritative schema for event names, our previous implementation had seen issues surrounding analogous event names such as
clicked-signup and
signup-clicked. To counteract this Wild West of event names I tackled my first challenge: designing a schema that was both consistent and intuitive.
Looking at the user interactions we care about on the site, it was clear that the majority were impressions, clicks, and state changes triggered by a user’s action. After reviewing many of our existing event names, I boiled the necessary structure down to a schema that would address all of these cases. The new convention became:
An example of this breakdown can be seen in the execution of:
upgrade-button-impression,
upgrade-button-clicked, and
plan-upgraded. Each represents a segment of our plan upgrade funnel: one for when the user sees the upgrade button, another for when they click it, and another when their plan is upgraded in the database. And each falls within the schema.
What is excluded from the event name is just as important as what is included. Take this beauty:
blue-signup-button-header-enterprise-page-clicked. CircleCI is not alone in this crime against brevity; I’ve seen this type of verbosity at many of my former companies. On the one hand, this name is extremely intuitive. It would be nearly impossible for a data consumer to misinterpret this event’s action. However, if event names are too granular, they run the risk of polluting the analytics namespace, becoming a burden on analysis.
From a data analytics perspective, this type of aggressive segmentation creates statistical nightmares. In order to calculate something as basic as the number of signup buttons clicked, it is now necessary to aggregate information across several events. Simplifying your behavioral data allows you to quickly and easily have a high-level view of which actions are being taken on which features across your platform.
If this example seems a bit hyperbolic it’s because it is. Usually, developers don’t try to force all information about an event into its name. However, there is one piece of information that developers are consistently keen on putting into the name: the location of the event. However, the schema very purposely excludes this information from the event name. Event names should be view- (and component-) agnostic; names should only represent user actions, and exclude where that action took place.
Event Data
Now, I’m not saying that an event’s location is unimportant; it absolutely is. It just shouldn’t be stored in the event name. If you see a 30% rise in signups one week, you’ll definitely want to see which page generated those signups.
Enter the use of event data.
With our behavioral analytics platforms (Segment + Amplitude), event data is crucial for segmenting events. In our SQL warehouse, Segment creates a table for each unique event name and converts each piece of the event data into a column in that table. This allows us to use SQL statements like WHERE and GROUP BY to partition event tables and gain more granular insights.
In Amplitude, we can use these same event data pieces to segment the data or create user cohorts. For example, we could group users into cohorts depending on how they followed their first project (via our “Add Projects” page or the “Follow Project” button at the top of a build). These cohorts (
project-followed.view =
add-projects and
project-followed.view =
build, respectively) could then be used to measure retention.
As with event names, it’s important to have a consistent event data schema. If
org refers to the organization name on one event, and the organization’s id on another event, then the event data becomes just as confusing and ineffectual as our event names used to be.
Because each event may require custom data, it’s challenging to completely schematize the event data taxonomy. For example, our
teammates-invited event has a
num-teammates property which represents how many teammates were sent invites. Other events would rarely use this
num-teammates data, so it doesn’t make sense to add it to a defined event data taxonomy.
There are, however, four pieces of event data that are fairly ubiquitous to all of CircleCI’s events:
org,
view,
user, and
repo. This data typically represents a user taking an action on a page (view) under the context of an organization (org), and sometimes under the context of a specific project (repo). Given this global context for our event data, tracking these four properties seemed like the most logical starting point for a global event data schema.
Turning Thoughts into Code
The crux of my plan was to create an infrastructure that enforced the event naming schema I had come up with, as well as creating a base for a global event data schema.
To enforce this consistency, I used the plumatic schema library. For those unfamiliar with Schema: “a Schema is a Clojure(Script) data structure describing a data shape, which can be used to document and validate functions and data.” This validation functionality meant that I could use “schema checking” to ensure that the data passed into the analytics library was from a predefined set of good values.
Note 1: Because I am using the plumatic Schema library to enforce my event naming schema, ‘schema’ is a bit of an overloaded term in the following section. For clarity, I will refer to the library and the objects created by that library as proper nouns (Schema), and my event naming schema as a common noun (schema).
Note 2: The code examples in this post are not exact representations of our production code. I’ve done this for two reasons. First, to try and highlight the implementation of the concepts I’ve laid out, and second, to make it more accessible to non-Clojure developers. However, the code snippets are based on our open source frontend, so if you want to see the real thing, feel free to check it out!
Consistent Names
The first thing I used Schema to validate was a central repository of event names. As some of you are aware, creating an event naming schema is one thing, enforcing it is another.
To get started, I created a list of all the events that were currently being fired from within our web app. I then used Schema to validate the event names passed into the track function by adding the following code:
;; Below are the lists of our supported events. ;; Events should NOT be view-specific. ;; They should be view agnostic and include a view in the properties. ;; Add new events here and keep each list of event types sorted alphabetically (def supported-events #{:account-settings-clicked … :web-notifications-permissions-set}) ;; Create an enum from the set of supported events (def SupportedEvents (apply s/enum supported-events)) ;; Create an AnalyticsEvent which is a merge of the CoreAnalyticsEvent ;; and a dictionary with a key :event-type, whose value must be found in the ;; enum of SupportedEvents (def AnalyticsEvent (merge CoreAnalyticsEvent {:event-type SupportedEvents})) ;; Create a track function, which expects a dictionary (event-data) of the ;; schema defined by AnalyticsEvent. That way, if the argument passed to track ;; does not have a key :event-data, with a value found in the SupportedEvents enum, ;; it will throw an Exception and not fire the event. (defn track [event-data :- AnalyticsEvent] track stuff…)
Plumatic Schema ensures that a developer adding a new event will have to first manually add it to the set of supported events, or they’ll see errors in their JS console while testing. This enforcement accomplishes three things, it:
Describes the event-naming schema (
An additional, personal, benefit: as the owner of our analytics, this gives me a place to check that events outside the schema are not being added. Previously, events were scattered throughout the entire code base, so enumerating them was difficult. This list of event names has already allowed me to catch events outside the event naming schema.
Consistent Data
The next place I needed to ensure consistency was in the event data, since well chosen event data provides invaluable insight into the more granular details of user engagement.
Luckily for us at CircleCI, we use Om (a clojurescript wrapper on Facebook’s React framework) for our frontend web app. This means our app is powered by a large state map held in memory and updated by user interactions or responses from API calls. A major benefit of this structure is that at any given time, our app “knows” its operating context, whether that’s the current page, the current user, or a specific organization or repository.
To ensure this state information was always included in the event data of analytics calls, I did several things:
First, I extracted this information from the state in a consistent way. Second, I ensured that the state was always passed to the analytics function. Finally, I always added these keys to the event data before firing the track call to our third-party providers. With those goals in mind, I ended up with the following code:
;; Define an `AnalyticsEvent` schema, which requires an `:event-type` key and ;; a `:current-state` key. The `:event-type` value must come from our our enum of `supported-events` (described in the code block above). ;; The `:current-state` can be a map with any values (this is the app state). (def AnalyticsEvent {:event-type SupportedEvents :current-state {s/Any s/Any}) ;; Given the `current-state`, return a dictionary of the properties that we want ;; to track with every event. (defn- properties-to-track-from-state [current-state] "Get a map of the mutable properties we want to track out of the state. Also add a timestamp." {:user (get-in current-state state/user-login-path) :view (get-in current-state state/current-view-path) :repo (get-in current-state state/navigation-repo-path) :org (get-in current-state state/navigation-org-path)}) ;; A `track` function which takes a single argument `event-data`, a dictionary ;; in the shape described by the schema `AnalyticsEvent`. ;; If the input data is not in the correct shape, it throws an Exception. (defn track [event-data :- AnalyticsEvent] (let [{:keys [event-type current-state]} event-data] (segment/track-external-click event-type (properties-to-track-from-state current-state))))
As you can see by reading the code above, our track function takes a single argument
event-data, which will have a key
current-state (the app’s state when the event was fired). We then parse the important properties out of the state, and send that dictionary as the event’s data.
BUT: although this implementation ensures that each event fires with a consistent set of populated keys, it’s extremely rigid. What if the developer needs to add extra data, like an A/B test treatment? Or worse, what if there is an edge case where the auto-populated data is wrong?
Consider our dashboard page. While this page has neither an organization nor repository context (it shows all orgs and repos, but isn’t specific to any), it does have links that are specific to an organization or repository. For example, any link on the branch selector component on the left side of the page clearly has an associated organization and repository.
Because of these cases, we need to be able to modify the properties dictionary. I accomplished this by adding a new
properties argument to the
track function signature, which take precedence over the auto-generated map. Below is the updated code:
;; Same as the AnalyticsEvent above, but now has an optional key `properties` ;; `properties` is a map that has Clojure keywords as keys, and allows custom user-set values. (def AnalyticsEvent {:event-type (s/enum supported-api-response-events) :current-state {s/Any s/Any} (s/optional-key :properties) {s/Keyword s/Any}}) ;; This function gets the data we want to track automatically out of the `current-state`, ;; and then merges the `properties` passed in. Because we pass in `properties` as the second ;; argument to the `merge` call, the `properties` take precedence. ;; So, if `properties` has an `:org` key, its value will overwrite the value of `:org` returned from ;; `properties-to-track-from-state`. (defn- supplement-tracking-properties [{:keys [properties current-state]}] "Fill in any unsupplied property values with those supplied in the current app state." (-> current-state (properties-to-track-from-state) (merge properties))) ;; Same as the track call above, but can take a `properties` key in its input map. ;; This map of properties takes precedence over the map generated automatically ;; by parsing the app’s state. (defn track :default [event-data :- AnalyticsEvent] (let [{:keys [event-type properties current-state]} event-data] (segment/track-event event-type (supplement-tracking-properties {:properties properties :current-state current-state}))))
The code now allows a developer to add custom properties to the event data as needed. Also, in the case that the auto-added properties are wrong, it allows the developer to overwrite them with the correct values.
And That’s a Wrap!
Three third-party platforms and one massive event naming taxonomy overhaul later, we now have an analytics library that ensures some consistency for our data consumers, while allowing for flexibility and ease of use for our developers.
Looking Forward – Areas for Optimization
In the eight months since this analytics library was first launched it’s become the primary way we collect behavioral data. During this time, I’ve learned about what I built well and what I built poorly. I don’t think this would be an honest blog post if I didn’t address what were either mistakes or scaling issues, so here are some things that are top of mind eight months later.
Separation of Concerns
In our current architecture, there is no separation between what is part of the CircleCI Frontend Analytics and what is actually part of a portable Analytics Library. Although this isn’t a concern when firing events from a single source, as we scale our behavior analytics to multiple services, this infrastructure is crucial in validating those events and their data. Having a common library encourages best practices across different code bases.
A place we’ve already felt this pain is in our server side events. While the frontend is very well schematized, the server side didn’t have rigid schematization. The result is that, among similar events, there are different keys representing the same thing (ie:
org and
org-name on different events). Having a proper library would have allowed me to reuse the schema checking and prevent this from happening.
Scaling of the Event Names
The set of event names has been very successful so far but, as we add more and more events, that list is rapidly growing. At this point, I’m starting to wonder if the list is maintaining its original usefulness, or if there’s a better way to layer it for easier consumption.
If you look at the list, you’ll notice the event names are really just combinations of features and actions. So why have them together? Why not have a set of valid features, a set of valid actions, and then have the analytics library autogenerate the event name based on a feature/action combination passed to it by the client? That would be more scalable and make it harder to create event names that fall outside of the taxonomy. It’s something I’d like to try out in the future.
The Rest of the Event Data
We properly schematize four event data keys, but how about the rest? We run A/B tests, so those treatments should also auto populate the event data. The more data, the better, but also the more potential for divergence among our event data dictionaries.
So how can we ensure that as the complexity of our behavior analytics grows, the schema of our event data stays consistent? This is probably the hardest problem to solve, but one that will be important in scaling our use of behavioral data.
Waiting for Om Next
We are currently in the process of migrating our existing frontend from Om to Om Next (you can read about it here). One of the exciting things about a massive migration like this is it allows developers to address problems that might have slipped through the cracks in the first architected solution.
For example, when we moved to Om, CircleCI did not have data analysts or a growth team, and was less committed to utilizing data. Now that we are more data-dependent, analytics is receiving first class consideration in this migration, which will allow us to fix some issues we’re seeing with our current implementation.
Conclusion
No matter how thorough the plan and design, things will always be forgotten. This implementation of event taxonomy and schema has taken us from a company that didn’t prioritize data to one that runs on data-informed decisions. That said, as we scale, it has some cracks that are beginning to show. I’m looking forward to taking some time to fix these issues and, hopefully, writing another blog post to share future insights.
Interested in hearing more about this topic? RSVP for December Office Hours in San Francisco where Justin will present on all things data, Wednesday December 14th at the Heavybit Clubhouse. Space is limited. | https://circleci.com/blog/building-a-consistent-taxonomy-for-behavioral-analytics-with-amplitude-segment-schema-and-om/ | CC-MAIN-2019-13 | refinedweb | 3,175 | 50.36 |
Didn't I say that in the first place....?
Quote:
Switches have to be constant...so you could just use a series of ifs
Printable View
Didn't I say that in the first place....?
Quote:
Switches have to be constant...so you could just use a series of ifs
Also, I think statements like 0 || 1, 1 || 2, 2 || 3, etc. evaluate (as integers) to 1 if either operand is non-zero, and zero in the case 0 || 0, since || is a boolean and not an integer operator.
I.e., 2 || 3 evaluates to int(bool(2) || bool(3))
which evals to int(true || true)
which evals ti int(true)
which evals to 1
Code:
int main()
{
00401800 push ebp
00401801 mov ebp,esp
00401803 sub esp,8
int i = 0;
00401806 mov dword ptr [i],0
cin >> i;
0040180D lea eax,[i]
00401810 push eax
00401811 mov ecx,dword ptr [__imp_std::cin (40203Ch)]
00401817 call dword ptr [__imp_std::basic_istream<char,std::char_traits<char> >::operator>> (402038h)]
switch ( i )
0040181D mov ecx,dword ptr [i]
00401820 mov dword ptr [ebp-8],ecx
00401823 cmp dword ptr [ebp-8],0
00401827 je main+37h (401837h)
00401829 cmp dword ptr [ebp-8],1
0040182D je main+40h (401840h)
0040182F cmp dword ptr [ebp-8],2
00401833 je main+49h (401849h)
00401835 jmp main+50h (401850h)
{
case 0:
i = 10;
00401837 mov dword ptr [i],0Ah
break;
0040183E jmp main+50h (401850h)
case 1:
i = 11;
00401840 mov dword ptr [i],0Bh
break;
00401847 jmp main+50h (401850h)
case 2:
i = 12;
00401849 mov dword ptr [i],0Ch
break;
}
return 0;
00401850 xor eax,eax
}
Code:
int main()
{
00401800 push ebp
00401801 mov ebp,esp
00401803 push ecx
int i = 0;
00401804 mov dword ptr [i],0
cin >> i;
0040180B lea eax,[i]
0040180E push eax
0040180F mov ecx,dword ptr [__imp_std::cin (40203Ch)]
00401815 call dword ptr [__imp_std::basic_istream<char,std::char_traits<char> >::operator>> (402038h)]
if ( i == 0 )
0040181B cmp dword ptr [i],0
0040181F jne main+2Ah (40182Ah)
i = 10;
00401821 mov dword ptr [i],0Ah
00401828 jmp main+46h (401846h)
else if ( i == 1 )
0040182A cmp dword ptr [i],1
0040182E jne main+39h (401839h)
i = 11;
00401830 mov dword ptr [i],0Bh
00401837 jmp main+46h (401846h)
else if ( i == 2 )
00401839 cmp dword ptr [i],2
0040183D jne main+46h (401846h)
i = 12;
0040183F mov dword ptr [i],0Ch
return 0;
00401846 xor eax,eax
}
Maybe the assembly for the switch program came out like that since there are so few cases (0,1,2, and default).
Although I don't see how a switch could possibly not check each case? It would have to be psychic then. I can try adding more cases to see if that makes a difference...
One more thing that has me confused is why VC++ used a sub instruction on the 3rd line after main() in the switch version and a push in the if/else version? I'm not that great with assembly, so I don't have a clue why it's different.
Code:
switch(x)
{
case 0:
cout<<"X is either 0 or 1"<<endl;
break;
case 1:
cout<<"X is either 0 or 1"<<endl;
cout<<"X is either 1 or 2"<<endl;
break;
case 2:
cout<<"X is either 1 or 2"<<endl;
cout<<"X is either 2 or 3"<<endl;
break;
case 3:
cout<<"X is either 2 or 3"<<endl;
break;
}
Briefly, here's what Patterson & Hennessey (not the Hennessey & Patterson book!) has to say:
Maybe Microsoft just hates C++ and is sabotaging it to force you to use C#. :lolMaybe Microsoft just hates C++ and is sabotaging it to force you to use C#. :lolQuote:
Originally Posted by Computer Organization and Design: The Hardware / Software Interface
No seriously, in Visual Studio 2005 (Pro!) you'll get deprecation warnings when using STL algorithms. I'll give you an example of of copying an array using STL:
This produces the following warning:This produces the following warning:Code:
#include <algorithm> /* std::copy */
int main()
{
int A[] = {1,2,3,4,5,6,7,8,9,10};
int B[10];
std::copy(&A[0],&A[10],&B[0]);
return 0;
}
LMAO @ Microsoft telling me not to use the STL!LMAO @ Microsoft telling me not to use the STL!Code:
>------ Build started: Project: somecrap, Configuration: Debug Win32 ------
1>Compiling...
1>main.cpp
1>f:\apps\visual-studio\vc\include\xutility(2282) : warning C4996: 'std::_Copy_opt' was
1> declared deprecated
1> f:\apps\visual-studio\vc\include\xutility(2270) : see declaration of 'std::_Copy_opt'
1> Message: 'You have used a std:: construct that is not safe. See documentation on how to use
1> the Safe Standard C++ Library'
1> f:\code\visual\somecrap\somecrap\main.cpp(121) : see reference to function template
1> instantiation '_OutIt std::copy<int*__w64 ,int*__w64 >(_InIt,_InIt,_OutIt)' being compiled
1> with
1> [
1> _OutIt=int *__w64 ,
1> _InIt=int *__w64
1> ]
1>Linking...
1>Embedding manifest...
1>Build log was saved at ":\code\visual\somecrap\somcrap\Debug\BuildLog.htm"
1>somecrap - 0 error(s), 1 warning(s)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ========== | http://cboard.cprogramming.com/cplusplus-programming/105830-quick-question-concerning-switch-statements-2-print.html | CC-MAIN-2014-35 | refinedweb | 866 | 59.57 |
LimeSDR, gettin going
I had trouble installing the ppa the first time I tried about a month ago. It seemed to go through the second time around
Install LimeSuite using the ppa instructions for ubuntu. I have 16.04
lsusb shows OpenMoko as the device. Odd.
Ok. A capitalized command LimeSuiteGUI is insane. No commands are capitalized.
It brings up some spaceship of cryptic options.
Some of the stuff in the top menu bar seems good. Connecting, Programming, FFT, etc.
The commands
LimeUtil –info
LimeUtil –find
Lists a device. So that’s good. Also does updating?
Added a myriad RF ppa for gnuradio
sudo apt-get install gnuradio gnuradio-dev
Also installed gqrx. This is very useful for determining if the goddamn thing is working at all
Ok. GQRX was crashing on boot.
So was gnuradio when I tried playing with the osmocom source
GNU C++ version 5.4.0 20160609; Boost_105800; UHD_003.010.001.001-release
ImportError: /usr/lib/python2.7/dist-packages/gnuradio/uhd/_uhd_swig.x86_64-linux-gnu.so: undefined symbol: _ZN3uhd4usrp10multi_usrp7ALL_LOSB5cxx11E
so did python
from gnuradio import uhd
Eventually I apt get installed libuhd-dev which makes gqrx run now with an rtl-sdr
gqrx with line
soapy=0,driver=lime
should work but didn’t
Hmm another twist
Limesdr is power hungry
I may not have a usb3 port on my 2012 desktop insane as that sounds
so i need external power? I wonder if that is what the blinking led signifies
Trying to install in windows now. Maybe that will work better
Install PothosSDR
After running zadig can recognize an rtl-sdr in gqrx
Install the drivers as specified for limesdr.
I accidentally installed the x86 instead of the x64 drivers and needed to uninstall with deletion and then reinstall properly. Got error code 48
It appears to be working.
GQRX opens.
It has been months since I tried in ubuntu 16.04. Maybe things have gotten better.
ok. At first gqrx wouldn’t load but after fiddling with the sampling and bandwidth it does. I don’t get any FM signals with nothing attached to the Lime. That is either good or bad. It does appear to be receiving data at least though.
So I have not gotten gqrx to actually receive signals with limesdr, but gnuradio appears to be working to some degree. This graph plays audio on 101.5 although very crappily. I hope it just needs filtering (I think I should be low passing those resamplers. Also I probably shouldn’t be receiving on the middle of the band where the DC spike is). I doubled the resampler because a single resampler through an error for too much decimation. Is this standard procedure?
Useful gnuradio tutorials
Possibly useful blog series
ok. Next step is simple transmit and receive | https://www.philipzucker.com/limesdr-gettin-going/ | CC-MAIN-2021-39 | refinedweb | 467 | 68.36 |
Handling Null/Empty situations while working with Generic Collections in C#
These days many of us are taking the advantages of Generic Collections, while working in C#. In this short article, we will discuss a problem of Null or Empty value.
Abstract
These days many of us are taking the advantages of Generic Collections, while working in C#.
In this short article, we will discuss a problem of Null or Empty value.
Problem
It breaks the code or throws the exception in case collection countered with null or empty value.
In C# there is no such way to handle this. However, we have one method, which is of a String method String.IsNullOrEmpty() and it only works for strings.
Solution
If we talk about the solution,so, what will be the best solution. Can we use string method to check Null or Empty values?
Lets think and find-out a proper solution. We can achive this by creating an extension method:
First create a class, named it as 'CollectioncExtensionMethods'
1. Create an extension method for IEnumerable:
public static bool IsNullOrEmpty
{
return ((genericEnumerable == null) || (!genericEnumerable.Any()));
}
2. Create an extension method for ICollection:
public static bool IsNullOrEmpty
{
if (genericCollection == null)
{
return true;
}
return genericCollection.Count < 1;
}
Now what?
We just need to use these extension methods and we are done! Isn't it easy :)
1. For collections:
var serverDataList = new List
var result = serverDataList.IsNullOrEmpty();
2. For enumerable:
var serverData = new ServerDataRepository().GetAll();
var result = serverData.IsNullOrEmpty();
With the use of above, you need not to worry about Null or Empty things.
Closing Notes
In this short article, we discussed, how to handle the situation when our collection meet with 'Null' or 'Empty' siatuations. We overcome this
problem with the use of Extension Method.
(this IEnumerable genericEnumerable) (this ICollection genericCollection) ();
Hi
Gaurav
Good post this one . How to Testing Realtime for this method . for ex: Button click event can you update this? | http://www.dotnetspider.com/resources/46216-Handling-Null-Empty-situations-while-working-with-Generic-Collections-in-C.aspx | CC-MAIN-2018-09 | refinedweb | 321 | 59.3 |
# Android, Google and free content licenses. Who is to blame and what can be done?
#### The story of another ban.
Have you heard about bans on apps and developers in Google Play? This is just such a story. It’s also an attempt to collect similar cases into one place and offer some kind of plan of action to prevent Google’s unpredictable actions. It isn’t fair to be banned for the legal use of free material. Personally, I like the idea of content licenses such as [CC BY-SA](https://creativecommons.org/licenses/by-sa/4.0/), which permits any use, including commercial. Thanks to such licenses, we developers have websites like StackOverflow, where I’ve been elected to be the [moderator](https://ru.stackoverflow.com/users/17609/). Unfortunately, companies like Google don’t respect the ideas behind these licenses. Here's my story.
It all started out fine. Our app for Android was created back in 2014 and had been living quite a normal life on Google Play. The app was a client to a site with texts. Nothing special, but people liked it, especially the option to download texts to the device and read them without the Internet. The app took the texts from <http://scpfoundation.net/>. It’s a website for joint literary creativity within a common fictional universe, quite well-known in some circles. Originally it appeared in the US (<http://www.scp-wiki.net).Then> their community translated thousands of articles from English into over 10 other languages. For posterity, it is important that all the content on the sites, the original and the translated ones, is distributed under a free Creative [Commons Attribution-ShareAlike 3.0 License](http://creativecommons.org/licenses/by-sa/3.0/), which is located at the bottom of each page. This also applies to the logo of the website indicating the license, as seen here: <https://en.m.wikipedia.org/wiki/File:SCP_Foundation_> (emblem).svg on Wikipedia. The license permits any use of the material, including for commercial purposes, requiring only the indication of authorship and preservation of the original license in derivative works. This information, the source of the texts with license indication, was in both the description of the apps and in the apps themselves.
For several years everything was running normally. Initially, it was decided to make all the features of the app free and to provide the possibility of voluntary donations through in-app subscriptions. However, it hardly brought in any profit at all. As a result, it was decided to monetize the most popular features of the app, compensating for the inconvenience to users by opening the [source code](https://github.com/mohaxspb/ScpFoundationCore). We also started to release versions for languages other than Russian. The original Russian version of the app even got into the top 10 of the "news and magazines" category of Google Play. While working on this project, I sort of taught myself programming, I tried new things, I made mistakes and I learned a lot. The important thing for this article is the development process. It was necessary to parse HTML on the server and then send it through API to all the sites with translations, instead of doing a separate app for each language with parsing on the client. I know this now, but 5 years ago I had very little idea of how to write servers. At the time, it didn't make much sense to me. My thinking was that if it ain’t broke, don’t fix it. Now I write API and plan to go onto iOS and hopefully one day return to Google Play.
Then the warning lights started flashing, one after another. First Google Play began to reject new apps for copyright infringement. It was the same code, but for a site in a different language. I believe the new versions started to get rejected in the summer of 2017. However, each time it was possible to solve the issue by contacting their technical support service, which even suggested a [special form](https://support.google.com/googleplay/android-developer/answer/6320428?hl=en), in which you can notify Google of the release of a new app by sending them any files needed. In my case, all I had to do was provide a link to the website and state that there was a license at the bottom that allowed the use of the content. After that, Google sent a letter saying that everything was okay. We were free to spread it and they had saved our information. But apps also got deleted (I’ll talk later about the difference between removal and blocking).They’d be deleted for things like mentioning the names of other apps in the description, in particular, the name of one of the games based on the site. In theory, the license should allow it. But okay, I'm not a lawyer, maybe Google was right, and we just had to clean up what they didn’t like and move on. But then they started removing apps due to the lack of privacy policy and processing of personal data. We were not alone in this situation. The problem was extensive. It seemed to have started around 2018.The network had several generators with such agreements, which were just enough to put on the website and add a link to the description of the app. Then there was Appodeal, where the app was removed due to problems in their SDK. But my mistake was that I had used the beta version, and Appodeal honestly warned about this problem the day before removal. I just had to update the SDK to the latest stable version, but I didn’t manage to up it in time.
Then things started going wrong with Google Play’s app checks. I tried to release an update with a new version of Appodeal SDK. It was rejected for the same reason. On reflection, I decided that it was easier to just remove SDK, replacing its functionality (it was used for advertising with rewards) with similar functions from AdMob. Do you think it helped? I don’t think so! This update was also rejected. But I'm a programmer. I'm cunning. I bypassed this bug on Google Play simply and gracefully. I posted an update in the form of an alpha version and raised it to the working version. And everything was fine. For a while.
Then there was the time that our apps were removed because of violations of their advertising rules. As always, no examples, just a link to the voluminous rules for developers. After talking with their technical support service, I managed to find out that Google saw a problem with the links to my other apps in Google Play, which was just a list of similar apps in other languages. I mean, come on, I can’t give links to my own apps on the same platform? Okay Google, if you want it that bad. Here you go. I released an update with "Ad " over each button-link. Problem solved.
Then I got a letter stating, "After a recent review, SCP Foundation France On/Offline database fr (ru.dante.scpfoundation.fr) has been removed from Google Play." The French version of the app got banned. The reason given was, of all things, "Violation of Sexually Explicit Content policy." And again, nothing was said about what exactly Google had found objectionable. Perhaps, if you search really thoroughly amongst the thousands of texts, you might have found a couple of provocative images. Well, I didn’t lose heart. Google probably knows what it's doing and I'm the one to blame. I put up with the loss of the app. It had a few users, but its loss didn’t set us back too much. I began to update the rest of the apps, disabling of all images. At the same time, I began to look for information on app bans on the Internet. And then I started to suspect that this was not an accident. I wasn’t the only one in this situation. It turned out that the network has many examples of app bans and even accounts bans.
Let’s digress and talk about the moderation system in Google Play. There are two or three types of sanctions against apps, depending on what you count. First, your app can be "Removed." In this case, the app will not be available for search and download on Google Play, but you have access to it in the developer console and can release an update with fixes. This is not considered a serious violation and does not affect the status of the account. A subset of this is “Update Rejection.” In this case, the app is available for search and installation through Google Play, however, you should make changes to the planned update, as it violates something — something in the current form. Like in the first case, it does not affect the status of the account and nothing threatens you except for spoiling the mood and having some extra work to do. The last type of sanction is really bad. It’s called "Suspended" and if you see a letter from Google with this word, prepare for the worst. The app isn’t just removed from Google Play, it’s removed permanently, with a ban on updating and even viewing the description, statistics and reviews in the developer console. The scary thing here isn’t that Google makes you release a new version with a new package and re-recruit users, reviews, paying audience and explain to the users of the deleted version why everything stopped working. The scary thing is that you’ve got a label on you and the timer has started. Now you are an unreliable developer. Some people say that strikes get "rotten" after about six months. If get two more "Suspended " apps, you automatically cease to be an independent Android developer forever. Google [explicitly prohibits](https://support.google.com/googleplay/android-developer/answer/9023898?hl=en) the creation of a new developer account after the ban of the existing one and, given the market share of Google Play, the ban deprives the developer of a lot market access.
Okay, back to the main plot. About three weeks later after the aforementioned app bans, I was at another meetup listening to some reports. And then I get two messages from Google. That's right, two more apps were banned. But this time, the two main ones, the Russian and the English versions. My first thought was, "Damn, I didn’t have time to release the update with the pictures disabled." But that wasn’t the reason. Here is a quote from the letter: "After review, SCP Foundation EN Database On / Offline, ru.dante.scpfoundation.eng, has been suspended and removed from Google Play as a strike policy because it violates the impersonation policy." In other words, Google decided that I was impersonating another person and using someone else's brand without permission. And here's the weird thing, all apps with "SCP Foundation" in their name were removed from the store. Except the ones I posted later, notifying Google of a free content license through the form I mentioned above. And not only were my apps removed, but other developers' apps were as well, about ten or more. I didn’t count them at the time, so I don’t know how many were removed and how many developers discovered that years of their work were thrown into a landfill by Google and their robots. Now you can’t find any apps with "SCP Foundation" in their name in Google Play, which implies that none of them managed to resolve the situation with Google.
In this case, I immediately issued appeals for both apps. I wrote that the apps use content under a free license and gave them links to the site where this is clearly written. However, in response, they wrote the following:
> For example, your app currently creates an unclear affiliation with SCP Foundation (<http://www.scp-wiki.net/>).
>
> If you are authorized by the site creator/content owner to redistribute the content in this manner, please reply this mail with verifiable documentation of content with the following examples: distribution agreement, authorization contract, or website domain ownership (PDF file).
>
> Kindly note that you may ask the content owner to reply for this email from a verifiable domain (@scpwiki.org) indicating your rights to use their brand asset and content.
That means that they want me to provide them with documents confirming my right to use the content and the brand, as I understand it, both the name and the icon. They also needed the documents in the form of a response to this letter from the mail server of the site. In addition, for the Russian and English versions, they had two different domains in mind, one of which is a mirror of the second, although the Russian version did not take anything at all from these sites. They didn’t care about the presence of a free license for content that allows its use, as they never even mentioning it. Although in other apps it was enough, going by the fact that other similar apps have not been removed. Okay Google, I tried to comply with this requirement of yours. I went on scp-wiki.net’s private messaging system(like other sites with translations, it works on the Wikidot engine) and I wrote to other local administrators dealing with issues related to their content licenses. In the “Help” section of the site, it was written that they answer within a day. The first admin didn't answer me, I wrote the other one, then another, then another. I was answered by deathly silence. But I didn’t give up. Although the first panic attacks began to occur, I still hoped for a solution to the problem within a week or two. Thinking about how many subscriptions to users would be canceled in this time, I browsed the net looking for information on how to make a document that the site administrators can send to Google. It looked like [this](https://scpfoundation.app/scp/reader/Authorization%20contract.pdf). Meanwhile, I wrote a newsletter to our users through FCM, describing the situation. With that, I built a simple [page on the site](https://scpfoundation.app/scp/gp-problem/).
One more digression. Let me tell you about the recent scandal in the SCP Foundation community related to content licensing, copyrights, threats, revelations and other things. I don’t know if this stems from blocking apps. I’ll just give you a list of facts and you can draw your own conclusions. It went more or less like this:
1. An individual registered the [trademark](https://onlinepatent.ru/trademarks/661748/) (hereinafter TM) on the name and logo of "SCP Foundation"
2. Using this document, he began to remove videos from YouTube, communities in VK selling attributes, to demand deductions from sales.
3. The victims appealed to the administrators of the Russian website.
4. Admins released a [long text](https://vk.com/@scpfoundation-oficialnaya-poziciya-scp-foundation-po-otnosheniu-k-proektu), in both Russian and English, explaining the situation and the rights of content use under a free license.
I know this individual. We’d worked together for some time, mutually advertising his artbooks and our app. But at one point we had a misunderstanding about the details of our agreement which resulted in a rather unpleasant conversation. Fortunately, we managed to resolve it. However during the conversation there were [direct threats](https://vk.com/@scp_foundation_app-po-povodu-situacii-s-artscp) to remove the apps from the Google store due to the use of the TM.
This case was in December 2018. And blocking all apps with "SCP Foundation" in their name occurred at the end of March. After two weeks, my developer account was blocked. Apparently, this was due to the fact that I had not received a response from the administrators of the English site and already had had three strikes on the account. The next day, the owner of the TM [presented](https://vk.com/wall-98801766_20601) his own analogue version of our app. Everything seemed to check out and the reason for the block was clear. However, in a personal conversation with the owner of the TM, he denied my assumptions about his involvement and announced his intention to withdraw the TM. Google also refused to confirm my suspicions, ignoring my questions to technical support about any claims of copyright holders and the name and logo of the apps, insisting on the connection with the original site. You can decide if there is any connection.
**Update:** After I started writing this article, the situation with the TM has worsened. He began to [block communities](https://vk.com/scpfanpage?w=wall-53433582_114082) in VK with its help and [withdrew board games](https://www.mirf.ru/news/osnovatel-artscp-prigrozil-zakryt-soobschestva-po-scp-prodolzhayuschie-proyavlyat-negativ-k-proektu) from the market. The administrators of the Russian site [released a post](https://vk.com/wall-53433582_113247) explaining the situation and reporting that the court documents for the app were almost ready. They were also supported by the original website, which started [collecting donations](https://www.reddit.com/r/SCP/comments/dvbktk/the_scp_wiki_is_under_attack/) for legal expenses. As a result, the site administrators [wrote](https://vk.com/scpfanpage?w=wall-53433582_117344) a statement to the Russian Federal Antimonopoly Service. It’s also worth mentioning the position of the technical support service of VK: they completely ignored any indication of the license and ban on the communities.
But let’s get back to Google. At some point I realized that there was only one way to win back the account and apps and that was to contact the admins of the original site and ask them to send an email with the ready-made document. Nothing could be easier, right? Initially, I had my doubts. Going by what I had known about the site and its administration system, they might not have their own mail server or even a desire to help me. But those were only my fears. And the task was so simple. I just had to contact them. But that turned out to be the biggest problem. No one answered my personal messages. And when one of the admins did finally answer, he said that he was busy and would answer later. Four (!) months later, I managed to get through to the administration, which said that I was not alone in this predicament. They have tried to help others with this and failed. Google just doesn't want to hear them. And they do not have their own mail server, so there is no technical possibility to send the letter I need. So the circle has been closed.
#### Am I the only one?
Is this an isolated case? As I’ve mentioned above, no, it’s not. You can see for yourself by searching the web or visiting my website (<https://dont-play-with-google.com/>). I created it specifically to collect articles about cases of blocking apps and accounts in Google Play. Some of the articles on the site were translated into Russian, English and French with the help of my friends. Keep in mind that we are not professional translators and many articles are translated automatically and only slightly corrected. It is also possible to add new articles and translations into other languages. If you have links to other blocking cases, please, add them to the site as people should know. If you want to help the site, you can translate articles, correct typos or just code. The site consists of server and client sections. BackEnd is made on Spring (Gradle, Kotlin, Postgresql): <https://github.com/mohaxspb/dont-play-with-gp-api>. FrontEnd — Angular (TypeScript): <https://github.com/mohaxspb/dont-play-with-gp-front>. Don’t judge the code too harshly as I specialize on Android. It's funny that in the process of creating the site I even had to edit the Angular compiler (<https://github.com/angular/angular/pull/32760>). PullRequests are welcomed on any subject either bugs or new opportunities. The list of tasks for the site’s functionality can be found in [Trello](https://trello.com/b/QLJ7W75S/dont-play-with-google-play).
Here are just a few examples of absurd app and account bans:
* Bans of apps for copyright, such as mentioning the brand in the text of the description, and the subsequent ban of the account for connection with another account. Google won’t even explain and it’s impossible to restore anything. The account was used for disabled children's apps. (<https://dont-play-with-google.com/#/article/49>)
* Sometimes accounts are banned just by accident. They apologize and restore it. Obviously there are robots involved. (<https://dont-play-with-google.com/#/article/54>)
* First the app, then the account was banned. Robots answer in the technical support service, but no details are given. After a post on Medium, a real person from Google saw the problem and the account was restored. Although they refused to reveal the reason for the ban. Take-home message: only the hype in the mass media helps in such situations. <https://dont-play-with-google.com/#/article/52>
* The developer changed the name of his account to "Android app store" and got banned in just four seconds. Technical support reacted to his appeal. As always, no explanation. On the other channel they claimed that the name was legal. Take-home message: you won’t be given any warnings. You will be banned by bots and there’s nothing you can do about it. <https://dont-play-with-google.com/#/article/66>
+ An account was banned for "Previous violations," even though there weren’t any. Technical support kept silent as usual. <https://dont-play-with-google.com/#/article/65>
* An account for a company was banned for connection with another account. As it turned out, a colleague of this article’s author was banned for intellectual property rights. For this link, the author was banned, as was the company’s account where he worked. Once again, hype seemed to help to restore the account for the company, but not for the author or his colleagues. <https://dont-play-with-google.com/#/article/64>
* Banning multiple apps for being "Misleading". Well, just ban the account once. Appeals led to nothing. However, after attention in the media, Google changed its mind, withdrew all claims and restored the apps with the account. Take-home message: only public complaint on the net works, and even the innocent can be banned. <https://dont-play-with-google.com/#/article/67>
* Apps are banned for violation of the TM. (<https://habr.com/ru/post/435702/>). Despite the fact that actually everything is legal under the law (<https://dont-play-with-google.com/#/article/14>).
* There are many more examples, but I’m not here to list them all.
In all these cases, the bans occur suddenly. The developer doesn’t receive any warnings. In many cases, one can avoid getting their ban apps or accounts banned simply by changing one line in the name of the app (as in my case) or the name of the account (as in a case from the list above). However, instead of a warning with a proposal to correct the violation, you’re just banned. And technical support either doesn’t want to help you or demands unnecessary documents. I even had a case in which an automatic email from Google about a problem with the app contained broken links. Also, there are never any specifics in automatic letters, only the indication of the violated point of very vague rules and a reference to these rules. To at least get some hint to the cause of the ban, you need to contact the technical support service. And it doesn’t always give any details, like in the case of the ban of the associated account, thereby depriving you of any opportunity to do something. Here’s [another example](https://dont-play-with-google.com/#/article/55). A person got three bans on their app, all automatic. The first two bans were later canceled by technical support due to lack of violations, but the third ban appears not to be canceled.
The worst part is that there is absolutely no way to talk to a real person, only through forms with a promise of a response by mail within 72 hours. And the mail is rumored to be answered by outsourcers from India. I've no problem with that, but as for the quality of the technical support service, I think I’ve already said enough. Compare this with Google Ads technical support. They’re on the phone, in your native language, and they’ll tell you that you need to put a comma in the text and lower the age rating. And they’ll call back from a personal mobile number to check up on you. "Is your ad okay now?" I had the opportunity to compare the Google Play service and Google Ads. It's like night and day. But how did it happen? And does Google know about this issue?
Of course they do. They even have special webinars for developers to clarify the details of the moderation system, complete with tips on how to avoid getting banned. And they conduct them in the developer’s native language. And they [announce](https://habr.com/ru/company/google/blog/445180/) these webinars on major IT resources like habr.com, the largest Russian-language IT resource. However, if you look at the recording of the webinar, you’ll find that it was just someone reading a printout of the info available in Google Help. The Q&A was also just people reading from papers, with pre-prepared answers for prepared questions. It was all just to check a box. Google does not have any real desire to help developers. The video of the webinar has already been removed. It was [here](https://www.youtube.com/watch?v=8yKI-igsWVE). There was also a chat in which dozens of developers, including me, tried to ask questions about blocks on our accounts and apps. We were answered with links to their rules. We were so upset, we tried to organize a Telegram chat. If you are interested in talking to colleagues about similar unfortunate events, welcome to our chat: <https://t.me/android_developers_ban>.
On the other hand, in local markets, Google is trying to convince everyone how amazingly organized they are at helping developers launch, distributing and support apps. For example, you read about how well everything is organized. Google Play is constantly in touch, always willing to help with advice on any matter. Help with promotion, help in general, whatever you need. It’s not just any old technical support, it’s a [waking dream](https://dont-play-with-google.com/#/article/33). But when people went to the comments section and asked how to get this access in Google Play, they were all ignored. Obviously, it was just a promotional article designed to draw developers into the store.
#### Who's to blame?
How did it happen that the app store, which once allowed anyone put up any app of any quality without being afraid of it getting banned, has now turned into a place where you’re terrified to post an update or even have the app on your account. Some say that bots check and can ban even unpublished apps. And you can’t delete them if someone has the app installed. There are several reasons for that, as far as I understand:
* First there’s the maturing of the market. New major players interested in stable working moderation have come about. For example, to promptly remove forging apps. And it’s easier, and more importantly, cheaper, to have bots do it.
* For years, when most apps were downloaded in the store, it was simply impossible to manually check in a reasonable time and for reasonable pay. New apps and updates are published by the thousands every day.
* The abundance of users and the monopoly on them, together with the lack of rigid moderation used to attract a lot of dubious personalities to the store, resulting in viruses, spyware and so on. And it’s necessary to be protected from that stuff, and to constantly improve and protect the system.
* Also, a number of people abused the capabilities of the Google Play API. Here’s an [example](https://dont-play-with-google.com/#/article/60). A couple of people wrote a code that generates copies of simplistic games, changing only the name and pictures. The store was inundated with their games. They are not the only ones doing it because it’s cost-effective.
* Finally, there’s pressure from state regulators to comply with a variety of laws regarding intellectual property rights, personal data and other things.
My friends told me about companies involved in the creation of apps that just embed WebView, in order to redirect advertising traffic to users. Their only goal is to push their app in the store, one way or another, and earn at least some money. If the account is blocked, they simply switch to another one. They have a lot of tools to hide their digital tracks. They can avoid bans for linked accounts and there’s even a market for selling developer accounts formed around them. It’s clear that such abuses can be fought only with the help of robots. But the wrongdoers don’t get punished, they just buy a new account for a few dollars. While ordinary developers suffer from friendly fire and lose their apps forever. Their apps are often their only source of income. But maybe these are unavoidable losses. It’s just the unavoidable result of the reliable security we enjoy on Google Play. Unfortunately, no. There’s constantly news about dozens of new malwares, viruses and other things popping up. Google can't keep users or developers safe.
What conclusion can be drawn from all this? I’m sorry to say it, especially after so many years, but my conclusion seems to be that you can no longer consider Google Play to be a reliable platform for publishing apps. Or even as a platform where you can count on a reliable source of income. And the worst part is that there are simply no alternatives, unless you publish in China where Google is banned. And after your account is deleted, you might not be able to continue earning ad revenue while you're trying to recover it; unless, of course, as per Google’s advice, you use their advertising SDK from AdMob. As soon as your app and/or account is banned, advertising in AdMob immediately becomes disabled. And it doesn't work the other way around. If you manage to restore the app/account you will have to write to AdMob technical support to restore the advertising display. You can use other advertising SDKs, but with new risks. I’ve already described a case of the failure in Google Play due to the availability of the SDK from Appodeal. The latter, by the way, also requires an account in AdMob and an app in Google Play and will seriously limit the display of ads or disable them altogether in case of problems with Google.
As you can see, if you are going to build a serious business with distribution through Google Play, you need to be prepared for the fact that you might suddenly lose it all and your only hope is a possible hype in the media. Or you need to be a company the size of Facebook, then you will have the phone number of a manager at Google and you’ll be able to solve any problem quickly and easily. And you won’t be banned for the nude photos of your app users which they placed there themselves. But if you are not Facebook, you’ll just be [banned](https://magazine.artstation.com/2018/12/happened-artstation-android-app/), because you violated the rules. And in this case, the developers managed to [restore](https://magazine.artstation.com/2019/03/artstation-app-back/) the app. After 3 months! But we all know that such a situation simply doesn’t happen to large companies. As indicated in the first link, the ban was for a picture which was considered too racy for Google Play. However, the developers found the exact same picture in Twitch and other big apps. That means the rules are not only vague, but also do not apply to everyone. Some developers are “more equal” than others.
So, can we improve the situation? I don’t think we can. Google is a commercial company and their goal is to make money. There's nothing wrong with that, of course. But it means that the company will try to reduce costs and increase profits. And try to avoid lawsuits. As a result, it is easier and cheaper for them to ban apps and developers automatically than to hire a huge number of specialists who will personally understand the nuances and view each app, especially since, most likely, a very small percentage of developers and apps give the bulk of the revenue to Google Play. I have not seen detailed statistics on this topic, but I think it is unlikely that the situation here is very different from the situation with another Google service: YouTube. According to this [study](https://dont-play-with-google.com/#/article/75) from Pex only 0.64% of videos get more than 100,000 views. And those videos generate 81.6% of all platform views. And since videos with a small number of views do not meet the criteria for enabling monetization, YouTube can remove 99% of all videos with almost no loss in profits and significantly reducing the cost of infrastructure for their storage. Moreover, at the time of writing YouTube plans to include a clause in [their rules](https://www.youtube.com/t/terms?preview=20191210%20%20%20#main) on December 10th, 2019, in which a user can be banned if he does not make a profit. "YouTube may terminate your access to or access through your Google account to all or part of the Service if it considers that providing you with access to the Service no longer makes commercial sense." I’m sure the same situation exists in Google Play. This way they can ban 99% of developers and apps and even increase profits.
And don’t even dream that the situation with technical support is better on YouTube. It’s the same story. Automatic bans, unsubscribed by bots, inability to talk to a real tech support person. Unless of course you’re one of the few who rake in significant profits for the service.
#### What can be done?
Is there any way to fix the situation? I'm not sure that's possible. Because it’s more profitable for Google to leave the situation as it is than to spend huge amounts on a solution. It seems that we developers affected by Google bots can only write articles about it over and over again, hoping that someone at Google will read and manually restore our app or account. I think you shouldn’t discount the thought that developers could unite and act as a united front to change the situation. People are wired this way. They think about such solutions when so many people face the same problem. Since I began to develop for Android, I had read articles about bans, but of course, I never thought that this would happen to me. I'm not a spammer. I don’t write viruses and in general, I am always ready to wait on Google hand and foot. And I didn’t think I would lose everything because I didn’t change one word in the name of an app, especially since the Creative Commons Attribution-ShareAlike 3.0 Unported License permits it, as far as I understand. At least I successfully uploaded two of my ten apps to the Amazon store and they didn't have any questions about them.
Here’s a list of what I think any developer should do to minimize the damage from apps and accounts getting blocked. Not to avoid the damage, but to reduce it, because no one will warn you that the Google algorithm has found a problem.
* Don’t count on the fact that upon publishing and developing the app in Google Play, you will be able to stay there safely for a long time, living on income from advertising and sales. Sooner or later, you may get banned.
* Don’t use ads from AdMob. Or use it together with other SDKs that will not stop displaying ads when you’re banned. You should be able to switch the source of advertising from the server.
* You should also plan to launch your app in places other than Google Play. You need to do this anyway if you plan to launch in places like China.
* If you offer in-app purchases, you need to use the same code in different stores. An imperfect [example](https://github.com/mohaxspb/ScpFoundationCore/blob/develop/core/src/main/java/ru/kuchanov/scpcore/monetization/util/InappPurchaseUtil.kt) can be found in the source code of my own app. Different builds for different SDK embedded payments.
* You need to create a website for your app so that you can direct the user to another store when Google bans you. There you will have to give a very long and complex instruction on how to install the app because Google strongly interferes with other stores on Android. Just think about how many problems had to be solved to uninstall the app from Google Play in the instructions [here](https://scpfoundation.app/). The Google Play app directly prohibits uninstalling it, which kills all competition.
* You need to build an in-app notification system in case of a ban. For example, you could use push notifications. I did that, but it didn’t work perfectly. After the ban, users with Android version 7 and above did not receive notifications. Keep this code up to date. And pray that Google doesn’t start to ban projects in Firebase, because alternative ways to send push notifications were actually squeezed out of the market after Google banned background processes in Android version 8 and above. They only allow push notifications in Firebase.
* Never post apps that you’re not going to use for earning money. This mainly applies to beginners as you risk getting banned even for an unpublished app project. Don’t risk it.
* Do not expect that the use of content under a free license will protect you. Google may still require you to confirm your rights to use the content. And you may have no one to get this confirmation from.
* If you’re an EU citizen, you can hope that the legislators will bring order to the market. [Here is](https://venturebeat.com/2019/04/17/european-parliament-passes-online-platform-rules-placing-new-limits-on-amazon-and-google/) a draft law obliging sites to provide comprehensive information in case of a ban.
Also, I would add to this list my thoughts on how the situation could be improved by creating competition. A while back Google was obliged to provide a choice of search engine at the first Android launch. It would be logical to oblige Google to also offer a choice of app store. Competition could emerge this way and, perhaps, Google would start to provide technical support on the phone (like in Russia, where Google has a strong competitor, Yandex) and stop automatic bans and let bots only be used for giving advice to moderators. Many problems could also be solved by changing the practice of banning without warning, so that the developer has the opportunity to fix something. Sometimes it is enough to change one word in the title to stay in good standing with the Google Play moderation system.
I don’t really believe I can do anything alone to improve the situation, but I won’t forgive myself if I didn’t try something, such as writing this article. Not expecting much, I sent an appeal to the FAS, the Russian Federal Antimonopoly Service. Please note, I am not a lawyer or a writer. I'm a programmer. So my application must be rather informal and generally naive, because it seems only the state can protect developers from Google.
**Statement of violation of the Antimonopoly legislation of the Russian Federation.**From Surname Name Patronymic, living at the address City, street Street, h. HOUSE, b. BUILDING, apt. APARTMENT.
Antitrust infringing company: "Google LLC", address: 1600 Amphitheatre Parkway, Mountain View, CA 94043, USA.
Google violates the Federal law "on protection of competition" of 26.07.2006 N 135-FZ. Articles 10.1 and 14.1 are violated.
The violation of article 10.1 (Prohibition on abuse of dominant position by an economic entity) is the failure to provide a choice of an app store for the Android platform when the device was first launched on this platform, as well as the non-admission of other app stores in the Google app store (Google Play app).
Violation of article 14.1 (Prohibition of unfair competition by discrediting) is the need on some versions of the Android operating system to disable Play Protection — a feature of the Google Play app store, which prohibits the installation of apps not from the "Google Play" store, allegedly because they are unsafe. Thus, Google misleads the consumer by pointing out the" insecurity" of apps from other app stores.
According to the above mentioned, I ask you to oblige Google to provide when you first run the device on Android, the choice of app store (as it is now provided for search engines) and not to prevent the installation of apps from other app stores using the "Play Protection."
In addition, it is necessary to prohibit the blocking of apps and developer accounts without prior notice of violations of any rules of the app store and the ability to correct these violations. Such warnings should be accompanied by comprehensive and unambiguous information about the problem and ways to a solution. At the present time the Google Play app store has a "presumption of guilt" of the developer, obliging them to prove their innocence in cases of blocking their account and/or app.
At the moment the situation of monopolization of the Android apps market prevents building a digital economy in Russia by means of unfair competition in this market, and also by the ability to block all apps and developer accounts without explanation and prior notice. As a result, the market cannot form competition and small and medium-sized businesses can not develop steadily in the market of Android apps due to the possibility of losing their income by being blocked without warning or explanation from the Google Play store, which occupies a dominant position in the Android app market.
If you are also not satisfied with the current situation, please do the same. I am sure that things will improve if the app market on Android gets healthy competition between stores.
#### Appeal to Google.
And finally, I would like to try to reach out to Google (in case someone from the company reads this article) and ask them to do something. For example:
* Restore all the apps deleted in March 2019 (approximately 25-26) for all developers (including mine, with packages `ru.dante.scpfoundation` and `ru.dante.scpfoundation.eng` ) which had `SCP Foundation` in the name, because the use of the name and logo does not violate the terms of the Creative Commons Attribution-ShareAlike 3.0 License (<http://creativecommons.org/licenses/by-sa/3.0/>), and the site administration (<http://www.scp-wiki.net/>) and (<http://scpwiki.org>) from which there was a redirect not working at the time of writing and has no mail server to send a letter with permission to use what is already allowed. License information is available on all pages of this site, as well as all other affiliated sites with translations into other languages. The license is listed in the bottom of the site. Here's my appeal number for both apps: 3-7609000025842
* Restore all developer accounts which, like my mine, were blocked as a result of blocking the apps that have `SCP Foundation ' in the name, because this is not a violation.
* Allow developers to change the names of apps if Google believes that they are violating something, instead of banning apps and accounts immediately and without warning.
* Stop automatic app bans, give at least a couple of days to make simple changes to correct violations, if any. As I’ve said, in my case it was enough to remove one word from the title.
* Add the ability to specify the rights to the content, name and logo of apps when they are published, instead of subsequent checks by an unknown algorithm. Consider the rights granted by free licenses, including, for example, the [Creative Commons Attribution-ShareAlike 3.0 License](http://creativecommons.org/licenses/by-sa/3.0/)
* Provide better technical support. If the developer needs to make an additional monthly or annual payment, instead of $25 for creating an account, this is a small price for peace of mind and reliability.
I would be very happy if Google restored my apps and account, because I’ve invested a lot of work in them for more than five years. I hope at least someone will hear me. I hope that one day Google will be able to configure the moderation system so that developers will be safe from the situation when one day they find that themselves thrown out of the market by some program by a ridiculous mistake. | https://habr.com/ru/post/479336/ | null | null | 7,722 | 64.71 |
Results 1 to 5 of 5
open() file length limit? Need to set?.
- Join Date
- Aug 2011
- 16
Hi
With the size limit you can specify, how much data you want to write into the file in byte.
Code:
write(pointer, "foobar", 1); //result will be only f in the file write(pointer, "foobar", sizeof("foobar")); //result will be foobar in the file
Code:
#include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> void main(void) { int val, pointer; pointer = open("test", O_WRONLY); write(pointer, "foobar", sizeof("foobar")); close(pointer); } //remember to create an empty test file first (echo "" >> test)
Haze
I don't know what size limit you're talking about. You open() the file, and then just write() to it: the file will be resized as necessary. In particular, the system keeps track of the offset into a file. If you open a new file and write three bytes to it, the offset is now 3. You can also set the offset manually by using lseek(). Anytime you write starting at a particular offset, the file on disk will be modified as necessary to accept that offset.
Haze's code shows how to combine open() and write(). The only thing that I'll say about that code is that you can use the O_CREAT flag to open() to create the file if it doesn't already exist.
What size limit are you talking about? Filesystems may impose file size limits (for instance, FAT32 is well known for not supporting files over 4GB), but this is something different.
- Join Date
- Aug 2011
- 16
@legendbb
What about just trying it and give us the result.
Br
Haze
Great thanks to you for working example code and in detailed explanation.
File size must be preset when working with mmap()
Found a good reference: gnu.org/s/hello/manual/libc/File-Size.html
Last edited by legendbb; 09-02-2011 at 04:34 PM. Reason: solved | http://www.linuxforums.org/forum/programming-scripting/182276-open-file-length-limit-need-set.html | CC-MAIN-2017-22 | refinedweb | 329 | 73.98 |
In this post I will demonstrates how Silverlight 1.1 can received and display data from a web service using the controls from ASP.NET Futures package.
The Microsoft ASP.NET Futures July 2007 release contains an early developer preview of features providing new functionality for ASP.NET and Silverlight.
There are two new ASP.NET server controls: a Media server control for integrating media sources into your web application, such as audio (WMA) and video (WMV), and a XAML server control that enables you to reference your own XAML and associated JavaScript files.
After installing the Microsoft ASP.NET Futures July 2007, open Visual Studio 2008, and create new project of type ASP.NET Ajax Futures Web Application or of type ASP.NET Futures Ajax Web Site.
Add new service which the Silverlight control can get the data from. Lets call it HelloService.asmx.
To allow this web service to be called from script using ASP.NET Ajax, uncomment the ScriptService attribute which allowed us to interact with the Xaml object that is going to display the result from this service.
The following sample code describes the web service:
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class HelloService : System.Web.Services.WebService
{
[WebMethod]
public String HelloWorld(String name)
{
return String.Format("Hello World {0}", name);
}
}
To display the result from the web service inside a Silverlight control, lets add Silveright Project called SilverlightControlDisplay as showing in the following image:
Add to Page.Xaml file a background color and a text block as showing in the following sample code:
<Canvas x:Name="parentCanvas"
xmlns=""
xmlns:x=""
Loaded="Page_Loaded"
x:
<Canvas.Background>
<LinearGradientBrush>
<GradientStop Color="Blue" Offset="0" />
<GradientStop Color="Orange" Offset="1" />
</LinearGradientBrush>
</Canvas.Background>
<TextBlock
x:Name="tb"
Text="Hello World!"
FontSize="36"
Canvas.Left="10"
Canvas.
</Canvas>
Add a Web Reference inside the Silverlight Project to the service HelloService.asmx:
Add MouseLeftButtonDown event lestener to the Silverlight Control, retrieve the data from the web service and display it:
public partial class Page : Canvas
public void Page_Loaded(object o, EventArgs e)
// Required to initialize variables
InitializeComponent();
tb.MouseLeftButtonDown += new MouseEventHandler(tb_MouseLeftButtonDown);
void tb_MouseLeftButtonDown(object sender, MouseEventArgs e)
// var - C# 3.0 - The compiler infered the type.
var svc = new localhost.HelloService();
// Get the data from the Web Service
String result = svc.HelloWorld(new Random().Next());
// Set the width of the text block
tb.Width = this.Width;
tb.Text = result;
The asp:Xaml control enables the page Default.aspx do display Xaml like any other ASP control. The content of Default.aspx:
In order to the Web Application to recognize the Page.Xaml we can right click on the Web Application and select 'Add Silverlight Link...' which add a Page.Xaml copy into the Web Application, and ClientBin folder, which contains the assembly of the Silverlight Project.
Select the Silverlight Project...
And the result is...
Now lets start the application, by right click on Default.aspx and select 'View in Browser'. The result is as follows:
After clicking on the text...
After another clicking on the text...
You can download the source code of the Silverlight Control Sample.
Great post!
Call Silverlight from JavaScript This post is about great feature - the Managed HTML Bridge . With this | http://blogs.microsoft.co.il/blogs/egady/archive/2008/02/21/creating-silverlight-custom-controls-and-web-service-with-asp-net-futures.aspx | crawl-003 | refinedweb | 543 | 52.36 |
It looks like I'm late to the party, but lately I've been finding myself leaning less on mocked objects and more on real implementations. This was talked about back in early 2008 (and likely before then), but I kinda let the conversation pass over me. Suddenly I'm finding that, despite my early concerns, hitting real implementations not only makes my test easier to write but, shockingly (to me), makes them far less brittle.
When I first started using a mocking framework, I used strict semantics wherever possible. It didn't take very long to realize that such tests had a high maintenance cost due to tight coupling of the internal interaction. So I switched to looser style stubs and immediately saw benefits. But eventually I realized that, where possible, forgoing mocking at all brought that decoupling to the next level.
I know, it sounds counter-intuitive, but hitting mocks can often tightly couple your test to the implementation more so than hitting the real object. Think about it for a second, if you are truly interested in testing a behavior, why are you having to spend a lot of code defining the internal implementation of said behavior?
Let's look at an example. Say I have a
Message which I wanna generate a hash for - in order to see if its a duplicate of a previously logged message:
public class LoggingService { private IEncrypt _encryptor; public LoggingService(IEncrypt encryptor) { _encryptor = encryptor; } public string CalculateHash(Message message) { var hashKey = message.Body + message.Application.Id; return _encryptor.Hash(hashKey) } }
How would you test this? A year ago I would have created a mock for
IEncrypt and simply tested my code's interaction. But what does that really buy me? More importantly, what is it that I'm actually trying to test. Honestly, I don't care how the hash gets generated, how the encryptor is being used, all I care about is that I get the right hash. By using a real implementation of
IEncrypt in my test, I not only free my test of knowing more than it should, I also, as a sweet little consequence, end up with more accurate tests.
Wait a minute, you say, isn't that integration testing? I've personally decided that, for myself, unit tests and integration tests have a lot more to do with what I'm trying to test than how I'm testing it. That is, a test of
CalculateHash would be interested in specific behaviors - like calculating a hash. Integration tests are more concerned with how all the parts work together. I'd argue that using a mock object is much more of an integration test, because you are specifically concerne with, dependent on, and detailing how your objects interact (or, you know, integrate) with each other.
Wait another minute, you say, what about performance? Sure, sometimes you rely on code that's slow, or for other reasons isn't practical to execute. The solution is simple, use a mock. The point isn't that I've stopped, or you should stop, using mocks (I haven't even come close to that), they just aren't my first choice. First try to use the real implementation, then try again a little harder, then use a mock.
Ok, but what about when you really do care about how your objects interact? It happens sometimes where a behavior will be directly related to interaction. A trivial example that comes to mind is lazy-loading: you want to make sure that subsequent calls don't reload the object. Of course mocks are handy in this situation, but make that its own focused test.
Its possible you aren't sold. That's fine. But I'll at least ask you to try and meet me half way. I urge you to make sure your mocks are as implementation ignorant as possible. Don't verify unless you actually have too. Don't use strict semantics. Don't care too much for specific inputs. Don't set expectations on occurrences (common for jMock programmers using the oneOf instead of allowing methods). Trust me, you won't regret it. | https://www.openmymind.net/2010/10/20/My-Slow-Transition-Away-From-Mocks/ | CC-MAIN-2020-05 | refinedweb | 693 | 63.29 |
49552/python-error-pygame-error-couldn-t-open-pygame-png
I'm trying to build the snake game using pygame. I'm following this tutorial.
I end up with the following error:
pygame.error: Couldn't open pygame.png
icon = pygame.image.load('spaceship.png')
pygame.error: Couldn't open spaceship.png
I am getting this error,\anyone?
Hope this Helps!!
To learn more, join the online course to do Masters in Python.
Thanks!
Hey, @ Ali,
It will be very helpful if you can post your code. Though I can suggest you something like better to use Relative paths instead.
current_path = os.path.dirname(__file__) # your .py file is located
current_path = os.path.dirname(__file__) # the resources folder path
image_path = os.path.join(resource_path, 'images') # the image folder path
By doing this, wherever you move the folder containing your .py file, its subdirectories (and therefore whatever they contain) can still be accessed without you having to modify your code.
current_path = os.path.dirname(__file__) # Where your .py file is located
resource_path = os.path.join(current_path, 'resources') # The resource folder path
image_path = os.path.join(resource_path, 'images') # The image folder path
player_image = pygame.image.load(os.path.join(image_path, 'spaceship.png'))
I hope this will be helpful.
Hi, @There,
You have to add in the file that has the script.
Every application usually ships with various resources, such as image and data files, configuration files and so on. Accessing those files in the folder hierarchy or in a bundled format for various platforms can become a complete task, for which the resources module can provide ideal supportive application components.
The Resource class allows you to manage different application data in a certain directory, providing a dictionary-style access functionality for your in-application resources.
Hey, @Sumit,
Do you import os?
Just add:
import os
in the beginning, before:
from settings import PROJECT_ROOT
This will import the python's module os, which apparently is used later in the code of your module without being imported.
Hey, @There,
Are you facing the exact same error which is mentioned above while executing your code?
my code is like this
import pygame
import sys
screen = pygame.display.set_mode([680, 480])
pygame.init()
screen.fill([130, 0, 200])
class Block(pygame.sprite.Sprite):
def __init__(self,file_name,location):
img = pygame.image.load(file_name)
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([width,height])
self.image.fill(color)
self.rect = self.image.get_rect()
pygame.image.load('ball(2)')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
So using this code you want to conclude that there is no error after executing it?
add import os at top of your ...READ MORE
Try installing libpng
You can do it with ...READ MORE
You need to download and install the ...READ MORE
pygame.Surface takes in integer values for building ...READ MORE
You must be trying this command in ...READ MORE
file = open('text.txt', . | https://www.edureka.co/community/49552/python-error-pygame-error-couldn-t-open-pygame-png?show=85022 | CC-MAIN-2022-27 | refinedweb | 499 | 52.97 |
Nov 06, 2020 05:42 AM|abhisinghal21|LINK
In ASP.NET MVC classic, there used to be a controller
Initialize method that one could override and put initialization code. Similarly there was
OnResultExecuted method where one could put finalization code.
Above were found super useful for controller base classes. And now not found in ASP.NET Core. Have used
OnActionExecuting and
Dispose Methods in Asp .Net core controller as new homes for above.
Q1 - What are the architectural / philosophical reasons behind this removal?
Further the ControllerBase class (equivalant to ApiController in Asp .Net MVC) does not even have above
OnActionExecuting and
Dispose methods. So now could find two remedies - use Controller class as base for ApiControllers as well or use filters.
Q2 Why exactly ControllerBase doesnt have any methods to put initialization and finalization code ?
Thanks
All-Star
57464 Points
Nov 06, 2020 04:51 PM|bruce (sqlwork.com)|LINK
Q1:
the ControllerBase is not equivalent to the old ApiController, the core equivalent is Controller.
In core there is no ApiController class. You get an api controller by adding the [ApiController] attribute to a class that inherits from Controller:
Q2:
ControllerBase does not define any lifecycle events. Those are defined as interfaces and implemented by say the Controller class.
note: asp.net core was a rewrite of the old asp.net/mvc as a clean slate. Complete backward compatibility was not a goal.
Nov 06, 2020 04:55 PM|abhisinghal21|LINK
Q1: Is actually regarding the MVC Controller (not API controller)
Q2: That is slightly old information
pl refer
All-Star
57464 Points
Nov 06, 2020 10:40 PM|bruce (sqlwork.com)|LINK
abhisinghal21
Q2: That is slightly old information
pl refer
the webapi template uses ControllerBase because it does not need the lifecycle events. it is still the [ApiController] attribute that makes its an apicontroller. in fact you don't even to need to inherit from ControllerBase.
a perfectly working api controller:
[ApiController] public class MyClass { [Route("api/echo/{s}")] public string echo (string s) { return s; } }
you just don't get the handy helper methods defined by ControllerBase
Nov 07, 2020 05:57 AM|abhisinghal21|LINK
Thanks Bruce.
Based on your answer, did some more investigation by visiting the source code of the Controller class.
Turns out we can apply IActionFilter and IResultFilter at the Controller Level and get the desired methods as before. As per this document, these are executed before action level filters so would achieve the same effect.
Controller.cs does that to generate the OnActionExecuting and OnActionExecuted methods.
Thanks
4 replies
Last post Nov 07, 2020 05:57 AM by abhisinghal21 | https://forums.asp.net/t/2172018.aspx?Controller+Initialize+Method | CC-MAIN-2020-50 | refinedweb | 437 | 57.77 |
Posts38
Joined
Last visited
About Johan ⚡️ Nerdmanship
- Birthday 03/25/1983
Profile Information
- GenderMale
- LocationBali
- InterestsSurf, design, games & tech
Recent Profile Visitors
Johan ⚡️ Nerdmanship's Achievements
Newbie (1/14)
33
Reputation
-
HI,
can you please help me wth this animation i am unable to perform this
- Ah perfect – thanks a lot, Jack! And by including a css wrapper GSAP won't change the objects, I presume. TweenMax.set(blueDot.target, { css:pointObjects[i] });
-!
- A million thanks, Jack! I went with the less optimal but to me conceptually familiar method. There are so many new concepts to me in this project, so adding another one – even if it's a small one – felt daunting. The methods I ended up using were good enough tho and are silky smooth on all devices I've tested on. Very pleased! The code is messy but it's working. For sake of learning tho I'm gonna refactor it as soon as I get the chance, and I will definitely use your suggested solution when I do. I sense there's some very usable concepts in there, and I recognise some from Coding Math (as recommended by Blake). Seems to be "animation standards" of sorts and as an aspiring web animator... I kinda like that. Here is the end result for whoever is interested:
- Thanks for some pretty code and your precious time, Jack! ❤️ I need to touch up my trigonometry to fully understand what's going on. At this point I can't determine if this will solve my problem or not. The actual project has large parts of it developed already and I depend on a solution in which I can use the x and y values from one elements gsTransform object and the rotation of another. In the actual project the particles will not be explicitly animated but respond to the coordinates of the colourful rectangles and the rotation value of a group element surrounding them. (mockup) My plan is to give each particle its own TweenMax object with its own modifier function feeding x and y values based on values from the leading elements gsTransform object. Here's a simplified part of that: TweenMax.to(particle, 1, { x: 0, y: 0, repeat: -1, ease: Linear.easeNone, modifiers: { // Distributes the particles exponentially between 0 and the current position of rect x: function() { return (indexSq / countSq) * rect._gsTransform.x; }, y: function() { return (indexSq / countSq) * rect._gsTransform.y; } } }); I'm not sure, but it seems like I could use the intended x/y/rotation values from gsTransform objects to update radius/angle of a proxy to generate x/y values for each particles. The math of it is possibly too advanced for me tho, so I might have to fall back on the SVG 2 style just because I can wrap my head around it.
-
GSAP on other platforms than web?
Johan ⚡️ Nerdmanship replied to Johan ⚡️ Nerdmanship's topic in GSAPThanks buddy!
GSAP on other platforms than web?
Johan ⚡️ Nerdmanship posted a topic in GSAPEvery dev around me get excited when I show them what can be done with HTML5 and GSAP. Most of them start playing with the idea to apply the same concept of programmed, and potentially data driven, animation to whatever project they are working on. Very often I get the question if you can do the same things for other platforms, i.e. native iOS or android apps, and I simply don't know how to answer. My initial thought is that you can use GSAP wherever you can use JS, but I don't have enough experience from projects on these platforms. Any experience, thoughts or recommendations on this? <3
Javascript intermediate and advanced learning?
Johan ⚡️ Nerdmanship replied to Visual-Q's topic in GSAPI learned a lot big and small from exercises such as Wes Bos' Javascript 30: javascript30.com/ I also enjoy watching conf talks on all different Js topics. It goes beyond syntax and coding techniques, and slowly but surely provides a great general knowledge on how JS things work and why. This in turn gives you a really good understanding on why devs do like they do. I.e: What the heck is the event loop anyway? I also follow people on youtube and listen to their opinions and watch them code live. I.e. FunFunFunctions GLHF!
Best way to apply a modifier tween on multiple targets?
Johan ⚡️ Nerdmanship replied to Johan ⚡️ Nerdmanship's topic in GSAPLOL – truly an awe-inspiring creation!
Best way to apply a modifier tween on multiple targets?
Johan ⚡️ Nerdmanship replied to Johan ⚡️ Nerdmanship's topic in GSAPI worship your input as a divine scripture. Thanks again for sharing! Since you shared the technique of map func, modifiers and storing values in an object I've not only been writing better code, but thinking more creatively about animations. I don't see many reasons not to use modifiers at the moment. I recommend anyone reading to check out Blake's forum posts about norm, lerp and map functions here, how he updates a tween with modifiersPlugin in this pen and how he combines map and modifier in this pen. ✌️
Best way to apply a modifier tween on multiple targets?
Johan ⚡️ Nerdmanship replied to Johan ⚡️ Nerdmanship's topic in GSAPBlake, what a surprise! Let me know if you ever need a kidney. I noticed this in the project I'm working on, and honestly I had no idea "let" created a new scope on each iteration. After knowing this and studying more of your mentioned pens, I rewrote my code and, as usual, it works better. My brain hurts tho. To me, using the let/const is a first step into ES6 and a little affirmation to myself that I'm not afraid of new syntax (which - of course - I am). Whenever I use var, I feel like I'm resorting to my comfort zone where I develop less. This is clearly not rational. Understanding var on a fundamental level would obviously not set me back. But when I think about it that's probably my main motivation. I bet a lot of people, just like me, don't fully understand what we're doing and why. However, this tend to put me in tricky situations in which I'm forced to learn. Edit: Oh, kind of on the same topic... you said in this post that you wouldn't use mouse position for some values in a real project. Why is that?
Best way to apply a modifier tween on multiple targets?
Johan ⚡️ Nerdmanship posted a topic in GSAPGreetings! I'm using Blakes clever method of using a mouse object to update a modifier function (pen), but in my case I have multiple targets. It feels like a pretty common use case, so I assumed there's a good practise to do it. In the example I want the boxes to follow the mouse movement depending on their respective index in the collection. The pen works, but I wonder if there's a way to do it without a for loop, like the way you can with "function based values". This is what I've got: (pen) // A collection of five boxes const boxes = document.querySelectorAll(".box"); // Mouse object as input in modifier function const mouse = { x: 0 } // Bind mouse to update function window.addEventListener("mousemove", updateMouseObj); // Updates mouse object function updateMouseObj(e) { mouse.x = e.clientX; } // Working example with for loop for (let i = 0; i < boxes.length; i++) { TweenMax.to(boxes[i], 1, { x: 0, repeat: -1, ease: Linear.easeNone, modifiers: { x: function() { return mouse.x * i; } } }); } /* // Seems lengthy and fragile, Codepen throws an infinite loop error TweenMax.to(boxes, 1, { x: 0, repeat: -1, ease: Linear.easeNone, modifiers: { x: function(x, target) { for (let i = 0; i < boxes.length; i++) { if (target === boxes[i]) { return mouse.x * i; } } } } }); // Would wanna do something like this TweenMax.to(boxes, 1, { x: 0, repeat: -1, ease: Linear.easeNone, modifiers: { x: function(i) { return mouse.x * i; } } }); // ...like function based values work TweenMax.to(boxes, 1, { x: function(i) { return 50*i; } }); */ Thanks! <3
Understanding TimelineMax callback and scope
Johan ⚡️ Nerdmanship replied to Johan ⚡️ Nerdmanship's topic in GSAPThank you so much for your thoughts and pens, guys! Great advice, Dipscom – thanks! Of course I ran in to this problem and my solution was to kill the interval on window.blur and recreated it on window.focus. It works well, but it doesn't feel robust enough. This (code below) was what I could imagine from your suggestion, but I realised that it probably would end up out of sync in the tab use case. It also kinda does the same as the previous version, only looping thru the array differently. What did you have in mind? var boxes = []; var dur = 2; // create one timeline that repeats itself tl.to(boxes, dur, { bezier: [ { autoAlpha: 0 }, { autoAlpha: 1 }, { autoAlpha: 0 } ], repeat: -1 }); // updates the contents of the boxes at a specific point in time setInterval(function() { // update stuff }, (dur*1000)/2) // Half way thru timeline duration - - Thanks Blake – always great advice and so useful resources! Thanks for both offering me what I was looking for and also a better way to approach it.
Understanding TimelineMax callback and scope
Johan ⚡️ Nerdmanship replied to Johan ⚡️ Nerdmanship's topic in GSAPThanks Carl! Sorry for the private settings, I wasn't aware it was limiting in that sense. It's update and public here: The brackets did do the trick with passing the i. It was sloppy of me and I haven't had this issue in other projects. I discovered that the callback was working only because $box was leaking to the global object, since I forgot to declare it with "var". I don't want that, I want to keep the variable in the local scope. So I'm still wondering about scope. By logging this from the callback function I can see that the scope is changed successfully from the timeline to the newItems function by writing like so: .call(getRandomItem, [i], newItems) However, the $box variable in the callback still throws a reference error. Which is my initial problem and query. If I would declare the callback function inside newItems function then $box is referenced properly. This is what I want to achieve, but I want to declare the function outside that scope to make it accessible to other functions too. If this is too much of a general Js question I could turn to Stack Overflow and then come back here and share any results. --- Just some context to clarify why I'm asking... - I want each function to have one job (as long as it makes sense) - I want to be able to reuse functions in other functions - I don't want to repeat myself and declare the same variable multiple times This is why I run into challenges regarding scope a lot. I'm practising and researching it a lot, but I still have some missing knowledge it seems. In this case I could solve this by re-assigning $box = $boxes in the callback function, but it seems like bad practice. Especially if you'd have a bunch of variables. The code eventually gets bloated, harder to overview and manage, and more prone to bugs. If this problem is solved there will still be a timing issue. The loop will perform all of its iterations before the first timeline has reached the first callback. All callbacks will reference the same $box – the last item of the $boxes array. Edit: Removed jQuery | https://staging.greensock.com/profile/43390-johan-%E2%9A%A1%EF%B8%8F-nerdmanship/ | CC-MAIN-2022-40 | refinedweb | 1,931 | 64.41 |
I want get the mount node of an usb mass-storage device, like /media/its-uuid in pyudev, class Device has some general attributes, but not uuid or mount node.
how to do it
thanks help
With pyudev, each device object provides a dictionary-like interface for its attributes. You can list them all with
device.keys(), e.g. UUID is for block devices is
dev['ID_FS_UUID'].
This will print the UUID of every USB flash disk currently plugged in along with its device node:
import pyudev context = pyudev.Context() for device in context.list_devices(subsystem='block', DEVTYPE='partition'): if (device.get('ID_USB_DRIVER') == 'usb-storage'): print '{0} {1}'.format(device.device_node, device.get('ID_FS_UUID'))
Similar Questions | http://ebanshi.cc/questions/4637503/how-to-get-uuid-of-a-device-using-udev | CC-MAIN-2017-51 | refinedweb | 116 | 52.15 |
Hello guys I need your help im really new in C++ and I need to do easter calculation to get the right easter day, at the moment I could get one year.
Example:
Year 2015
Easter Day in 2015 is/5/4/2015Year
but my professor is asking me to get year range
Example:
Year 2015 2020
Easter day in 2015 is 5/4/2015
Easter day in 2016 is 5/8/2016
........
Easter day in 2020 is ....
The problem that have is I don't know how to start at the moment I just have integer to calculate year how can I have two integers? and then guess I need while and increment or how can I do it ? please help me out guys! I would really appreciate this my code so far:
#include<iostream> using namespace std; int main() { int year, date, month; int a, b, c, d, e, f, g, h, i, j, k, m, p; do { cout<< "Year "; cin >> year; a=year%19; b=year/100; c=year%100; d=b/4; e=b%4; f=(b+8)/25; g=(b-f+1)/3; h=((19*a)+b-d-g+15)%30; i=c/4; j=c%4; k=(32+(2*e)+(2*i)-h-j)%7; m=(a+(11*h)+(22*k))/451; month=(h+k-(7*m)+114)/31; p=(h+k-(7*m)+114)%31; date=p+1; cout << "Easter Day in" << " " << year << " " << "is" << "/" << date << "/" << month << "/" << year; } while (year>=0001&&year<=5000); return 0; }
I'm really lost I think should do loop but I dont even know how to compare to years in the same calculation maybe increment ? im lost guys help me out.. | https://www.daniweb.com/programming/software-development/threads/499938/c-help | CC-MAIN-2017-34 | refinedweb | 282 | 78.32 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.