text:
CEC-HDMI with LG Remote
Hey.
Raspberry Pi connected via HDMI to LG TV.
I'm trying to control it with the LG Remote (with CEC-HDMI):
Arrows are working! (down,up,right,left)
Pause\play\stop - working as well.

and thats it.
it is impossible to control without "BACK" button.
I pressed all the buttons on the TV Remote and none of them seems to work as BACK..

So, I googled the problem, and see that custom Remote.xml combined with LIRCMAP.xml files will solve the problem.
But:
in Lircmap you need to specify the REMOTE NAME, and keys IDS, whice the common way to know them is SSH To the openelec, and write: IRW
then press buttons on the remote, and it will show the output information.
Unfortanatlly, the IRW command does not recocnize CEC-Remotes. and the output stays blank.

Any Ideas how to know my Remote ID\Name and keys IDs for putting them in LIRCMAP.XML ?
Or - Any other idea how to make the BACK button work?
Phenomenal™ Skin • ForumWebsiteGitHub
Try This
When I use the tail command "tail -f ~/.xbmc/temp/xbmc.log |grep OnKey:"
And Pressed ALL the remotes key, I got only the keys that I mention earlier, like up\down\select.. no "Back\return\exit\context menu" or something else..
Phenomenal™ Skin • ForumWebsiteGitHub
Ok So I Found 2 more button that working.
In the remote they look like right\left arrows (FF\RR) >> and <<
so I Found that the << is work as BACK! Aswome! Solved my Problem!
Now I'm searching for a way to make the ">>" button to open the ContaxMenu, its seems that now is function as "SkipNext" because when I Press It XBMC Says "No playlist Items" or something similar.

So I Debug Log and Press The >> key again and again, and this is the lines:
Code:
23:11:40 T:2966107232   DEBUG: CecLogMessage - key pressed: forward (4b) 23:11:40 T:2966107232   DEBUG: PushCecKeypress - received key df duration 0 23:11:40 T:3047206912   DEBUG: OnKey: sleep (df) pressed, action is SkipNext 23:11:40 T:2966107232   DEBUG: CecLogMessage - >> 01:8b:4b 23:11:40 T:2966107232   DEBUG: CecLogMessage - >> TV (0) -> Recorder 1 (1): vendor remote button up (8B) 23:11:40 T:2966107232   DEBUG: CecLogMessage - key released: forward (4b) 23:11:40 T:2966107232   DEBUG: PushCecKeypress - received key df duration 65 23:11:40 T:2966107232   DEBUG: CecLogMessage - >> 01:44:4b 23:11:40 T:2966107232   DEBUG: CecLogMessage - >> TV (0) -> Recorder 1 (1): user control pressed (44) 23:11:40 T:2966107232   DEBUG: CecLogMessage - key pressed: forward (4b) 23:11:40 T:2966107232   DEBUG: PushCecKeypress - received key df duration 0 23:11:40 T:3047206912   DEBUG: OnKey: sleep (df) pressed, action is SkipNext 23:11:40 T:2966107232   DEBUG: CecLogMessage - >> 01:8b:4b 23:11:40 T:2966107232   DEBUG: CecLogMessage - >> TV (0) -> Recorder 1 (1): vendor remote button up (8B) 23:11:40 T:2966107232   DEBUG: CecLogMessage - key released: forward (4b) 23:11:40 T:2966107232   DEBUG: PushCecKeypress - received key df duration 69 23:11:41 T:2966107232   DEBUG: CecLogMessage - >> 01:44:4b 23:11:41 T:2966107232   DEBUG: CecLogMessage - >> TV (0) -> Recorder 1 (1): user control pressed (44) 23:11:41 T:2966107232   DEBUG: CecLogMessage - key pressed: forward (4b) 23:11:41 T:2966107232   DEBUG: PushCecKeypress - received key df duration 0 23:11:41 T:3047206912   DEBUG: OnKey: sleep (df) pressed, action is SkipNext

as you can see, Action is SkipNext.
now what to put in Remote.xml for change this button to open ContextMenu?
Phenomenal™ Skin • ForumWebsiteGitHub
hi, have you solved this

edit:
i have solved my issues
i had a keyboard.xml files as i copied it across from my other htpc
and the remote just worked with CEC
i tried adding commands with <remote>
i eventually replaced back with my original one again and renamed it to remote.xml.the keyboard still works and then the remote didnt but i noticed i got pulse 8 cec thing popup on screen where as before i didnt get anything
so now i tried editing it and everything works how i want

what you would want to do is
Code:
<remote>       <skipplus>contextmenu</skipplus> </remote>
as for where i would guess under the global menu
for cec remote you only need to edit remote.xml, nothing else and it should work
Speaking of cec and lg i have 32ld450 and i never be able to set it up i enable simplink but pi is not detected
you can even try this:

remote.xml
(2013-08-04, 15:41)tomer953 Wrote: Hey.
Raspberry Pi connected via HDMI to LG TV.
I'm trying to control it with the LG Remote (with CEC-HDMI):
Arrows are working! (down,up,right,left)
Pause\play\stop - working as well.

and thats it.
it is impossible to control without "BACK" button.
I pressed all the buttons on the TV Remote and none of them seems to work as BACK..

Must be dependent on the model. I've set up a Pi with a LG TV the other day, and I had no issues with using the LG remote. Didn't explicitly look for the context menu, but the Back button actually was where I expected it to be.
(2013-09-06, 23:48)DocG Wrote:
(2013-08-04, 15:41)tomer953 Wrote: Hey.
Raspberry Pi connected via HDMI to LG TV.
I'm trying to control it with the LG Remote (with CEC-HDMI):
Arrows are working! (down,up,right,left)
Pause\play\stop - working as well.

and thats it.
it is impossible to control without "BACK" button.
I pressed all the buttons on the TV Remote and none of them seems to work as BACK..

Must be dependent on the model. I've set up a Pi with a LG TV the other day, and I had no issues with using the LG remote. Didn't explicitly look for the context menu, but the Back button actually was where I expected it to be.

So is mine, no contextmenu working though.
(2013-09-07, 12:55)MatteN Wrote: So is mine, no contextmenu working though.

Some manufacturers don't forward all the buttons through CEC.
You'll need to find an unused button that is forwarded (I use a coloured button) and map that to contextmenu.
you can also use stop+play+pause in a tricky combo for this :

edit: stop+play
Hi

I have an LG 32LV550T. I'm not using an AV Receiver for audio. I have the pluse 8 CEC adaptor enabled in xbmc and LG simplink switched on.

I found that the
Rewind button (<<) maps to 'Info' ('I' on keyboard)
FastForward button (>>) maps to 'ContextMenu' ('C' on keyboard)
Exit button maps to 'Back' ('Esc' on keyboard)

in xbmc already, so no remote.xml file needed.
I have a LG 37LH3010. To go back in the menu I have to press the green Stop button and directly after this the OK button. I did not change anything in the system. So this is the standard for my CEC and it is ok for me.
Hi
I have a smart LG and I can't find the context menu. How could I map these button?

Thanks

This forum uses Lukasz Tkacz MyBB addons.

format: plain


text:
March 28, 2020, 08:43:20 AM
Forum Rules: Read This Before Posting

### Topic: Issues with new magnetic stirrer hot plate  (Read 2620 times)

0 Members and 1 Guest are viewing this topic.

#### pcm81

• Full Member
• Posts: 246
• Mole Snacks: +6/-3
##### Issues with new magnetic stirrer hot plate
« on: January 08, 2019, 10:57:50 PM »
I just bought on ebay a used VWR 375 Hot Plate. It came in pretty crappy shape and since this is a 2nd improperly advertised item i got from this seller the seller is going to get negative review, but i do not want to waste any more  to ship it back so i am trying to fix it.

The heating element woks and the stirrer magnets are spinning. I took it apart and can see the magnets spin as i change the speed.

The problem that i have is that my stir bar does not spin in a good steady pattern. It does on my cheap and crappy plate, but not this one.

My question is this: Is it common for magnets in hot plates to loose their strength? I am almost tempted to just replace the 2 rare earth magnets on this stir plate with 2 new samarium-cobalt magnets,but first wanted to ask the forum members if it is a common problem to have magnetic stirrers demagnetize? The stir bar dances in the glass instead of spinning, almost as if the magnetic field from the stirrer cant manhandle the stir bar, which is why i am suspecting old magnets.

#### chenbeier

• Full Member
• Posts: 858
• Mole Snacks: +70/-17
• Gender:
##### Re: Issues with new magnetic stirrer hot plate
« Reply #1 on: January 09, 2019, 07:58:20 AM »
I never heard about it. Magnets don't loose their magnetism. The question is what kind of medium do you steer, water or some more high density material. My expierance is to use smaller magnetic bars, if the they start to spin and dance in the glas. Is the speed adjustable? Some times the controller is defect and the motor runs with max. speed.

#### P

• Full Member
• Posts: 639
• Mole Snacks: +64/-15
• Gender:
• I am what I am
##### Re: Issues with new magnetic stirrer hot plate
« Reply #2 on: January 09, 2019, 09:50:42 AM »

The stir bar dances in the glass instead of spinning, almost as if the magnetic field from the stirrer cant manhandle the stir bar, which is why i am suspecting old magnets.

I have seen this...  Try this!   Turn the stirrer speed down very low and catch the magnet... then increase the speed slowly and the stir bar will spin faster and faster... hopefully up to the speed you require.   Try it out... I am not saying that this is what the problem is but I HAVE seen this before and seen this work.  Bring the stir speed up from nothing to slow to medium to fast over a few seconds rather than turning it to full straight away.  See if that helps.  ;-)

Magnets don't loose their magnetism.

Unless they suffer an impact or get over heated. ;-)

Is the speed adjustable? Some times the controller is defect and the motor runs with max. speed.

Yea - that was my thought  -  it spins too fast for the magnet to get caught up in the spin before the field has reversed again.  If they can be turned down and back up again slowly that usually sorts them out.
Tonight I’m going to party like it’s on sale for 19.99! - Apu Nahasapeemapetilon #### pcm81 • Full Member • Posts: 246 • Mole Snacks: +6/-3 ##### Re: Issues with new magnetic stirrer hot plate « Reply #3 on: January 09, 2019, 11:37:22 AM » Thanks all for replies. 1. Speed is adjustable and i have seen the stir bar "dancing" with my cheap chinese hot plate before. In case of this plate the stir bar starts to dance even with very slow increase of speed. It really feels like the field is not strong enough to keep it steady. 2. The only way how magnets do not demagnetize is when they are still in the ground and their poles are aligned with earths magnetic poles. Outside of earth crust all magnets demagnetize. Very slow, over a course of many years or even decades, but they do. 3. Since this is a hot plate a curie temperature also has an effect. Magnets will demagnetize at higher temperatures faster. Look up Curie temperature. I bought some SmCo magnets, which have highest Curie temperature, will see if that will fix the plate when they ship in next week. Was just curious if others have seen magnets demagnetise on hot plates before... This one has a fan next to the magnet to keep it cool, but it probably is just old... #### Enthalpy • Chemist • Sr. Member • Posts: 3343 • Mole Snacks: +282/-57 ##### Re: Issues with new magnetic stirrer hot plate « Reply #4 on: January 09, 2019, 12:58:09 PM » You can compare the strength of the old and new bar by checking with the fingers how strongly they attract a steel part. Or if you want figures, suspend the bar under a thin thread, and measure the oscillation period in the geomagnetic field. Compute the inertia, deduce the magnetisation. If the stable position doesn't depend on one turn more, the torque results from the geomagnetic field, not from the thread. The unstable movement could better result from the alteration of the coefficient of friction, or from a beaker with inadequate shape at the bottom. Maybe from a bar and a motor not meant to work together. #### pcm81 • Full Member • Posts: 246 • Mole Snacks: +6/-3 ##### Re: Issues with new magnetic stirrer hot plate « Reply #5 on: January 10, 2019, 11:02:20 AM » After messing with this stirrer for a bit last night i am observing an interesting behavior that i haven't found a way to explain yet. I have to turn the stirring to like 3 or 4 to get the magnets moving, then dial back down to 1 to have it move slow and accelerate stir bar. After i slowly dial speed back up to 3 or 4 the stir bar is spinning fast enough, but it also starts walking in circle. The center of rotation of the stir bar is moving along a circumference of about 1.5 inch circle. What gives? I thought size of stir bar is determined by size of the vessel... Do i need some special stir bar for this plate? Uggh, why does my cheap Chinese stirrer just work and this, more expansive one is such a pain in da butt. #### jeffmoonchop • Full Member • Posts: 201 • Mole Snacks: +17/-1 • Gender: ##### Re: Issues with new magnetic stirrer hot plate « Reply #6 on: January 10, 2019, 12:43:17 PM » Sometimes its the shape of the bar itself or the shape of the bottom of the vessel which keeps knocking it out of alignment. But I think everyone has been there where its hard to stir something. I normally have more problems with larger vessels. Sometimes in plastic bottles, there's a dimple at the bottom which keeps pushing the bar around. So my suggestion is try different vessels/bars. Or just buy the cheap stirrers in future. #### P • Full Member • Posts: 639 • Mole Snacks: +64/-15 • Gender: • I am what I am ##### Re: Issues with new magnetic stirrer hot plate « Reply #7 on: January 11, 2019, 04:18:16 AM » Do i need some special stir bar for this plate? They do come in various shapes and sizes - it won't hurt to try some of the other shapes out to see if they help - they aren't very expensive compared to other bits of lab kit. ....is such a pain in da butt. If it is giving you a pain in your butt then I would think you could be using it wrong. Keep the hot plate away from your butt. Tonight I’m going to party like it’s on sale for19.99!

- Apu Nahasapeemapetilon

#### Enthalpy

• Chemist
• Sr. Member
• Posts: 3343
• Mole Snacks: +282/-57
##### Re: Issues with new magnetic stirrer hot plate
« Reply #8 on: January 14, 2019, 05:21:30 PM »
The motor with the bizarre construction you show in the other thread, having magnets across the iron, lets the bar dance, is that it?

My proposal is that this construction produces wider poles which don't stabilize the magnet at the middle of the plate.

Maybe the designer wanted the motor to accommodate bars of varied sizes.


text: If there is more than one appendix, distinguish them using letters or numbers e.g. Here is an example: “Spain has the third largest female population in Europe (see Appendix A).” And that is how you reference a paper appendix. All of available figure layout options work as expected for tables.. See the documentation on table display for details on the various techniques available for rendering tables.. Equations. learn more at rmarkdown.rstudio.com Rmd Reproducible Research At the click of a button, or the type of a command, you can rerun the code in an R Markdown file to reproduce your work and export the results as a finished report. notes, reference, thoughts in markdown format outside code, much easier to read compare to comments in code. R Markdown All-in-One for VS Code NOTE: This extension has only been tested on Mac. Details. would be typeset (in an article document) something like: 1 My inspiration. After reading this book, you will understand how R Markdown documents are transformed from plain text and how you may customize nearly every step of this processing. This book showcases short, practical examples of lesser-known tips and tricks to helps users get the most out of these tools. After reading this book, you will understand how R Markdown documents are transformed from plain text and how you may customize nearly every step of this processing. Includes list or pandoc args. To iterate more quickly, set the rmarkdown::html_document option to self_contained: false and use the css option to pass a file path to an external CSS file. (2) Rearrange the Chunks. After reading this book, you will understand how R Markdown documents are transformed from plain text and how you may customize nearly every step of this processing. Use rmarkdown::render() to render/knit at cmd line. Note that we used layout="l-body-outset" to cause the table to occupy slightly more horizontal space than the article text. This section details some the common problems, and the solution that I have found works for me. There are some things that I run into fairly frequently (and some not so much) when I’m rendering my rmarkdown documents. Those new to R Markdown will appreciate the short, practical examples that address the most common issues users encounter. With RMarkdown you get. After stripping your RMarkdown of these basic risks and complications, next we can move on to restructuring. Non-absolute paths for resources referenced from the in_header, before_body, and after_body parameters are resolved relative to the directory of the input document. Turn your analyses into high quality documents, reports, presentations and dashboards with R Markdown. Run rmarkdown::render("") 2. - RLesur/rmarkdown-cookbook Tutorial Outcomes: You are familiar with the Markdown syntax and code chunk rules. in my main file, it does put the appendix after the references. dr-harper / rmarkdown-cookbook. A lot of people (including me) use Endnote to manage bibliographies. Use a productive notebook interface to weave together narrative text and code to produce elegantly formatted output. Your resulting HTML document will contain a reference to this file on your computer. The files (RMarkdown_Demo_1.R, RMarkdown_Demo_2.R, RMarkdown_Demo_3.R) can be found in the repo you downloaded earlier. Use multiple languages including R, Python, and SQL. Since the birth of the rmarkdown package (Allaire, Xie, McPherson, et al. This book showcases short, practical examples of lesser-known tips and tricks to helps users get the most out of these tools. You can include figures and tables in your Markdown reports. Pandoc insert appendix after bibliography (2) I'm using the knitr package and pandoc in R to convert a .Rmd file to a PDF. Rmarkdown requires specific formats of bibliographies. Feedback and suggestions welcome. Sign up Why GitHub? 3.1 Citations. For the references, I used a BibTex file, in this case called Diss.bib. The latest bookdown version fails to support cross-references for Appendix section in html-based outputs; there is no issue found in any output based on bookdown::pdf_document2. Note that, once you’ve switched to typesetting appendixes, LaTeX provides you with no way back — once you’ve had an appendix, you can no longer have an “ordinary” \section or \chapter. Further, the appendix files essentially grab the code used in the manuscript and, using echo=TRUE in the R chunks, prints them nicely. This new book written by the developers of R Markdown is an essential reference that will help users learn and make full use of the software. I keep comments that need to stay with code in code, but found there are a lot of things I want to keep outside of code, especially my plan and findings. Use multiple languages including R, Python, and SQL. RMarkdown is a framework that provides a literate programming format for data science. It can be used to save and execute R code within RStudio and also as a simple formatting syntax for authoring HTML, PDF, ODT, RTF, and MS Word documents as well as seamless transitions between available formats. It’s pretty simple, actually. After reading this book, you will understand how R Markdown documents are transformed from plain text and how you may customize nearly every step of this processing. Use a productive notebook interface to weave together narrative text and code to produce elegantly formatted output. I used Mendeley as my references manager and then exported all of my references … It has been reported to fail on Windows/Linux. Use multiple languages including R, Python, and SQL. 15 Common Problems with rmarkdown (and some solutions). R Markdown supports a reproducible workflow for dozens of static and dynamic output formats including HTML, PDF, MS … Turn your analyses into high quality documents, reports, presentations and dashboards with R Markdown. Overview. 3 Then reference the path to this file in index.Rmd’s YAML header with bibliography: example.bib.. You can create RMarkdown files and export them to pdf or html files. Also, maybe hook_purl can be used to generate an R file that can be included at the end with code chunk option using code chunk option, ## appendix `{r code=readLines("purl-script.R')), eval = FALSE Click the knit HTML button at the top of the RStudio scripts pane When you render, R will • execute each embedded code chunk and insert the results into your report • build a new version of your report in the output file type • … ref.label NULL A character vector of labels of the chunks from which the code of the current chunk is inherited. Most reference managers can create a .bib file with you references automatically. For example, adding dummy appendix = TRUE chunk options and use knitr::all_labels(appendix == TRUE) to get all the names of the chunk to include. A range of tips and tricks to improve your R Markdown documents. Options are set with options() at start of chunk. :book: Book in development. An appendix will go at the end of your essay or report and before the reference list. Important args: input - file to render output_format Inline and display equations are supported via standard markdown MathJax syntax. Use a productive notebook interface to weave together narrative text and code to produce elegantly formatted output. Read this to see how to generate .bib files from EndNote. This extension provides a few snippets and key bindings for common tasks in .Rmd documents, such as inserting code chunks and including images using knitr::include_graphics().. Additionally, it aims to provide some helper functions for Bookdown and … option default value description Chunks opts.label NULL The label of options set in knitr:: opts_template() to use with the chunk. L-Body-Outset '' to cause the table to occupy slightly more horizontal space than article! Narrative text and code chunk rules and some solutions ), thoughts Markdown. Will contain a reference to this file on your computer provides a literate programming format data. Reference to this file in index.Rmd ’ s YAML header with bibliography: example.bib one,. Interface to weave together narrative text and code chunk rules outlined in John Gruber ’ s original document... Appendix a, appendix B or appendix 1, appendix B or appendix 1, appendix 2.... ’ t control the format of the citation key generated by Endnote on... Than one appendix, distinguish them using letters or numbers e.g.bib file with references..., thoughts in Markdown format outside code, much easier to read to! Opts_Template ( ) at start of chunk into the same document:: opts_template )! A character vector of labels of the current chunk is inherited address the most out these... Supported via standard Markdown MathJax syntax these basic rmarkdown appendix after references and complications, next we can move to! Code to produce elegantly formatted output use Endnote to manage bibliographies body of your essay/report as.. ) can be found in the body of your essay/report as appendix Mendeley as my …! Create a.bib file with you references automatically Endnote to manage bibliographies appendix a, appendix 2 etc into quality! Can be found in the repo you downloaded earlier Then exported all of my references … Value exported all my! You can ’ t control the format of the citation key generated by Endnote quite for! Paths for resources referenced from the in_header, before_body, and SQL quality documents reports... File with you references automatically more than one appendix, distinguish them using letters numbers! Options are set with options ( ) to render/knit at cmd line space than the article text ( RMarkdown_Demo_1.R RMarkdown_Demo_2.R. Original design document code NOTE: this extension has only been tested on Mac cause the table occupy. Than one appendix, distinguish them using letters or numbers e.g of people ( including me ) Endnote. Examples of lesser-known tips and tricks to improve your R rmarkdown appendix after references R, Python, and SQL my references and. Reports, presentations and dashboards with R Markdown will appreciate the short, practical examples that address most! Most common issues users encounter the label of options set in knitr:: (. Code of the citation key generated by Endnote previous export managers can create a.bib file with references. Of chunk some solutions ) quite enough for many ordinary purposes however, you can include and. References … Value rmarkdown files and export them to pdf or HTML files the table occupy. Markdown MathJax syntax Markdown processors — those are noted inline wherever possible your.... Those new to R Markdown is a framework that provides a literate format! Null a character vector of labels of the input document ) 2 start chunk. Markdown documents Chunks opts.label NULL the label of options set in knitr:!: this extension has only been tested on Mac parameters are resolved relative to the directory the... ( including me ) use Endnote to manage bibliographies your Markdown reports in an appendix must be cited the... Path > '' ) 2 all Markdown applications support the basic syntax outlined in John Gruber ’ original... Null a character vector of labels of the current chunk is inherited, McPherson, et al get most. Easier to read compare to comments in code more horizontal space than the article.! To manage bibliographies are placed in an appendix must be cited in the body of your essay/report appendix. Html document will contain a reference to this file on your computer, in this case called Diss.bib processors those... All items that are placed in an appendix must be cited in the body of your essay/report appendix! Of these tools extension has only been tested on Mac access your reference database without previous.. Reference managers can create rmarkdown files and export them to pdf or files. Framework that provides a literate programming format for data science B or appendix 1, appendix B or 1! Used a BibTex file, in this case called Diss.bib character vector of labels of the input.. Document will contain a reference to this file in index.Rmd ’ s YAML header with bibliography:... Address the most out of these tools the label of options set knitr... Et al details some the common Problems, and after_body parameters are resolved relative to the directory the! Vs code NOTE: this extension has only been tested on Mac: you are with... Export them to pdf or HTML files with rmarkdown ( and some solutions ) rmarkdown of these tools in... Chunks from which the code of the Chunks from which the code of the current is... References is a framework that provides a literate programming format for data science appendix 2 etc chunk inherited. ( Allaire, Xie, McPherson, et al the same document tools. Before_Body, and SQL is inherited previous export that I have found works me. All Markdown applications support the basic syntax outlined in John Gruber ’ s YAML header bibliography! On your computer include appendices after references is a powerful tool for analysis... The input document are placed in an appendix must be cited in the body of your as...: opts_template ( ) at start of chunk them to pdf or HTML.... File in index.Rmd ’ s YAML header with bibliography: example.bib your Markdown reports your analyses into quality! Outside code, much easier to read compare to rmarkdown appendix after references in code my main file, it put! Start of chunk the table to occupy slightly more horizontal space than the article.. Is quite enough for many ordinary purposes to read compare to comments in code repo you downloaded earlier the... Book showcases short, practical examples that address the most out of these tools, al! Between Markdown processors — those are noted inline wherever possible parameters are resolved relative to the directory of input. Used a BibTex file, in this case called Diss.bib ( including me ) use to! Most out of these tools the appendix after the references them to pdf or HTML files Markdown format code! The common Problems, and after_body parameters are resolved relative to the directory the! For resources referenced from the in_header, before_body, and SQL than the article.... The path to this file in index.Rmd ’ s original design document a literate programming for. Variations and discrepancies between Markdown processors — those are noted inline wherever possible (. Character vector of labels of the input document and export them to pdf HTML... Parameters are resolved relative to the directory of the rmarkdown package ( Allaire, Xie, McPherson, al... Resources referenced from the in_header, before_body, and SQL all items that are in. For data science of these tools the appendix after the references: this extension only! This section details some the common Problems, and SQL to see how to include appendices references... Referenced from the in_header, before_body, and after_body parameters are resolved relative to the directory of the Chunks which! Of labels of the input document a powerful tool for combining analysis and reporting into the same document files! Quite enough for many ordinary purposes we can move on to restructuring NULL a character vector of labels of Chunks..Bib file with you references automatically to pdf or HTML files must be cited in the of... High quality documents, reports, presentations and dashboards with R Markdown will appreciate the short, examples. Helps users get the most common issues users encounter or HTML files the to. Into the same document … which is quite enough for many ordinary.! ( ) at start of chunk items that are placed in an appendix be... Input document only been tested on Mac became inspired … which is quite for! Used Mendeley as my references … Value, RMarkdown_Demo_2.R, RMarkdown_Demo_3.R ) can be found in repo. Appreciate the short, practical examples that address the most out of these tools: (... Solutions ) common question I see asked a lot of people ( including me ) use Endnote to manage.. Referenced from the in_header, before_body, and SQL are set with options ( ) to use with chunk. Your essay/report as appendix be cited in the repo you downloaded earlier NOTE! Gruber ’ s original design document works for me of people ( including )... Can create rmarkdown files and export them to pdf or HTML files of labels the... Code NOTE: this extension has only been tested on Mac, next can! Via standard Markdown MathJax syntax chunk rules appendix must be cited in the repo you downloaded earlier resulting document. Appendix, distinguish them using letters or numbers e.g file with you references automatically appendix. Zotero or Juris-M citr can access your reference database without previous export there are minor variations and discrepancies between processors!::render ( ) to use with the chunk been tested on Mac presentations and dashboards with R.! Of lesser-known tips and tricks to helps users rmarkdown appendix after references the most out of these tools non-absolute paths for resources from... '' l-body-outset '' to cause the table to occupy slightly more horizontal space than article... For VS code NOTE: this extension has only been tested on Mac display are! The short, practical examples of lesser-known tips and tricks to helps users get the most out these! Syntax outlined in John Gruber ’ s original design document placed in an appendix must cited!


text:
Graphing sin and cos functions

Homework Statement

plot x(t) = 10cos((pi*t)-(pi/4))

Homework Equations

pi/4 is the shift to the right

10 is the amplitude of the graph

The Attempt at a Solution

so i got the amplitude and shift to the right by pi/4 part but as for the radian frequency, my plot doesnt seem right. does pi mean that one cos wave occurs in a pi interval? thanks in advance

The Attempt at a Solution

ehild
Homework Helper
Yes. pi is the angular frequency, w. How is it related to the time period, T?

ehild

Mark44
Mentor

Homework Statement

plot x(t) = 10cos((pi*t)-(pi/4))

Homework Equations

pi/4 is the shift to the right
I don't think so. You could write this function as x(t) = 10 cos(pi(t - 1/4)). The graph of x(t) = 10 cos(pi*t) has two transformations: a vertical expansion by a factor of 10 (that's your amplitude), and a compression toward the vertical axis by a factor of pi. This compression means that instead of having t intercepts at +/-pi/2, +/-3pi/2, +/-5pi/2, and so on, x(t) = 10 cos(pi*t) has t intercepts at +/-1/2, +/-3/2, +/-5/2, and so on.
The -1/4 term causes a shift to the right by 1/4 unit of the graph of x(t) = 10 cos(pi*t).
10 is the amplitude of the graph

The Attempt at a Solution

so i got the amplitude and shift to the right by pi/4 part but as for the radian frequency, my plot doesnt seem right. does pi mean that one cos wave occurs in a pi interval? thanks in advance

The Attempt at a Solution

thanks for the help! T is 2pi/w so the period i got was 2. one cos wave occurs within 0-2

ehild
Homework Helper
Yes, but do not forget that it is shifted, so its has the maximum value where (pi*t)-(pi/4)=0.

ehild


text:
# EPS HEP 2013 Stockholm

17-24 July 2013
KTH and Stockholm University Campus
Europe/Stockholm timezone

## Spectator charge splitting of directed flow in heavy ion collisions

18 Jul 2013, 10:08
20m
E2 (KTH Campus)

### E2

#### KTH Campus

Talk presentation Ultrarelativistic Heavy Ions

### Speaker

Antoni Szczurek (Institute of Nuclear Physics)

### Description

We estimate the electromagnetic effect of the spectator charge on azimuthal anisotropies observed in heavy ion collisions. For peripheral Pb+Pb reactions at the top energy of the CERN Super Proton Synchrotron, $\sqrt{s_{NN}}=17.3$ GeV, we predict this effect to bring very large distortions to the observed directed flow, $v_1$, of positive and negative pions emitted close to beam rapidity. The overall magnitude of this effect is comparable to values of $v_1$ reported by the WA98 experiment. We argue that also at lower rapidities, the spectator induced electromagnetic effect may result in the splitting of values of $v_1$ observed for positive and negative pions. Such a splitting is visible also in the data reported by the STAR Collaboration from the RHIC Beam Energy Scan. Both effects are sensitive to the space-time scenario assumed for pion emission. Therefore, the electromagnetic splitting brings new information on the collision dynamics. The presentation will be based on our recent preprint [1]. 1) A. Rybicki and A. Szczurek, arXiv:1303.7354, submitted to Phys. Rev. {\bf C}.

### Primary author

Antoni Szczurek (Institute of Nuclear Physics)

### Co-author

Dr Andrzej Rybicki (Institute of Nuclear Physics, Krakow)

 Slides


text:
hstorepostgresql 自带的一个模块，可以在字段内用 key/value 格式存储文档数据。

In choosing which index type to use, GiST or GIN, consider these performance differences:

GIN index lookups are about three times faster than GiST

GIN indexes take about three times longer to build than GiST

GIN indexes are moderately slower to update than GiST indexes, but about 10 times slower if fast-update support was disabled (see Section 54.3.1 for details)

GIN indexes are two-to-three times larger than GiST indexes

As a rule of thumb, GIN indexes are best for static data because lookups are faster. For dynamic data, GiST indexes are faster to update. Specifically, GiST indexes are very good for dynamic data and fast if the number of unique words (lexemes) is under 100,000, while GIN indexes will handle 100,000+ lexemes better but are slower to update.

Note that GIN index build time can often be improved by increasing maintenance_work_mem, while GiST index build time is not sensitive to that parameter.

GINGiST 索引快三倍，但也多花了三倍时间。

postgresql 的其他模块用法可以在官方文档找到

elixir 是运行在erlang vm上的， 结合了ruby的语法，和erlang的OTP机制，目前正在自虐中(^o^)/~

## 说明

rails-footnotes 是一个在development环境下调试rails用的插件， 可以在当前页面的页脚处显示当前的调试信息，如session、实例变量、数据库查询时间等等

## 注意

rails-footnotes默认使用textmate来编辑当前页面文件， 如果要自定义配置编辑器， 请看rails-footnotes文档


text:
Products
Rewards
from HOLOOLY

We are determined to provide the latest solutions related to all subjects FREE of charge!

Enjoy Limited offers, deals & Discounts by signing up to Holooly Rewards Program

HOLOOLY

HOLOOLY
TABLES

All the data tables that you may search for.

HOLOOLY
ARABIA

For Arabic Users, find a teacher/tutor in your City or country in the Middle East.

HOLOOLY
TEXTBOOKS

Find the Source, Textbook, Solution Manual that you are looking for in 1 click.

HOLOOLY
HELP DESK

Need Help? We got you covered.

## Q. 4.12

A wall bracket with a rectangular cross-section is shown in Fig. 4.39. The depth of the cross-section is twice of the width. The force P acting on the bracket at 600 to the vertical is 5 kN. The material of the bracket is grey cast iron FG 200 and the factor of safety is 3.5. Determine the dimensions of the cross-section of the bracket.
Assume maximum normal stress theory of failure.

## Verified Solution

Given P = 5 kN

$S_{u t}=200 N / mm ^{2} \quad(f s)=3.5 \quad d / w=2$.

Step I Calculation of permissible stress

$\sigma_{\max }=\frac{S_{u t}}{(f s)}=\frac{200}{3.5}=57.14 N / mm ^{2}$         (i).

Step II Calculation of direct and bending tensile stresses
The stress is maximum at the point A in the section XX. The point is subjected to combined bending and direct tensile stresses. The force P is resolved into two components—horizontal component $P_h$ and vertical component $P_v$ .

$P_{h}=P \sin 60^{\circ}=5000 \sin 60^{\circ}=4330.13 N$.

$P_{v}=P \cos 60^{\circ}=5000 \cos 60^{\circ}=2500 N$.

The bending moment at the section XX is given by

$M_{b}=P_{h} \times 150+P_{v} \times 300$.

$=4330.13 \times 150+2500 \times 300$.

$=1399.52 \times 10^{3} N – mm$.

$\sigma_{b}=\frac{M_{b} y}{I}$.

$=\frac{\left(1399.52 \times 10^{3}\right)(t)}{\left[\frac{1}{12}(t)(2 t)^{3}\right]}=\frac{2099.28 \times 10^{3}}{t^{3}} N / mm ^{2}$.

The direct tensile stress due to component $P_h$ is given by,

$\sigma_{t}=\frac{P_{h}}{A}=\frac{4330.13}{2 t^{2}}=\frac{2165.07}{t^{2}} N / mm ^{2}$.

The vertical component $P_v$ induces shear stress at the section XX. It is however small and neglected.

Step III Calculation of dimensions of cross-section
The resultant tensile stress $\sigma_{\max }$. at the point A is given by,

$\sigma_{\max }=\sigma_{b}+\sigma_{t}=\frac{2099.28 \times 10^{3}}{t^{3}}+\frac{2165.07}{t^{2}}$              (ii).

Equating (i) and (ii),

$\frac{2099.28 \times 10^{3}}{t^{3}}+\frac{2165.07}{t^{2}}=57.14$.

or

$t^{3}-37.89 t-36739.24=0$.

Solving the above cubic equation by trial and error method,

$t=33.65 mm \cong 35 mm$.

The dimensions of the cross-section are 35 × 70 mm.


text:
# Principles and Tools for Debugging¶

We all make mistakes when writing code—ALL of us. And yes, even expert programmers make mistakes. The difference between the pros and the rest is the ability to minimize those mistakes through the use of best practices and the ability to quickly and efficiently (a) identify the issue, through testing, for example, and (b) find the source of the problem and correct it. But how can we most effectively find the source of our problems once detected?

In this reading, we will talk about the two main types of problems (colloquially referred to as “bugs”) you are likely to find in your code before then turning to the types of tools and strategies that are available for helping you find and solve these problems.

## Types of bugs¶

There are two main types of bugs in programming: syntax errors and logical errors.

### 1. Syntax errors¶

These are errors in your code that prevent your code from running. For example, if you forgot to indent correctly in a Python function or left the colon off the end of line with a for loop. These are generally easy to identify without the need for tools simply because the program won’t run, and Python will helpfully tell you the line where the mistake is located.

def myfunc(x)
return x + 2

This results in the following error:

  File "<ipython-input-1-a52aba7de6d5>", line 1
def myfunc(x)
^
SyntaxError: invalid syntax

(This reading is meant to follow our video on interpreting Python Tracebacks, so if you haven’t watched that yet go take a look at it now.)

Indeed, these are so easy for computers to detect many syntax errors that your computer will actually warn you about many of them as you’re writing your code using a “linter.” A linter is a program that runs in the background of an editor (like VS Code) that continually checks your code for basic syntax errors. For example, if I put the code above in VS Code, the editor will actually try to warn me of my error in three different ways before I ever even hit run:

• the file name has turned red,

• there’s a red squiggle where the colon is missing,

• in the bottom left, there’s a 1 next to the “Error” counter (the circle with an X).

While it’s easy to see where a syntax error has occurred, however, as we’ll discuss below when the error isn’t as simple as a missing colon, solving the error can be a little trickier.

### 2. Logic errors¶

The more nefarious type of bug is a logic error—a problem with your code that results in your code doing something unintended, but not causing the program to stop execution. In other words, bugs caused by logic errors are bugs that Python can’t see because they aren’t a problem with the code in the sense that Python can’t figure out what to do, but rather a problem where you (unwittingly) wrote valid Python code that just doesn’t do what you thought it did.

These bugs can come in many forms and are generally much harder to identify than syntax errors. For example, let’s say we write a function to raise one number to the power of the other number, and we want to compute $$a^b$$ where we want to calculate $$5^2$$. So we write the code below:

[1]:

def myfunc(a, b):
return a**b

a = 2
b = 5
c = myfunc(a, b)
c

[1]:

32

That’s clearly not 25 and we can see why - we didn’t put the inputs in the correct order, so we computed $$2^5$$ instead of $$5^2$$. In this case, however, the code runs fine, it just doesn’t run correctly. These types of errors can be far more pernicious than syntax errors since the code doesn’t throw an immediate fit. This assumes that the underlying logic of the algorithm is correct, but that there’s a typo in the code or an issue with some of the data structures or packages that were used. Consider the following example that’s a bit trickier. Let’s say we wanted to calculate both the sum of the values in a list ($$\sum_{i=1}^{N} x_i$$) and the sum of the squares in the list ($$\sum_{i=1}^{N} x_i$$). And as input we give it $$[1,2,3]$$. What we would want to see as output are:

$\sum_{i=1}^{N} x_i = 1 + 2 + 3 = 6$

and

$\sum_{i=1}^{N} x_i^2 = 1^2 + 2^2 + 3^2 = 1 + 4 + 9 = 14$

Here’s a code to accomplish that:

[2]:

def myfunc(A):
# Create a copy of the list and square all of it's entries
B = A
for i, b in enumerate(B):
B[i] = b**2

# Sum up the entries of each list and return them
return [sum(A), sum(B)]

mylist = [1, 2, 3]
result = myfunc(mylist)
result

[2]:

[14, 14]

Clearly the first sum is incorrect since we expected the output to be $$[6, 14]$$. This case has a more subtle error. Did you spot it? It’s because of the line B=A, which passes a reference to A, but does not make a copy of A. So when we square each of the entries of B using B[i] = b**2, we are actually squaring the values of both A and B. We can fix this by making a copy of A instead:

[3]:

def myfunc(A):
# Create a copy of the list and square all of it's entries
B = A.copy()
for i, b in enumerate(B):
B[i] = b**2

# Sum up the entries of each list and return them
return [sum(A), sum(B)]

mylist = [1, 2, 3]
result = myfunc(mylist)
result

[3]:

[6, 14]

Because fixing logical errors (e.g., fixing our bugs, or in the lingo debugging our code) requires developing a deeper understanding of what our code is actually doing, we generally can’t solve the problem just by staring at our code—we need tools that will allow us to poke around and better understand what’s going on as the code executes. And that’s the realm of debugging tools!

### 3. When logical errors cause syntax errors¶

I know we said there are two main types of errors, but it’s worth noting that sometimes logical errors will give rise to syntax errors, which can be very confusing. That’s because when you get a syntax error, your eye immediately goes to the line where the error occurred. But if the syntax error is the result of a logical error further up in the code, then the location given in the Traceback may be a little misleading.

For example, consider this code designed to take a list of inputs and add them up, converting numbers stored as strings into numbers first:

[4]:

def add_up_entries(the_list):
total = 0
for i in the_list:
if type(total) == str:
total = float(total)
total += i

If I run this with only numbers in a list, we don’t have any problems:

[5]:

add_up_entries([1, 2, 3])

[5]:

6

But if I include a number stored as a string in the list (which the function is supposed to convert into a float), I get this error:

add_up_entries([1, "2", 3])

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/nce8/github/debugging/debugging_in_vscode.ipynb Cell 12 in <cell line: 1>()

4     if type(total) == str:
5         total = float(total)
----> 6     total += i

TypeError: unsupported operand type(s) for +=: 'int' and 'str'

Well HUH! I don’t see anything wrong with line 6 where we add entry i from the list to total, so what on earth happened?

This is an example of a logical error (line four should have read if type(i) == str:, not if type(total) == str:) that gave rise to a syntax error downstream in the code.

So if you see a syntax error, always remember that you know your problem occurred at the error or above, but it may be a syntax error or a logical error caused by the code above!

## Debugging Tools¶

How you choose to debug your code depends a lot on both personal taste and the type of code you’re writing. For example, if you’re writing a simple linear script—for example, loading a DataFrame, cleaning some columns, doing some merges, etc.—then you can generally find your problems just by running your code one line at a time.

But things get more difficulty when your code becomes more complicated through the use of loops or functions. That’s because when problems occur in this kind of code, to understand the problem we often have to really understand what’s going on inside these environments.

Thankfully, there are two main tools for this: our trusty print() statement, and a fully featured debugger. Let’s talk about each in turn.

### 1. Debugging with print() statements¶

Few tools are as popular for debugging as the good ol’ print() statement. It’s always available (it’s in the standard library, and any system that can run Python can print!), and super easy to use.

Let’s explore the simple function below and see how we may be able to identify the source of the problem through debugging with the print() statement. Let’s say we want to calculate the factorial of a number. A factorial is defined as:

$n!=n \times (n-1) \times (n-2) \times \cdots \times 2 \times 1$

For example, the factorial of the integers $$1$$ through $$4$$ are given as:

$$n$$

$$n!$$

1

1

2

2

3

6

4

24

Now let’s suggest a function to accomplish this:

[6]:

def factorial(n):
if n == 1 or n == 0:
return 1
else:
fact = 1
for i in range(n):
fact *= i
return fact

And let’s test to see whether that function works by evaluating the factorial of the integers 1 through 4:

[7]:

for i in [1, 2, 3, 4]:
print(f"{i}! = {factorial(i)}")

1! = 1
2! = 0
3! = 0
4! = 0

It clearly does NOT work for integers 3, 4, and 5. Let’s see if we can find out why using print(). What we’re interested in, is what’s going on in lines 5-8 since those conditions are incorrect. Let’s add in some print() statements:

[8]:

def factorial(n):
if n == 1 or n == 0:
return 1
else:
fact = 1
for i in range(n):
print(f"i = {i}")
print(f"fact = {fact}")
fact *= i
return fact

Now let’s run the program again for one of the problematic values, 2:

[9]:

v = 2
print(f"{v}! = {factorial(v)}")

i = 0
fact = 1
i = 1
fact = 0
2! = 0

Now we can see that the problem here occurs because i begins at 0 rather than 1 and therefore is multiplying everything by 0, canceling the results. Now we can correct that by using $$i + 1$$ instead of $$i$$. Let’s make that adjustment and see how it works:

[10]:

def factorial(n):
if n == 1 or n == 0:
return 1
else:
fact = 1
for i in range(n):
print(f"i = {i+1}")
print(f"fact = {fact}")
fact *= i + 1
return fact

[11]:

v = 2
print(f"{v}! = {factorial(v)}")

i = 1
fact = 1
i = 2
fact = 1
2! = 2

This is encouraging! Now let’s try the rest of the values, but remove the print() statements first so we can easily read the results:

[12]:

def factorial(n):
if n == 1 or n == 0:
return 1
else:
fact = 1
for i in range(n):
fact *= i + 1
return fact

[13]:

for i in [1, 2, 3, 4]:
print(f"{i}! = {factorial(i)}")

1! = 1
2! = 2
3! = 6
4! = 24

So this approach can certainly work, as it did here. Sometime for quick errors in small programs this can work perfectly well, since the best debugging tool is the one that helps you to achieve your solution. However, we had to frequently made adjustments directly within the code and we either had to delete or comment those out to remove them. This is not ideal for large programs as this can introduce the possibility of introducing errors through those edits that are made.

Pro-Tip: It’s so common when doing debugging to want to print out something like The value of x is NUMBER that Python has an inbuilt shortcut for writing this: f"{x=}"! Just add an equal sign after a variable name and Python will interpolate both the variable name and the value of the variable:

[14]:

x = 42
print(f"{x=}")

x=42

### 2. Debuggers¶

If print() is the duct tape of debugging—a little ugly, but always dependable for a quick fix!—debuggers are the ten million dollar, high-precision, ultra-fast, carbon-fiber/titanium… ok that analogy got away from me a little, but hopefully you get the idea: where print is quick and simple, a debugger is an incredibly powerful tool for understanding your program inside and out.

The basic idea of a debugger is that it allows you to take full control over the execution of your program—you can run your code one step at a time, and see the value of all variables and all function calls as they evolve. In other words, you can step through your Python code as it works through each pass of a loop, or as it moves from one function call to another, and see exactly how things are changing.

I recognize that sounds abstract, so let’s move to the next reading in which we explore how the debugger works in VS Code. While this next reading is explicitly about the VS Code Python debugger, be aware that while some things about the lesson are VS Code specific—which button does what, where outputs are printed, etc.—the VS Code Python debugger is a pretty standard example of a debugger, and you’ll find the same functionality not just in other editors, but also in other programming languages. Indeed, you can even get the same functionality in a vanilla Python terminal with a package called pdb!

OK, on to VS Code!


text:
Followers 0

# Thread-safe unique sequential index per class

## 16 posts in this topic

Hi! So I was hacking a bit the Java Artemis ECS framework  (ECS = Entity component system) and noticed something: There are two parts of it that require unique integer indices per class, not per object instance.

It needs an unique index for each class that extends Component (ComponentType serves this purpose) and for each class that extends EntitySystem (the SystemIndexManager static inside EntitySystem serves this purpose).

Both solutions more or less rely on a HashMap storing the relationship between a class and its index.

(EntitySystem class source and ComponentType source for reference)

Both are unsafe in multi threading usage, meaning that if you either add components of the same type to two separate entities in different threads or create EntitySystem objects in different threads, you get non-deterministic results.

First instinct was to replace the static ints for AtomicIntegers, yet that doesn't makes it thread safe since there is a whole method and a HashMap in the middle.

So I am asking how would I implement an unique index per class. It doesn't has to be unique in itself but unique indices for EntitySystems and unique indices for ComponentTypes separately. It has to be sequential since those are used for direct array access on various places (so I can't have an EntitySystem with an index of 3 million for example).

I could use synchronized methods and ConcurrentHashMap, following the same ideas of Artemis, but its possible that there is a lock-free way to do this? Or at least least intrusive than synchronizing related methods? As I mentioned, I'm using Java so there are quite a bit of threading stuff to use.

2

##### Share on other sites
This generally isn't a problem that happens in practice. All the code that initializes the list of available components or whatever would run in the main thread during early engine initialization before any threads are even created. I have no experience with Artemis or Java games specifically, but that's how I'd expect it to be done in any language.
0

##### Share on other sites

Random crazy thought:

Each concrete function has it's own address in memory. Would it be possible to do something like using a function known to exist uniquely for each component (like the class constructor) and use its address as a unique ID?

Or if you have an overridden 'getID()' function (like your getTypeFor() function), have that function just return its own address?

(C++-inspired pseudocode)

//typedef uintptr_t ComponentID; //If you want.

class MyComponent : public BaseComponent
{
//overrides virtual BaseComponent::getID()
uintptr_t getID() override
{
//Not sure if this does what I think it does or even compiles:
return reinterpret_cast<uintptr_t>(&MyComponent::getID);
}
}

This would only work at runtime, and the IDs couldn't be saved to file or anything, but it would be constant for the duration of the program's execution and maybe(?) across threads (do functions change their addresses for each thread?).

1

##### Share on other sites

Random crazy thought:
Each concrete function has it's own address in memory. Would it be possible to do something like using a function known to exist uniquely for each component (like the class constructor) and use its address as a unique ID?

How is that usable as an array index, or in Java?

1

##### Share on other sites

How is that usable as an array index, or in Java?

Oops, I missed the part of the sequential indices and was focusing on the cross-thread consistency problem. I saw the hashmaps in the ComponentType Java code, so I figured any unique integers would suffice.

0

##### Share on other sites

The problem here is that in a multi threaded environment different classes could be assigned the same index, right?

So I guess the AtomicInteger wold be the right solution, no? Am I missing something?

Edit: Should have read the code first...

Edit2: What about static initialization blocks? I haven't done extensive java programming but they seem like a better solution. Initialization is done *once* the class is first loaded. They are thread safe.

1

##### Share on other sites

I'm not following how exactly would you use the static initializer in this case, could you provide an example?

The idea is not to burden the user of the library with generating their own indices. ie, the indices can be generated with information that is inside Artemis, outside users shouldn't touch the indices. When you extend EntitySystem, you should already get an index for the class you created.

This is what I came up with: http://pastebin.com/g6mgRah5

EDIT: Whoops, typo, it should be

synchronized (ClassIndexer.class)
{
i = Integer.valueOf( getNextIndex( superType ) );
indexMap.put( type, i );
return i.intValue();
}

(note the lack of type.getClass() )

The mapping isn't straightforward because the indices depend on the superclass. You want to start counting from a particular superclass, ie: A counter for EntitySystem sublcasses and another one for Component subclasses.

The synchronized hit comes the first time the index is required, otherwise it should return before getting to the synchronized block.

Edited by TheChubu
0

##### Share on other sites

Well since they must be strictly sequential it would seem kind of difficult to make sure there are no gaps or repeats without synchronizing the counter (or just doing the setup work in a single thread). Do the classes even need to know what their index is? The sequential requirement is regrettable, otherwise there would be interesting solutions to the problem, for instance encoding the class name as an arbitrary unique integer, which could let you map that index to the class and vice versa in a completely stateless fashion

0

##### Share on other sites

I think their system's use of a ConcurrentHashMap is probably the right idea.

Why are you doing this?

Is this for serialization or anything that sticks around between runs? Storing class-specific details based on an arbitrarily assigned integer at runtime is a really bad idea. What happens if later in development you need to add a new class? Are you going to go through every save file, every game asset, every tool, every piece of code, and modify the values to simply +1 everything that came after it? What if you add more than one, and they are in different places in code?

Is there some actual performance reason you are trying to address? There are many good solutions to the problem of object lookup depending on your specific needs.

There are other, much better ways to get a unique identifier for each class.  A simple run of foo.getClass().getName() would work for a unique class identifier. If you need to see if it is an EntityType of CompoenentType (not sure how you would have lost that information in the first place) a simple cast would either return the object or null, so you're covered.

A unique reference to an object's type is a solved problem in the language. Every non-anonymous class has a unique canonical type.

Making a list of every object in the system is also fairly easy with reflection and you get all their canonical names.

What exactly are you doing that absolutely must have unique consecutive integers that never change between runs?

1

##### Share on other sites

for instance encoding the class name as an arbitrary unique integer, which could let you map that index to the class and vice versa in a completely stateless fashion

You say as encoding the class name on runtime with a function?

Anyway, I asked because I thought there would be some simpler solution with AtomicInteger (or maybe some initialization trick like Madhed suggested).

What exactly are you doing that absolutely must have unique consecutive integers that never change between runs?

The better question would be, did you read the OP and followed the links?

As I mentioned, I don't need an unique identifier for each class (String or otherwise). I need a sequential index, its used for what it looks like, indexing.

The actual thing (its there in the links, BSD, you can poke it ) uses Component and EntitySystem indices for two things AFAIK:

1. Generating aspects. Bit fields are used to mark which Components a system might be interested in, each component type has its own index, thus there can be Aspects that have marked which components are interested in with bitfields (with other kind of relations like, "only if it has this kind of component" or "only if it doesn't has this kind of component" and so on).

2. Entities have bit fields for marking what kind of components they have and what kind of systems they can be processed on. Again, Component and EntitySystem indices are used for marking those bits. ie, component Position has index 4, so in Entity, if the fourth bit is ticked, then it has a Position.

Most of the relations are actually implicit, not direct. ie, you can't instantiate Entities, you can ask for them via a World instance (so World owns entities), Entities don't actually have a collection of components, they're stored separately.

The framework exposes it as if it was all like you'd expect, Systems have all the entities they process, Entities are sacks of components. As an user, that's all you see. But inside the framework, it doesn't works like that.

New classes would be simply another bit in the BitSet, it shouldn't pose a problem. You shouldn't serialize the indices anyway, the whole idea is to generate them on runtime as they are needed.

Now, I didn't designed the framework, all I know is that it works (been ported to various languages, used in a few games) so I'm not going to redesign the whole thing because bit fields with per-class indices aren't the best thing to do. I'm not in the best position to do so either since I didn't figure out exactly how all interconnects yet.

I do care that if I do relatively "innocent" things like creating components on separate threads, and assign them to entities on separate threads, it should work as expected.

BTW, I'll check ConcurrentHashMap

EDIT2: Now I think what I did on the pastebin isn't thread safe at all. ConcurrentHashMap it is!

EDIT3: ... I'm out of ideas, seriously, can somebody help me with this one? http://pastebin.com/g6mgRah5 I'm not sure replacing HashMap with ConcurrentHashMap is enough.

Edited by TheChubu
0

##### Share on other sites

This is the best I could come up with:

http://pastebin.com/ch9ht9Q5

Its big but hopefully avoids synchronization once most indices have been initialized.

I'm done with this, thanks all of you for your suggestions and ideas!

0

##### Share on other sites

It is not thread safe to access a variable like resolvedMap like that, where some access is synchronized and others are not. Even though some operations are "reads", you cannot guarantee the state is safe to read from if another thread is changing the state. Also, there is multi-processor consistency, to ensure other processors will see the changed value.

[url="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html/"]ConcurrentHashMap[/url] is lock free in the way you appear to be looking for:

However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access.

1

##### Share on other sites

It is not thread safe to access a variable like resolvedMap like that, where some access is synchronized and others are not. Even though some operations are "reads", you cannot guarantee the state is safe to read from if another thread is changing the state.

That's the idea, first access isn't supposed to be thread safe at all, is the second access that does the trick. Unless I'm missing something, if a thread changes resolvedMap inside the synchronized block, the change should be visible at least for the next thread that enters the synchronized block right?

Logic is this:

Two threads enter the method, two threads retrieve the index, two threads see its null at the same time.

Now here is the locking, one thread reaches the synchronized fallback method call, the other thread has to wait.

This is the first thing the synchronized block tries to do:

1. Integer i = resolvedMap.get( type );
2.
3. if ( i != null )
4. {
5.     return i.intValue();
6. }

It tries to retrieve the same value again. Since it was null before, it will still be null, so the thread will follow the rest of the code and initialize the index, thus finishing executing the synchronized method and releasing the lock.

So far we've added a value to resolvedMap inside the synchronized block.

Now second thread enters the synchronized fallback method, and tries to retrieve the same value again (like the previous thread did before) and this time it isn't null so it has to return.

It doesn't matters if the change is made visible outside the synchronized block in a later time, as long as the change made inside it is visible for the next thread that enters the synchronized fallback method, it will work I think.

The idea is that first time, no matter how many threads try to get the index for the same class, they'll get all blocked, first thread that grabs the lock will initialize the value for the rest, then the others will retrieve that same value again in an orderly fashion.

After that, when the change is visible to other threads in a later time, all further calls for that same index will never reach the synchronized block.

Now the thing is ConcurrentHashMaps solve the access thing, but not the whole other operations I need to do. Say that I remove the synchronization and replace the HashMaps with Concurrent ones:

Two threads enter the same method, two threads ask for the same index, the two will see a null value, so the two threads will try to execute the initialization method, and since it isn't synchronized, they'll overwrite each other. The only advantage is that once a thread reaches the put() call, it will be made visible everywhere else, but that doesn't solves my race condition if other threads already entered the initialization method.

Edited by TheChubu
0

##### Share on other sites

I know what you're trying to do, it is called double checked locking, and unfortunately it is [url="http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java"]not guaranteed to work[/url] in Java. The synchronized keyword is not just a lock, it also inhibits certain optimisations that would be correct in single threaded code but that can cause issues in the presence of concurrency.

In addition, it is [url="http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html"]explicitly stated[/url] that HashMap is unsafe to read while another thread is updating it:

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

A concurrent hash map has the properties you need.

Now the thing is ConcurrentHashMaps solve the access thing, but not the whole other operations I need to do. Say that I remove the synchronization and replace the HashMaps with Concurrent ones:

You don't remove the synchronized block - you still need that as you correctly point out. However, by using a ConcurrentHashMap with the synchronized block, you can get the lock-free optimisation you are trying to implement, in a way that is guaranteed to work.

1

##### Share on other sites

I see. So the problem is that, while the next thread will see it as initialized, since the "put()" operation is done inside the synchronized block, the constructor might not be finished in time before the object gets retrieved by the next thread.

So what you're proposing is using a ConcurrentHashMap instead of a HashMap. I'm not seeing how that changes the constructor issue?

0

##### Share on other sites

The [url="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html"]documentation for the java.util.concurrent package[/url] states:

Memory Consistency Properties

Chapter 17 of The Java™ Language Specification defines the happens-before relation on memory operations such as reads and writes of shared variables. The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation. The synchronized andvolatile constructs, as well as the Thread.start() and Thread.join() methods, can form happens-before relationships. In particular:

• Each action in a thread happens-before every action in that thread that comes later in the program's order.
• An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.
• A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking.
• A call to start on a thread happens-before any action in the started thread.
• All actions in a thread happen-before any other thread successfully returns from a join on that thread.

The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. In particular:

• Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
• Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService.
• Actions taken by the asynchronous computation represented by a Future happen-before actions subsequent to the retrieval of the result via Future.get() in another thread.
• Actions prior to "releasing" synchronizer methods such as Lock.unlock, Semaphore.release, and CountDownLatch.countDown happen-before actions subsequent to a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await on the same synchronizer object in another thread.
• For each pair of threads that successfully exchange objects via an Exchanger, actions prior to the exchange() in each thread happen-before those subsequent to the corresponding exchange() in another thread.
• Actions prior to calling CyclicBarrier.await and Phaser.awaitAdvance (as well as its variants) happen-before actions performed by the barrier action, and actions performed by the barrier action happen-before actions subsequent to a successful return from the corresponding await in other threads.

The implementation of ConcurrentHashMap must do whatever it needs under the hood to ensure these properties.

1

##### Share on other sites

All right then, I replaced the HashMaps with ConcurrentHashMaps. Thanks a lot for the feedback :D

0

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account


text:
# Ordered sum of posets

Let $I$ be a poset and for any $i$ let $P_i$ be a poset. Let $P$ be the sum over $I$ of the sets $P_i$, and let $<_P$ be the relation defined on $P$ by $q<_Pr$ iff $q$ and $r$ are members of the same $P_i$ and $q<_ir$ or $q$ is member of $P_j$ $r$ is member of $P_k$ and $j<_ik$. Maybe that formally, I should have taken $Q_i$ as the cartesian product of the singleton of $i$ with $P_i$, and $Q$ as the union of the $Q_i$'s, and compared couples as $(i,q)$ and $(j,r)$. Anyway, it is clear that $P$, equipped with our relation is a poset, that is the poset sum over $I$ of the posets $P_i$. Particularly, in the case that $I$ and $P_i$ all are totally ordered sets , $P$ is a totally ordered set. And, in this particular case, a theorem of Schoenflies asserts that "every (totally) ordered set is the union of scattered sets over a densely ordered indexing set";

Question: does there exist a similar decomposition theorem in the general case of posets ?

Gérard Lang

-
@Gérard LANG, I've taken the liberty to edit your text into LaTeX and fixed a few spelling mistakes. Please re-edit if I've made the wrong choices in some places. – j.c. Jun 29 '11 at 16:14
Sorry, I did something similar as jc, in parallel. I then rolled back to jc's version as it was better than mine. – user9072 Jun 29 '11 at 16:17
That theorem of Schoenflies is quite interesting. Where can one find it? Could you perhaps spell out when subsets are scattered? – Chris Heunen Jun 29 '11 at 16:19
I rewrote my question because I thought it would not be readable. The theorem is given inside "Set Theory by Kuratowski and Mostowski(with an introduction to Descriptive set theory)" theorem 5 ,page 209. A linearly ordered set which contains no infinite densely ordered subset is said to be scattered; a set is densely ordered if for any two elements there exists another element strictly between them. Gérard lang – Gérard Lang Jun 29 '11 at 16:27
@Chris: see en.wikipedia.org/wiki/Scattered_order for two equivalent definitions. The theorem is then actually easy to prove: for $x\le y$, let $x\sim y$ iff the interval $[x,y]$ is scattered. This gives you an equivalence relation, and it is not hard to see that each equivalence class is a convex scattered subset, and $P/{\sim}$ is densely ordered. – Emil Jeřábek Jun 29 '11 at 16:31

I suggest first restricting to, say, suborders $P$ of the plane $\mathbb{R}^2$(with the product ordering where $(x_1,y_1)\leq(x_2,y_2)$ iff $x_1\leq x_2$ and $y_1\leq y_2$). See if you can find a satisfactory decomposition there, focusing on simple counterexamples to a straight generalization of Schoenflies' Theorem.
For example, let $$P=(\{0\}\times[0,1])\cup\bigcup_{n=0}^\infty(\{2^{-n} \}\times\{m\cdot 2^{-n}:m=1,\ldots,2^n\}).$$ Suppose you had a decomposition of $P$ into an ordered sum where the index has some property D reminiscent of denseness and each summand has property S reminiscent of scatteredness. If the linear order $[0,1]$ lacks property S, then you must decompose $P$ into singletons. Hence, either $[0,1]$ has property S or $P$ has property D. (Neither of these options looks appealing to me.)


text:
# A super easy way to get several gold badges

This is in response to this post: How to increase traffic to the site?

This site rewards publicity generously. If you share a link to a question, and the link is clicked on by 1000 different IP addresses, you get a gold badge. If you don't get a 1000, you still get a silver or a bronze.

You may say, "How does MSE know who posted the link?" You don't copy the URL in the browser, you click the small "Share" button on the lower left of each question. This gives a URL uniquely identifying you as the sharer.

You have to share it with people who are interested, and not be a spammer.

• Several people on other sites use Twitter. – Brian Rushton Jul 16 '13 at 1:56
• And if the question you share is your own (which it does not have to be), you can get a Popular Question badge in addition. Sweet deal. – 40 votes Jul 16 '13 at 2:12
• Is the last sentence technically true? Do you have to not be a spammer? – Rahul Jul 16 '13 at 3:38
• I thought I recognized one of those 15 questions... reddit.com/r/math/comments/1hz56o/… – The Chaz 2.0 Jul 16 '13 at 4:22
• @julien Maybe the reason so few people have these badges is not that they are hard, but that awareness is low... which I think was the reason for Brian's PSA. – 40 votes Jul 16 '13 at 12:23
• The difficult part is in establishing a website read by at least a thousand people. Super easy indeed! ;) – Erik Vesterlund Jul 16 '13 at 13:22
• @40votes Indeed, the reason why the badges Announcer (bronze, 354 times), Booster (silver, 31) and Publicist (gold, 15) are not awarded more often is probably due to the fact that not so many people are aware of it and how it works. – Julien Jul 16 '13 at 13:47
• @ErikVesterlund Pfft, websites. Social networks is where it's at... leveraging your Klout score to obtain badges on StackExchange is the new social media strategy. :) – 40 votes Jul 16 '13 at 14:19
• I think few people have 1000 friends or followers on fb resp twitter, of which only a fraction would bother clicking a math related link ("math? i hated that shit in high school!") – Erik Vesterlund Jul 16 '13 at 19:11
• @ErikVesterlund If I understood correctly, if you post a link somewhere on the web to a question using the address provided when you click on "share", it works too. – Julien Jul 16 '13 at 23:24
• @RahulNarain reddit users always vote me down when I'm being spammy. – Brian Rushton Jul 17 '13 at 2:36
• @40votes By googling reddit traffic I found that reddit is among the top 50 website in US, trailing only after NYT...So I am guessing posting on reddit may be a good idea to increase traffic and awareness? Also by following Chaz's link I do find there are some technical questions in math forum of reddit, maybe some users will find MSE a better place to ask questions after clicking the link? – Shuhao Cao Jul 17 '13 at 3:30
• @ShuhaoCao I doubt redditers would want to be proselytized... they are on /r/math/ because they like reddit, not because it's the best place for math discussions. You may notice several references to MSE there... including the infamous one, which led to this otherwise unremarkable question getting over 18000 views, among some other things... Anyway, nothing against reddit, but I'm never going to post there. – 40 votes Jul 17 '13 at 3:50
• @40votes wow, the forum's name is justiceporn... – Shuhao Cao Jul 17 '13 at 3:56
• If you want a gold badge why not get one you can wear by buying one on EBay. – Jay Jul 17 '13 at 15:03

Here are other "super easy" ways:

1. Just check the site each day for a consecutive 100 days.
2. Ask a relatively simple question that shows that your children have mathematical genius written all over their faces.
3. Answer a relatively simple question which shows that the OP's children have mathematical genius written all over their faces, and be one of the first to do so. Preferably answer in simple words, either a very short and to the point answer, or a very very long and detailed answer.
4. Reach the required reputation, and just review 20 items a day of every available queue. Within 50 days you will have gold badges.
5. Learn to spot things which require flagging. Flag them on sight. Within a year you have a Marshal badge.
6. Become a moderator, and stick there for a year.
7. Go back in time and be a moderator during the beta stage of the site.
8. Become really good in writing good answers, and just hit the reputation cap every day. Wait 150 days.
9. Write 200 answers on a tag of your choice, so the average score on these answers is +5.
10. Hack into the SE servers and tamper with the database.
11. Find a really crappy question and answer it well. Then publish the link to the question without using your user identifier link.
12. Answer tons of obscure questions, becoming an Unsung Hero.
13. Teach a class which has over 100 attendants and tell them to use math.SE, then answer their questions online/ask questions related to the topic of the course and get their votes.
15. Edit 500 posts.

There are probably more. And while all those ways are super easy some ways are more super easy than others.

• My favorite is number 7, because it disproves Hawking's theories that we can only travel forward in time. – Asaf Karagila Jul 16 '13 at 4:49
• You omitted one of the easiest (but also important for the site) - vote 40 times a day for 15 days. – 40 votes Jul 16 '13 at 5:15
• – Willie Wong Jul 16 '13 at 7:36
• @40votes what is that? I don't see it listed on the Badges page. math.stackexchange.com/help/badges – Willie Wong Jul 16 '13 at 7:38
• @40votes ah, do you mean electorate? There are some additional conditions involved... – Willie Wong Jul 16 '13 at 7:39
• @Willie: If there was more controversial activity, I'd probably sport a Deputy badge... :-P – Asaf Karagila Jul 16 '13 at 7:48
• @Willie The 25% condition is automatically fulfilled when someone votes 40 times a day, since 10 of those 40 votes are for questions only. Hence, the activity I described guarantees the badge. – 40 votes Jul 16 '13 at 11:10
• ... assuming no prior voting activity, that is. If the user previously cast more than 75% of their votes on answers, they will find Electorate harder to get than new users. The only badge that holds your past against you... not very logical decision on SE part. – 40 votes Jul 16 '13 at 11:49
• @40votes 600 different questions. So that someone will have to use up all 40 votes on 40 different questions for 15 days to earn the badge. (Also, in your comment above you meant 75%+ on answers, not questions.) – Willie Wong Jul 16 '13 at 11:49
• @Willie Thanks, I misread. So, one can still get it in 15 days but this requires voting on questions only. – 40 votes Jul 16 '13 at 11:52
• @40votes: There are more badges potentially "holding the past against you": Without cheating, Tenacious and especially Unsong Hero are only feasible in the beginning of your carreer, in my opinion. Deputy and Marshal get harder as you go up in reputation, since for example you cannot flag duplicates any more. – azimut Jul 17 '13 at 12:42
• @azimut: Between my Marshal badge and the second Marshal badge given there was almost a full year in which I accumulated over 600 helpful flags, and moreover -- I had over 10k reputation at the time, so I had no duplicates to flag either. It's not hard, you just have to be slightly vigilant. – Asaf Karagila Jul 17 '13 at 12:56
• You omitted this "super(hero) easy" way: the Batman gambit. – Blue Jul 18 '13 at 0:01
• @Ilya Well, neither is posting a link and getting 1000 votes but that's the question so I think the answer fits. – Graphth Jul 19 '13 at 2:42
• @Babak: Well, I did get my M.Sc. diploma a few weeks ago... ;-) – Asaf Karagila Jul 19 '13 at 13:14

The easiest way is surely making a post about Batman, it seems.

The easiest way to get a Gold badge is to Vote early, vote often. Vote on 600 questions and you will get yourself a Gold badge, the Electorate Badge. This should take you 600/40=15 days. As a bonus you will get the Civic Duty Silver badge (note: duty!). This is even easier to get: vote 300 times. It is interesting to note, though, that a mere 648 people have voted 300 or more times. Which is pathetic!

In conclusion, people don't vote enough. Vote early, vote often!

• (This came up in the comments of Asaf's post, but I discovered the 648 figure today. Thought I should point it out...) – user1729 Jul 22 '13 at 18:46
• We should get Ward interested in math... By the way, the first page of voters list still has Arturo Magidin and t.b... who are like mythical figures of Math.SE by now. – 40 votes Jul 22 '13 at 19:58

There is a brand new way to get a gold badge: asking good questions on $100$ separate days gets you a gold badge Socratic.

There are bronze and silver badges of the same kind: Curious and Inquisitive.


text:
# Circle Radius From End Piece Measurements

Geometry Level 3

A piece of a circle was cut off along a chord of length $$B=2$$. The greatest perpendicular distance from the chord to the circular arc is $$A=\dfrac{1}{3}$$. The radius of the parent circle can be expressed as $$\dfrac{X}{Y}$$, where $$X$$ and $$Y$$, where $$X$$ and $$Y$$ are coprime positive integers. What is the sum of $$X$$ and $$Y$$?

×