Message Boards Message Boards

[WSG21] Daily Study Group: programming tutorials

Posted 3 years ago

Daily Study Groups are back, now providing expertise on practical programming! After a short break, we're starting up with a series that picks up where Wolfram Language Basics sessions ended. This 3-week series will take you from basic programming concepts to package development.

Need tips on improving your code’s speed or functionality? Programming Tutorials offer a great opportunity to level-up your skills while interacting with software development professionals. See hands-on examples and get questions answered by Wolfram Language experts. Plus: participants who pass weekly quizzes are awarded a program completion certificate. Level 1 certification is available for those who pass manually graded exercises.

Join us any time between August 2 and August 20! Check out our registration page for more details.

POSTED BY: Wolfram U
128 Replies

Thank you. Let me try :)

Revisit the link to the exercise and the updated version should load for you.

What should I do after the 15_excercise deleted?

[WSG21] Daily Study Group: programming tutorials

Sorry about the unsatisfactory answers.

Your conclusion is correct. "\$Line" is just a global variable that specifies the number of the current input line. It can be reset without erasing the input history. However as you start evaluating inputs with the new line number, new lines are numbered so as to overwrite previous ones with the same numbers.

There is however "\$HistoryLength" to specify the number of previous lines of input and output to keep in a Wolfram System session. So by resetting it you can reduce memory usage in a session by limiting the amount of history that is remembered.

At any point MemoryInUse gives the number of bytes currently being used to store all data in the current Wolfram Language kernel session. Here are some functions that provide information about the Wolfram System Session https://reference.wolfram.com/language/guide/WolframSystemSessionInformation.html but we do not have one that specifically gives the memory used just by the previous input lines.

As for the poll question, we could perhaps rephrase it to "Which of the following can be used to re-evaluate a previous input?"

Posted 3 years ago

I clearly phrased my question in the wrong order. I should have stated my problem first. I don't care about the planets dataset, per se, I care about a dataset of my own that has a similar hierarchical structure.

My dataset will have thousands to tens of thousands of entries. Your suggestion of deconstruction/reconstruction, particularly using a file as intermediate storage, is completely impractical. Wolfram loves to tout the analytical capabilities for processing a given set of data, but where is the help for incrementally building the dataset for analysis?

I am creating a database-like application, but, for practical reasons, I cannot use an external database. I am creating and adding to my data incrementally.

Suppose that I have a thousand+ objects. Each object (~planet) has a name, a stock number and 1-100 parts (~moons). Each part has a name, dimensions, weight (~moon mass) and color. Each color (1 level finer structural detail than the planets dataset) has mixing instructions for how to reliably reproduce it.

How do I efficiently add a new part to object 742?

How do I efficiently change the mixing instructions for the color of part 7 of object 128?

POSTED BY: Gerrie Shults
Posted 3 years ago

Hi Gerrie,

ExampleData is part of the Mathematica install. It can be automatically updated via a paclet update (e.g. if a new moon was discovered) so changing it is not a good idea. Changes can be made to a copy and persisted for later use.

Structural changes to Dataset are sometimes easier to perform on the corresponding Normal expression and then converting back to Dataset. Here is an example of how to add a new moon to the earth using a subset of the data and broken down into steps so it is easier to follow. It can be done more directly but is harder to follow.

(* First 4 planets *)
data = ExampleData[{"Dataset", "Planets"}][[1 ;; 4]] // Normal
earth = data["Earth"]

(* Add a new moon *)
newEarthMoons = earth["Moons"] // 
Append["BlueMoon" -> <|"Mass" -> Quantity[10.^15, "Kilograms"], 
     "Radius" -> Quantity[1.5, "Kilometers"]|>]

(* Replace moons and earth *)
newEarth = <|earth, "Moons" -> newEarthMoons|>
newData = <|data, "Earth" -> newEarth|>
myPlanets = newData // Dataset

(* Save, clear, read *)
DumpSave[FileNameJoin[{NotebookDirectory[], "myPlanets.mx"}], myPlanets];
ClearAll@myPlanets
Get[FileNameJoin[{NotebookDirectory[], "myPlanets.mx"}]]
myPlanets
POSTED BY: Updating Name

We plan to post the notebook from the final review session soon. Sorry for the delay.

POSTED BY: Jamie Peterson
Posted 3 years ago

Thank you for the information regarding the symbolic capabilities of Mathematica. I am wondering how to create a program like the one Wolfram Alpha has where you can type in the values of the known variables to get the target variable. I have the following code but would like to make it so that I can input the values with labels.

Manipulate[
 SolveValues[
  bigmass*Quantity[1, "StandardAccelerationOfGravity"]*
     distancefrompivotpoint + (length - distancefrompivotpoint)*
     smallmass*Quantity[1, "StandardAccelerationOfGravity"] == 0, 
  thingtosolve], {thingtosolve, {bigmass, smallmass, length, 
   distancefrompivotpoint}}]
POSTED BY: Updating Name

The programming exercises for the Level 1 certification offered by the "Programming Tutorials" study group series have been updated at https://wolfr.am/WSG15_Exercises . If you do not see the changes taking effect, please try the following:

Before: enter image description here

Log in to cloud and go to "Copied Files" folder within your Home folder. Delete 15_exercies.nb enter image description here

Go to "Trash" folder and delete permanently 15_exercies.nb enter image description here

After: enter image description here

Posted 3 years ago

As a small addition to Michael's answer, I would recommend that you not use numbers in your set of equations, since WL is known to handle symbols.

More precisely, I think that NSolveValues[75kgf*(x-9m)+(x)*25kgf==0,x] does not work the way you want it to. Mathematica will interpret kgf and m as additional variables - and proposes in the suggestion bar to solve the equation for kgf and m .

After solving the equations symbolically, I would use something like

param = {Fadult -> Quantity[75, "kilograms"], 
  Fchild -> Quantity[25, "kilograms"], L -> Quantity[9, "meters"], 
  Fboard -> Quantity[15, "kilograms"]}

to get a numerical result.

As a follower of the SI, I personally would never use the unit "kgf".

POSTED BY: lara wag

Did anybody get the NB files for the Review III session (August 20)?

Posted 3 years ago

Did anybody get the NB files for the Review III session (August 20)?

POSTED BY: Updating Name

Hi, Abrita. Probably, I have missed the announcement. Are the NB files for the last Review session available?

Thank you. M

Peter, you probably do not need NSolve. Instead you can solve it analytically (or using Solve) in two lines. Then you can parametrise the solution (say, using masses, the length of the board, etc as the parameters, some fixed and others - unknown). Then you can suggest users to fix some of the parameters and find the others, in order to establish a neutral equilibrium.

In reality, in static case, if you are not interested in the elastic deformation of the board, you may end up with just one equation.

After the first part is done, you can select a proper interface for your "app". Wolfram presents a lot of choices.

I am also having issues with the autograder. The major one is that from the several possible solutions leading naturally to the same results, it choses just one and blocks all the others. The "guy" is very authoritarian.

I am trying to make a program that solves statics problems such as the following that follow a general format: A 75-kg adult sits at one end of a 9.0-m-long board. His 25-kg child sits on the other end.

Where should the pivot be placed so that the board is balanced, ignoring the board’s mass?

Find the pivot point if the board is uniform and has a mass of 15 kg.

My plan is to create a general set of equations that relate the 3 conditions for equilibrium (net forces in x-direction=0, net forces in y-direction=0 and net torque=0) to the known quantities to solve for what is needed.

For example in this case I would use the following Mathematica code:

NSolveValues[75kgf*(x-9m)+(x)*25kgf==0,x]

And

NSolveValues[75kgf*(x-9m)+x*25kgf+4.5m*15kgf==0,x]

My goal is to create a program where the user can select whether they would like to solve for the big mass, the small mass, the pivot points distance from the big mass, the length, or the mass of the bar.

I am not sure whether to use Manipulate, Form Function, Form Page, Dynamic, or Dynamic Module.

I am also considering uses Switch and Which to build a program where they select what quantity they would like to solve from a dropdown menu, and then enter the values for the remaining quantities. The kernel would then solve for the variable and output the result.

I am also having issues with the AutoGrader and was wondering what to do.

I am also wondering if there is a way to see if I need to watch any of the recordings to get the certificate of completion. I think I may have missed one day, but I can't remember which day I missed.

POSTED BY: Peter Burbery
Posted 3 years ago

How can I modify, in place, a dataset like the planets data used in the session on Datasets?

For example, suppose I set planetData = ExampleData[{"Dataset","Planets"}] and a new moon of Jupiter is discovered. How would I add it, such that the value of planetData contains the new moon.

Or, suppose a new mission updates the mass and/or radius of known moons of any planet. I'd like to update those in place, again so that planetData returns all the correct information.

I'm working on a program with a much larger dataset that is structured similarly to the planet data, and I would like an efficient mechanism to perform these kinds of updates.

POSTED BY: Gerrie Shults
Posted 3 years ago

By FullForm you mean using Canonical Names without icons? If so, I've tried that. :).

POSTED BY: Rongoetz

Looks like the auto-grader is being very picky about how Entities or EntityClass is represented in the code. With the latest update, we hope that the FullForm representation of an Entity or EntityClass will be accepted for sure.

Posted 3 years ago

Where do I find the "Check My Progress" page?

Also, I've tried four different (minor) variations each for #'s 16 and 17, all giving the expected output but all rejected by the auto-grader. I'd just like to know if someone has found a version that the auto-grader accepts (but don't tell me what it is!).

POSTED BY: Rongoetz

OH, GOOD! I was wondering. Thanks, Abrita!

POSTED BY: Lori Johnson

[WSG21] Daily Study Group: programming tutorials

A few more words about MC and Pi.

Using the "weighting" or, equivalently, the " regular grid " approaches to determining the relative area of a circle (or the value of Pi) is not inferior to using MC with RNG. In both cases the error ~ N^(-1/2). MC is a nice Demo, but there is nothing really mind-boggling about it. Thanks for raising this questions. I had some suspicions before, but had never took time to think it through.

Posted 3 years ago

Good video! Interestingly, when we touched the "weighting" approach to Pi, and the "atomic precision", it was actually about the atomic plane, similar to a grid displayed in the video. You have to draw a circle in such a plane (How? :)) and them to decide which atoms are in and which are out...sort of. And, funny to say, the Planck constant will likely determine the corresponding precision of Pi. So, it seems to me that the discussion in video has a straight "atomic analogy"...

In physics, this realm of questions was wonderfully outlined by Eugene Wigner (if you did not have a chance, please check it: https://www.maths.ed.ac.uk/~v1ranick/papers/wigner.pdf "THE UNREASONABLE EFFECTIVENSS OF MATHEMATICS IN THE NATURAL SCIENCES". )...

Best regards.

POSTED BY: Updating Name
Posted 3 years ago

Pi in terms of Gaussian numbers and the distribution of primes (it has the feel of Monte-Carlo without RGNs) :)

https://tinyurl.com/p54hjtee

POSTED BY: Doug Beveridge

Yes!

Posted 3 years ago

RNG's (Pseudo- RNG's) are at the core of Monte-Carlo

https://demonstrations.wolfram.com/MonteCarloEstimateForPi/

POSTED BY: Doug Beveridge

It seemed to me that Monte-Carlo itself relies on RNGs. It always starts with random moves. In physical applications they can be accepted or rejected based on their "energy cost". I guess, you meant a simplest and may be the most beautiful example of MC, - finding the value of Pi (by randomly shooting "rounds" at the target and counting fraction that entered the circle of a given R). But the accuracy of the obtained Pi will depend, among the other factors, on the quality of RNG (on how random the shots are). The Pi itself is obtained by regular mathematical means, not relying on randomness. Interestingly, there is also purely "physical" way of "measuring" the Pi. Take a 1x1 square made of a uniform material, and measure its weight Wsq. Then, cut from it a circle of D=1. Find its weight. Wci. The rest is straightforward. The real challenge would be measuring Pi with "atomic" (quantum? ) precision. I know it sounds funny :)

Posted 3 years ago

So it seems that pi is not a good random number generator but the fact that you can generate pi using random number techniques (monte carlo method) still boggles my mind.

POSTED BY: Doug Beveridge

It was also entertaining (just for fun) to check the plots for "randomly generated" 300 digits. After all, there is an old and interesting discussion on "randomness" in Pi's digits (see e.g. https://mathoverflow.net/questions/26942/is-pi-a-good-random-number-generator).
In addition, one may also play with gaussian and other distributions :). Their qualitative effect on the plots would be interesting to discuss.

Here is the expected output for problem 2 with ListLinePlot3D: ListLinePlot3D-ExpectedOutput

Posted 3 years ago

Abrita has stated above that

"Sorry about the expected output and auto grader solution not matching the exercise text. The exercise will be updated on Monday. Thank you for your patience"

So, it seems we will have to wait till Monday to see if the new "output " looks like this, otherwise back to the drawing board.

enter image description here

It took a while to work out ListLinePlot3D is new in 12.3 so does not work in my 12.2 version

[1

POSTED BY: Doug Beveridge

There seem to be two possibilities: either the expected result (the picture) was correct while the proposed function was wrong, or vice versa. In any case, trying to solve under both assumptions was good for learning. The closest I could get under the first scenario (trying to reproduce the original plot using ListLinePLot3D) was by setting "Joined -> False" in ListLinePlot3D , which turned lines into points.

In my humble opinion, the original ( with the dots) picture is clear and instructive, while the second is beautiful, impressionistic and hardly interpretable. In combination with the story, it can make a nice NFT. Any way, thank you for the wonderful brain teaser. The errors like this must be included by design! PS. By the way, while playing with the functions, try using the "plane" version ListLinePlot [list, ColorFunction -> "Rainbow"] (both with "Filling->Bottom", shown below, and without it *), Aren't they nice?! "? :)

enter image description here

Posted 3 years ago

I agree that the output is cooler with ListLinePlot3D, but I didn't see how to make it match the expected Output.

POSTED BY: Rongoetz

We do want you to use ListLinePlot3D. The output will look way cooler :)

Sorry about the expected output and auto grader solution not matching the exercise text. The exercise will be updated on Monday. Thank you for your patience.

Posted 3 years ago

I could certainly be wrong, but... In the exercises, #2, I don't think you meant ListLinePlot3D. I got the correct answer (per auto-grader) using another function. Ron

POSTED BY: Rongoetz

Deadlines for Quiz and Exercise submissions:

  • Quizzes (for Certificate of Program Completion): Aug 27, 2021
  • Programming Exercises (for Level 1 Certification for Proficiency in Using the Wolfram Language): Sep 3, 2021

Thank you! Be well. M

Michael, we have requested Support to get back to you on this over email.

On the issue with webMathematica on Workbench install, I remember seeing both Wolfram Core and Wolfram webMathematica being on the list of options but only Core was checked by default on my system.

POSTED BY: Ray Chandler
Posted 3 years ago

There were several unsatisfactory answers (IMO) given in yesterday's session.

I had asked if resetting \ $`Line` erased the history entries, or if they persisted until a new entry was evaluated with the `In[]` number. The instructor didn't really answer the question at all (perhaps he didn't understand what I was asking) and simply reiterated that setting \$Line caused the In[] numbers to start again from that value. In a similar vein, someone had asked (I think) about measuring the amount of memory tied up in history entries and did not get a relevant answer.

In any case, for those who may be interested, experimentation shows that changing \$Line does not immediately erase any history entries. And I think an estimate of the amount of space used by previous results can be obtained by

Total[ByteCount /@ Out[Range[$Line - 1]]]

(Out[\$Line] itself has to be excluded to avoid recursion.) But I couldn't figure out how to find the space occupied by the In[] entries, given that I don't actually want to reevaluate them.

Which leads me to mention the third poor or missing reply yesterday. Someone suggested that the correct answer to Poll question 2 "How would you evaluate a previous input?" was not in fact "d. All of the above", as answers b. and c. merely retrieve a previous result, rather than reevaluating the expression that produced it. I agree completely. As stated, the answer should be "a. In[-k] for the input k lines back". Of course In[n] for the specific line n also works, as does re-evaluating the cell in question as suggested in answer e.

POSTED BY: Updating Name

The documentation for Plot should help https://reference.wolfram.com/language/ref/Plot.html Look under "Details and Options".

A reply from Jayanta Phadikar (original author of the Programming Tutorials):

It is correct that if context 1 precedes context 2 in $ContextPath, the system will use the context 1 definition. Here is an experiment:

In[7]:= Begin["context1`"];
func[] := "From Context 1";
End[];

Begin["context2`"];
func[] := "From Context 2";
End[];

In[26]:= $ContextPath = Flatten[Prepend[$ContextPath, {"context1`", "context2`"}]];
func[]

Out[27]= "From Context 1"

In[28]:= $ContextPath = Flatten[Prepend[$ContextPath, {"context2`", "context1`"}]];
func[]

Out[29]= "From Context 2" 

In practice we should however avoid keeping symbols that are common in two different contexts (it is fine of course to keep common symbols in Private contexts). Since without checking the order in $ContextPath we won't know which definition is being used. The red syntax coloring is exactly meant for this warning.

So the Remove expression was meant for ensuring that there is no duplication.

Side note: it is correct that the square symbol in the Global context was created by In[7].

Issue with WorkBench installation ;

For some reason, Eclipse does not show the "Wolfram Workbench webMathematica". I only see the "Wolfram WorkBench core". Tried to add a path to my local Mathematica, but Eclipse does not accept it. Please, advise.

Posted 3 years ago

You can add the definition(s) to $UserBaseDirectory/Kernel/init.m.

POSTED BY: Rohit Namjoshi

Is there a way to define the function globally in my system so that when I close Mathematica and open a new document the function is still defined. I realized that the function only works within a session.

POSTED BY: Peter Burbery

Pursuant to my question during today's session about why Remove[Global`square] and Remove[Global`fun1] were said to be necessary, I experimented with leaving it out. I tried the following extracts from the lesson notebook, starting with a fresh kernel:

In[1]:= Begin["mathOperations`"];
        square[x_] := x^2
        End[];
In[4]:= $Context (* current context *)
        square[10] (* returns unevaluated since the current context is not mathOperations` *)
        mathOperations`square[10]
Out[4]:= Global`
Out[5]:= square[10]
Out[6]:= mathOperations`square[10]
In[7]:= PrependTo[$ContextPath, "mathOperations`"];
In[8]:= square[10]
Out[8]:= 100

Although a Global`square did indeed exist, presumably created by the reference to the undefined square by In[5]:

In[9]:= Names["Global`*"]
Out[9]:= {Global`square}

But as observed, the short name square still refers to the function we created, presumably because mathOperations occurs in $ContextPath before `Globals`. Hence the Remove[] call in the original notebook was just an act of excess caution. Does this seem right?

POSTED BY: Hilderic Browne

That's genius! I figured out a way to help with the issue of the network timing out.

POSTED BY: Peter Burbery
Posted 3 years ago

Try evaluating an expression using Plot, then check the Attributes. Take a look at this post on MSE for details.

POSTED BY: Rohit Namjoshi
Posted 3 years ago

Hi Peter

A location within

EntityValue[Entity["GeographicRegion", "World"], "Polygon"]

can be below sea level. e.g. Death Valley, Dead Sea, ... An alternative approach is in the attached notebook - to avoid spoiler.

POSTED BY: Rohit Namjoshi

This is about the question 8 of the Test 2: Which attribute of Plot causes it to return an error when the following expression is evaluated? Plot[Integrate[x,x],{x,-10,10}]: (a) HoldRest, (b) HoldFirst, (c) HoldAll, (d) Hold Pattern

To avoid the error, the function Integrate[x,x] can be evaluated to 0.5 x^2 before x is allowed to vary. This can be done, e.g., by switching to Plot[Evaluate[Integrate[x,x]], {x,-10,10}]. However, the question suggests to focus on the (alleged) attribute(s) of the Plot. Attributes[Plot] does not include any of the suggested choices (a)-(d). I would appreciate any possible hints that won't compromise the integrity of the Test.

In an earlier version of the quiz, the quotes were missing around ""too bee or not". The correctly formatted expressions should be:

StringCases["too bee or not", x_ ~~ x_]

StringCases["too bee or not", ("o" | "e") ..]

StringReplace["too bee or not", x_ ~~ x_ :> StringJoin[x, x]]

StringCases["too bee or not", ("o" || "e") ..]

This would work after reformatting the input to "too bee or not". However, my grade is 90, and this frivolity seems to be the only plausible reason for its reduction.

I am working on a Wolfram Challenge to determine whether or not a geographic point's antipode is above sea level or not (https://challenges.wolfram.com/challenge/antipode-above-or-below-sea-level). I have some code that I am attaching in a notebook in case anyone happens to be working on Wolfram Challenges and does not want to view the solution. The test coordinates should return True and are for Beijing China. The problem is I keep getting a Network Time Out error. How can I resolve this? I tried to use EntityPrefetch but that did not fix the problem. I hope Internet speed is not the problem.

POSTED BY: Peter Burbery
Posted 3 years ago

Quiz 1, Problem 8. None of the answers seem to be correct. Am I missing something?

POSTED BY: Rohit Namjoshi
Posted 3 years ago

Attributes[f3] returns an empty list {} because f3 itself has no attributes permanently set for it. If within the definition of f3, there are calls to some built-in functions, the attributes of the built-in functions will work independently on the inputs being provided to the built-in function itself, regardless of the original inputs to the user-defined function. Within the function definition everything will get evaluated according to the "Standard Evaluation Procedure" which will take into account the attributes of the built-in function. (This tutorial on "Evaluation of Expressions" may explain some of the process, and the concept of assigning attributes, a little more https://reference.wolfram.com/language/tutorial/EvaluationOfExpressions.html).

POSTED BY: Updating Name

Thank you! This is a great help.

POSTED BY: Peter Burbery
Posted 3 years ago

Hi Peter,

wolfieSay = ResourceFunction["WolfieSay"];
wolfieSay["Hello"]

enter image description here

resourceFunctionToSymbol[rfName_String, symbolName_String] := (ClearAll@symbolName; 
  Evaluate@Symbol[symbolName] = ResourceFunction[rfName];)

resourceFunctionToSymbol["Alphametic", "myAlphametic"]

myAlphametic["SEND+MORE=MONEY"]
(* {{{"D" -> "7", "E" -> "5", "M" -> "1", "N" -> "6", "O" -> "0", 
   "R" -> "8", "S" -> "9", "Y" -> "2"}, "9567+1085=10652"}} *)
POSTED BY: Rohit Namjoshi

I have been working on a program that takes a resource function name as a string for input and then it assigns the name of the resource function to ResourceFunction[name_input]. The hard part is figuring out how many arguments a function receives, particularly if it is overloaded. Is there a simple way to figure out how many arguments a function takes (The multiple numbers of arguments a function takes is the hard part). I was trying to use the function ExpressiontoFunction to help me with my program. I want to help with the process of defining every single Resource Function I download defining it in a package on my computer and automate the process. For example, let's say I have the ResourceFunctions WolfieSay, Alphametic, and FunctionOverview. I would like to be able to type ProgramDefineNewResourceFunctionGlobal["WolfieSay"] and then output a definition where instead of having to type ResourceFunction["WolfieSay"] every time I can simply type WolfieSay[stuff I want to communicate]. It may not be possible but is something I am interested in creating. I would then like to be able to do the same thing with Alphametic and FunctionOverview.

POSTED BY: Peter Burbery

Great point. And the example is really telling. Thank you! M

Posted 3 years ago
Sum[x, y]
(* x y *)

Perhaps you meant

Plus[x, y]
(* x + y *)

Consider

f[x_, y_] := If[x > 0, Plus[x, y], Sin[x*y]]

What Attributes should f implicitly have?

POSTED BY: Rohit Namjoshi

Is there a relation between the attributes of a user-built function f (if none of attributes have been assigned to it), to the attributes of built-in functions included in f? And specifically, why Attributes[f3] returns {} if it does exactly what the Sum does?

f3[x_, y_] := Sum[x, y];
Attributes[f3] ={}..

Probably, the answer should be obvious: when M evaluates Sum, it deals with the attributes of Sum. But this still may trigger some extra question (say, about a possible conflicts between attributes assigned to f3, and the existing attributes of built in functions). Hence, I would appreciate your take on this issue. Thank you. M

Posted 3 years ago

Hi Peter,

Perhaps I am not understanding what you are trying to do. What is wrong with

squared = Function[x, x^2] (* or squared = #^2& *)

squared[5]
(* 25 *)

ClearAll[squared];
pureToNamed[named_, pure_] := named = pure

pureToNamed[squared, Function[x, x^2]]
squared[5]
(* 25 *)

Your example works fine too

SetDelayed[seventhpower,Function[x,x^7]]
seventhpower[2]
(* 128 *)
POSTED BY: Rohit Namjoshi

I am working with pure function and am wondering if there is a way to make a named function out of a pure function. For example is there a way to take the pure anonymous lambda function Function[x,x^2] and SetDelayed to create Square[x_]=x^2. I am working on creating a function that takes in a function name and a pure function and creates a function out of it. This is my goal

 PuretoNamedFunction(sample name)[functionname_,purefunction_]:=
"solution here"

. I tried SetDelayed[seventhpower,Function[x,x^7]]. I also tried using Block and With.

POSTED BY: Peter Burbery
Posted 3 years ago

Thank you, that helps a lot! Have a good one.

POSTED BY: Tom Lieber

I believe the author wrote out:

EntityProperty["City", "Area"]

and evaluated using Shift+Enter to get the output in a separate cell (to copy and paste) or selected the code snippet and evaluated in place from the menu Evaluation -> Evaluate in Place or shortcut keys Shift+Ctrl+Enter (Windows) or Cmd+Return (Macintosh).

If you hover over a formatted EntityProperty, it will show you the InputForm that you could write out in full, in the tootip.

Posted 3 years ago

I get that, thanks. I'm just wondering if there's a shortcut for writing the italic-yellow-box form of an attribute. Because yes, if you type "area of New York City" in a natural language entry box you can get area of New York City result, but much of the time, notebooks don't include it in that form.

For example, this week's quiz has:

enter image description here

And yesterday's example notebook has:

EntityValue of fertilizer production,

So, is it the case that all these notebook authors created those cells by typing "area of New York City" then completely reformatting the expressions using copy/paste… or is there a way to type a property directly?

POSTED BY: Tom Lieber

The yellow box with the italic print is just one way of representing entity properties. Entity properties are also represented as plain strings within quotes. These string names for the properties are accessible from the auto-completion menu that comes up when you type in [" immediately following the entity. For example: enter image description here

You can also get to the entire Wolfram Language interpretation of both Entity and the EntityProperty by typing in a natural language query after the = sign in an input cell: enter image description here

and then hit enter to see the following: enter image description here

An EntityProperty is always associated with an Entity. So if you are interested in a property, look at the documentation for the Entity you think it will be associated with. If I am interested in a property like "Literacy Rate", it would be a property I would associate with an Entity like a "country". So I could look within the "Properties" section at https://reference.wolfram.com/language/ref/entity/Country.html

Similarly "Elevation" sounds like a property associated with a mountain. So I could look for it at http://reference.wolfram.com/language/ref/entity/Mountain.html or type in : enter image description here

Hope this helps.

Posted 3 years ago

How can I type the yellow-box form of a property? They appear italic in the example notebook, like "electric charge".

When I press ctrl+= and type elevation for example, I sometimes get a gray box that when confirmed turns into a string "Elevation". Sometimes I get "No Wolfram Language translation found." Never do I get a property that looks like what's in the example notebook.

An instructor answered that if you type EntityProperty["River", "Length"], then the property is printed in italic-yellow-box form like in the example notebook. Does that mean that the example notebook was written by evaluating EntityProperty and copy/pasting? What about "fertilizer production" which was used in the last example today, for which I don't know the entity class it applies to?

POSTED BY: Tom Lieber

Hi Brad,

The zip file in the folder are updated notebooks that accompany the lecture videos. The "02Discussion" notebook was extra material from Vamshi for that day. Last week's Q&A digest along with Vamshi's review notebook from Friday are now available. Also, Duncan has supplemental materials for tomorrow's session on Entities following the video lecture. His notebook has also been added to the shared folder.

I should have the poll notebooks which I think are the "discussion" materials you are looking for up in the next day or so.

Please let us know if you have any other questions.

POSTED BY: Wolfram U
Posted 3 years ago

I have noticed that the files at this link ( https://amoeba.wolfram.com/index.php/s/LWsQDeqpLeEW5MW?path=%2F ) have not been added to for several days. Is there somewhere else I should be looking for the most recent "Discussions" notebooks?

Thanks

POSTED BY: Brad Vance

Hi @Francisco Gutierrez. I have confirmed your registration, and your emails are being sent to a yahoo email address. If you contact us at wolfram-u@wolfram.com, we can help you manage your registration settings.

POSTED BY: Jamie Peterson

I am registered in the course, but I am not getting the messages with the links to be able to attend the sessions.

You can view the recordings on the series signup page here.

The link to the notebooks will be included in the reminder email.

UnitConvert would work as follows:

In[19]:= UnitConvert[Quantity[1, "SpeedOfLight"], "PlanckLength/second"]
Out[19]= Quantity[1.8549*10^43, ("PlanckLength")/("Seconds")]

In[18]:= UnitConvert[Quantity[1, "UniverseMass"], "PlanckMass"]
Out[18]= Quantity[7.*10^60, "PlanckMass"]

TargetUnits is an option available for use with visualization functions e.g. ListPlot

Symbolic computations can definitely be performed with Quantity expressions as described here: http://reference.wolfram.com/language/tutorial/SymbolicCalculationsWithUnits.html

Sorry, I did not find the links to recording in the aforementioned page. What is the total number of posted recordings? In my email I found just 5. Is it all? Thank you. M

  1. What is the total number of posted recordings? In my email I found just 5. Is it all? Please post the link to recordings.
  2. Could you please post a link to the most recent updates of the notebook files.

Thank you. M

Part of the answer to my question is that the trapezoid elements in GraphElementData are set up for use with vertices as shown here:

Table[EdgeTaggedGraph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3, 
   3 \[UndirectedEdge] 1}, VertexShapeFunction -> s, 
  VertexSize -> 0.2, PlotLabel -> Style[s, 9]], {s, 
  GraphElementData["VertexShapeFunction", "Rounded"]}]

https://wolfram.com/xid/0cpsizfbsjq8gq-lsz53w

POSTED BY: Kathryn Cramer

I was am interested in converting various quantities such as the mass of the observable Universe, the number of particles in the observable Universe, the age of Universe, the speed of light, the surface area of the Universe as a ball and its cross-section, the width and volume of the Universe to Planck units. I am wondering if there is a way to specify with UnitConvert to convert to Planck length, time, and mass. I have read the documentation on UnitConvert and am wondering if there is a way to go about my project. The following code returns an error:

UnitConvert[{Quantity[1, "SpeedOfLight"],Quantity[1, "UniverseMass"]}, 
 TargetUnits -> {Quantity[1, "PlanckLength"], 
   Quantity[1, "PlanckMass"], Quantity[1, "PlanckTime"]}]

I was wondering if there is a way to specify PlanckUnits as the UnitSystem or define my own unit system. I found an example that relates to NonDimensionalTransform documentation. enter image description here

POSTED BY: Peter Burbery

The reason you get an empty list is because the == condition is failing. EntityValue[#,"Countries"] comes back as a list and so you never find a match for the list against the single entity of Entity["Country", "UnitedStates"]

Try instead:

Select[EntityList[EntityClass["NuclearReactor", All]], 
     MemberQ[EntityValue[#, "Countries"], 
       Entity["Country", "UnitedStates"]] &]

or

EntityList[
 FilteredEntityClass["NuclearReactor", 
  EntityFunction[c, 
   MemberQ[c["Countries"], Entity["Country", "UnitedStates"]]]]]
Posted 3 years ago

I am working on mapping the nearest nuclear reactor and first aim to select nuclear reactors that are in the United States. I have the following code: Select[EntityList[EntityClass["NuclearReactor", All]], EntityValue[#, "Countries"] == Entity["Country", "UnitedStates"] &]

but receive an empty list as a result for some reason. How can I select all nuclear reactors in the US? I would like to use the Select function.

POSTED BY: Updating Name

Thank you that fixed it!

POSTED BY: Peter Burbery
Posted 3 years ago

Re-read your last question. I think this is what you were looking for

Style[#, If[#, Green, Red]] & /@ stringlist

enter image description here

POSTED BY: Rohit Namjoshi
Posted 3 years ago

Hi Peter,

The "obvious" ways don't work

mylist /. Except[_Integer] :> "Real"
mylist /. _?(Not@IntegerQ[#] &) :> "Real"

both result in "Real" because the pattern matches at level 0. Have to use Replace and specify a levelspec

Replace[mylist , Except[_Integer] :> "Real", 1]
Replace[mylist , _?(Not@IntegerQ[#] &) :> "Real", 1]
(* {1, "Real", 2, 3, "Real", "Real"} *)

Need to specify the rules individually

mylist /. {_Integer -> "Integer", _Real -> "Real"}
(* {"Integer", "Real", "Integer", "Integer", "Real", "Real"} *)

stringlist is not a List of String,

stringlist = {True,False,False,True,False,False,True,False,True,True,False} 
Head /@ stringlist
(* {Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol} *)

Since they are either True or False

Style[If[#, Green, Red]] & /@ stringlist
POSTED BY: Rohit Namjoshi

How do choose not as a condition with patterns? For example,

mylist={1,1.5,2,3,3.14,2.718}
list /. _! Integer :> "Real"

I was also wondering how to replace all integers with "Int" and all reals with "Real" in one line. I think there is a way to use replace with lists

mylist /. {_Integer, _Real} :> {"Integer", "Real"}

The previous code does not work. How would I use conditions and patterns to replace each element of string list equal to False with Style[False, Red] and each element of string list equal to True with Style[True, Green]?

stringlist={True,False,False,True,False,False,True,False,True,True,False}

Example Notebook->

POSTED BY: Peter Burbery

Each session is recorded. You can access the recordings from the Study Group series landing page, by clicking the link to each daily section. Registration is required. Here is a link to Day 2: https://www.bigmarker.com/wolfram-u/dsg15-iterations-counting-and-lists

POSTED BY: Jamie Peterson
Posted 3 years ago

I didn't see a recording for Day 2. Is there one?

POSTED BY: Updating Name
Posted 3 years ago

Very cool trick. I had no idea we had that much control over the appearance of a graph.

POSTED BY: Rongoetz

Here is something to get you started:

Graph[{1 -> 2, 2 -> 3, 3 -> 1}, 
 EdgeShapeFunction -> 
  Function[{coord, edge}, 
   Tooltip[
    Triangle[{First[coord], Last[coord] + {0, 0.04}, 
      Last[coord] - {0, 0.04}}], {First@coord, Last@coord}]]]

The EdgeShapeFunction needs to be set to a pure function that will take the coordinates of the edge line and create something closer to your requirements. In the above example I created a triangle. The Tooltip is only intended to show what the inputs to the pure function look like when it tries to draw the edge.

I am in the Programming Study Group.

I have a practical problem I am trying to solve. I am trying to make a network graph on a hexagonal/triangular grid. All of the edges are directional and I need to have each edge represented by a symmetrical trapezoid where the edge thickness is narrower at the originating point than at the destination point on the grid. I was hoping EdgeShapeFunction would allow me to do this, but while GraphElementData knows about trapezoids, Wolfram Language doesn't seem to want to let me use a trapezoid as an EdgeShapeFunction. Is there another way to accomplish this?

POSTED BY: Kathryn Cramer

The weekly quizzes will be announced on Fridays, and the exercises will be announced during the final week of the Study Group. Watch your email notifications for direct links to recordings, the quizzes and exercises, and additional resources.

POSTED BY: Jamie Peterson

For this Study Group, the certification refers to Wolfram Technology Certified Level 1 for proficiency in using the Wolfram Language. This Level 1 certification is equivalent to the one you can earn by taking the Wolfram Language Level 1 exam on the Wolfram U website.

POSTED BY: Jamie Peterson

Here is the series landing page, where you can see details and from where all session recordings will be linked: https://www.bigmarker.com/series/daily-study-group-programming-tutorials/series_details

The weekly quizzes will be announced on Fridays, and the exercises will be announced during the final week of the Study Group. Watch your email notifications for direct links to recordings, the quizzes and exercises, and additional resources.

POSTED BY: Jamie Peterson
Posted 3 years ago

Can I have the link to the "Series 15 Programming Tutorials" webpage containing the exercises etc

POSTED BY: Doug Beveridge
Posted 3 years ago

What is the Level I Certification in, exactly? Is it different from the Wolfram Technology Level I Certification?

POSTED BY: Rongoetz

Right! Sorry for the error.

POSTED BY: Jamie Peterson
Posted 3 years ago

Download files again , this has been corrected .

POSTED BY: Doug Beveridge

The .nb files are Wolfram Notebooks. You can open and work with the notebooks with a free trial.

POSTED BY: Jamie Peterson

I have never participated in a webinar like this. The study materials .nb downloads. Don't look familiar or readable. What am I supposed to do with them?

POSTED BY: Jay Gourley
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract