Get translated field value with fallback

Question: How can I get the translated value of a field in Drupal 8 and if no translation is given, fallback to the default node language?
I tried this: https://drupal.stackexchange.com/a/145747/9586, but when no translation for a field if added, it just returns NULL.
Here is what I tried:
<code>    $node = Node::load(2);
dsm(\Drupal::entityManager()->getTranslationFromContext($node)->field_my_awesome_field->value);
</code>
Answer: Drupal 8 does not have built in field-level language fallbacks. That feature was removed in favor entity level language fallbacks since that is the common case. Usually an entity is translated as a while (or not) and it removes a huge amount of complexity, especially in views or so.
If you have a specific field where you want to apply this, then you need to implement that yourself. You can check if an entity-level translation exists with $node->hasTranslation('en') and if so, get it with $translation = $node->getTranslation('de') ($translation is still a node object, it's a clone of the original one with a different active language). Then check if you have a value and repeat until find one.
Something like this:
<code>$value = NULL;
$language_manager = \Drupal::languageManager();
$current_langcode = $language_manager->getLanguage(Drupal\Core\Language\LanguageInterface::TYPE_CONTENT);
foreach ($language_manager->getFallbackCandidates(['langcode' => $language_manager->getLanguage(]) as $langcode) {
  if ($node->hasTranslation($langcode) && !$node->getTranslation($langcode)->field_my_awesome_field->isEmpty()) {
    $value = $node->getTranslation($langcode)->field_my_awesome_field->value;
    break;
  }
}
</code>
Comment: I would mark your comment also as right answer, but the guy before you was quicker sorry.
Anyways your comment also helped me to understand that better thank you.
Answer: You can try to provide the context for a fallback as 3rd parameter:
<code>public EntityRepositoryInterface::getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array())
</code>
Here is the documentation, but it is not documented, what the content of the array is exactly:
getTranslationFromContext
I would code the fallback myself and take control, how this is handled exactly, if the node is not fully translated:
<code>$val = \Drupal::service('entity.repository')->getTranslationFromContext($node)->field_my_awesome_field->value;
 if (empty($val)) {
    // $node has no translation with the default node language
    // get the default from somewhere else (domain, user ...) and try again
    $val = $node->getTranslation($defaultlanguage)->field_my_awesome_field->value;
}
if (empty($val)) {
   // someone needs to translate this node, in the meantime get the original value
   $val = $node->field_my_awesome_field->value;
}
</code>
You can adjust the code to your needs, you can add as many fallbacks as you like or go directly to the last if-statement to load the original field value.
One remark: If your multilingual site is setup correctly, this should not happen. The fallback is there, when something goes wrong. For example, if you configure a field as translatable, but when translating the node, you leave only this field blank. Then drupal does not know, is this intentionally, should it be blank or do you want to load the field from another language?
Comment: Alright that totally makes sense, thanks for the help.
Answer: Drupal 10.
Face same problem where client needed field level fallback functionality. Did below code. Hope it will help someone
<code> function yourmodule_paragraph_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
   if ($display->id() == "paragraph.image_video_media.default" && empty($build['field_image_video_media'])) {
     // Display data in the default language when a translation is unavailable.
     $defaultLanguage = \Drupal::languageManager()->getDefaultLanguage()->getId();
     $defaultLanguageEntity = \Drupal::service('entity.repository')->getTranslationFromContext($entity, $defaultLanguage);
     $defaultLanguageBuild = $display->build($defaultLanguageEntity);
     if (isset($defaultLanguageBuild['field_image_video_media'])) {
       $build['field_image_video_media'] = $defaultLanguageBuild['field_image_video_media'];
     }
   }
}
</code>


Is a free kick justified in this situation?

Question: I encountered a frustrating scenario in a soccer match that I would like your opinions about. During a play, the attacking player prepared to take a shot, but I was quicker and managed to kick the ball from behind just before he was able to take a shot, but as the attacking player had already begun their kicking motion, he striked my heel instead of the ball, fell to the ground, and a free kick was given to him.
How could a free kick be justified in this situation?
Comment: Impossible to review by just reading a (subjective) written version.
It can indeed be seen as dangerous play, and at a moment in time almost any challenge from behind was considered a foul.
Answer: Law 12.1 Direct free kick, emphasized with the relevant point:

A direct free kick is awarded if a player commits any of the following offences against an opponent condidered by the referee to be careless, reckless or using excessive force:

charges
jumps at
kicks or attempts to kick
pushes
strikes or attempts to strike (including head-butt)
tackles or challenges
trips or attempts to trip

If an offence involves contact, it is penalised by a dirct free kick.

Careless is when a player shows a lack of attention or consideration when making a challenge or acts without precaution. No disciplinary sanction is needed

Placing your body in a position that almost guarantees you will be kicked meets this requirement. It should be sanctioned to discourage actions which increase the likelihood of injury, whether to others or yourself. The sanction is a direct free kick for this offence.
If you continued to play this way within the same match, you may be justifiably cautioned for persistent offences under Law 12.3, Disciplinary action.
Had you made the tackle successfully without causing contact, in a way that "threatens injury to someone ... and includes preventing a nearby player from playing the ball for fear of injury" you could and should still be sanctioned with an indirect free kick under Law 12.2, Indirect free kick for playing in a dangerous manner.
Comment: I strongly disagree. From the description, the defensive player makes a legal tackle/challenge as he does not touch the offensive player. It is the offensive player that then commits the foul by not aborting his kicking motion and therefore is careless while attempting to kick. The free kick should be given to the defensive player.
Comment: You can disagree that it is the correct decision in any particular circumstance, but it is the correct decision in many circumstances. Either way, it is justified by this law, as the question asked about.
Comment: @treuss there's nothing to disagree with... Very aggressive tackles can result in very serious injuries, so that rule exists for the referees to judge dangerous challenges, even if they result in ball hit. Hard to say if it was a foul in this case without seeing footage of the play.


Wrong Currency symbol in view filter

Question: I have a view with BEF which is generating a criteria box like this below

I have no clue where this $ sign is coming from and how to remove it or change it.
Update
I investigated further and what I have noticed is that the currency symbol is linked to the theme settings. There is a field in the theme settings to accept currency code which was by default EUR. That I changed to INR which is not working but when I change to JPY it shows proper japan yet currency symbol. This confirms that this is the place where we need to look at.
Can some one help me where to start from?
Comment: I think this you need block settings.. You shown "Configure filter criterion" -> For This Page (override ). May be this is not your seeking answer.
Comment: Do you mean. I need to look at block settings not the view settings?
Answer: Your currency symbol is most likely coming from the field definition. Check the "prefix" value for the field in question at admin/structure/types/manage/<content_machine_name>/fields/<field_machine_name> replacing the items in <> as appropriate.
Comment: Thats reflecting change in the view contents but not in the view filters (which is, in my case is search box)
Comment: I further investigated and spotted where that $ sign is coming from. Please see updated post.
Answer: I figured out that the symbols were tweaked in the jquery.currency.js
It has format_current function which has a list for mapping 3 Letter currency symbol to actual currency symbol
I have added this line to that mapping list
            if(bc == 'INR') currency_before = 'Rs.';

Wrong Currency symbol in view filter


How do you optimize multiple objective functions simultaneously?

Question: For example, suppose we want to maximize the 3 expressions on the right, subject to some constraints.
To give some context, this is a problem about generating prototypes in unsupervised learning. In our example, we have 3 collinear centroids (representing 3 different classes) positioned (1,1), (7,1), (9,1) in the 2D-plane, with a line through all of them. The two centroids at the ends of the line are called prototypes, which carry information (the vectors with a's and b's).
To determine which class a random point on the plane belongs to, you calculate 3 different values: $\frac{a_i}{\text{distance from point to Prototype 1}}+\frac{b_i}{\text{distance from point to Prototype 2}}$ where $i=1,2,3$, and the largest value among the 3 gives you the $i^{th}$ class. For example, if $i=2$ is the largest, then the point belongs to the class at (7,1). (We order the classes from left to right, so the 1st class is at (1,1), 2nd class is at (7,1) and 3rd class is at (9,1).
Essentially, what we are saying in our 3 objective functions is that points lying arbitrarily close to a centroid must hold a strong membership to that class (the epsilons are very small values). The equality constraints say that the midpoints between each centroid must hold equal membership to its adjacent classes. Finally, the last line of constraints just requires that the a's and b's are probabilities.
Comment: So $\epsilon$ is just one fixed small positive constant, not to be changed while optimizing?
Comment: Yes. We're just considering a point in the vicinity of a centroid. For example, if we consider the centroid $(1,1)$, a point arbitrarily close to it would have a distance $0+\epsilon$. This way, we also don't divide by zero.
Answer: You already realized that, if there was only one objective function, that would be a linear-programming problem in the $a_i, b_i$. But in general, multiple such objective functions don't have to have the same solutions.
So first you could try whether you are lucky and they have a common optimum. Second, you could consider combining your multiple objective functions into a single one, e.g. by optimizing the sum or something similar. If that also doesn't fit your needs, you might want to have a look at Pareto optimization, which is dealing with what is achievable when in multi-objective optimization.
Comment: Just to add to @frank's response - one pretty easy to use method of multiobjective optimization is the multi-objective genetic algorithm, which is implemented in a range of  languages and doesn't require a huge amount of theoretical knowledge. Not saying it's the best thing ever for this task, but it could be a starting point.

That said, if you care about all your clusters equally (or you know the weights), using the (weighted) sum of the 3 objectives functions as a single one may be good enough.


Can you teach someone rhythm - to tap their feet or sway even?

Question: I just read a really great post here about teaching someone rhythm so they could play guitar, someone who seemed to have no rhythm at all. Someone suggested getting them to groove a bit to a song and feel it, tap their feet, etc.
What if they can't do that - groove to a beat in a song that is. They can't stay on beat or seem to feel the beat at all in songs. Any suggestions on how to get through that? To get them to be able to tap their foot to a beat and keep it? Or move to a beat- even sway to a beat?
Comment: I guess, like singing in tune, there are some who just can't do it. After all there is actually no reason why we *should* be able to, is there?
Comment: Duplicate of 'how can I teach a student who seems to have  no rhythm'?
Comment: Have you taught them to verbalize the rhythm first? One-and-two-and-three-and-four-and-one-and-two....and so on. Use your hands to give them cues while they count to let them know if they are going too fast or slow.
Answer: Have them count to four out loud repeatedly. If they can't count smoothly and evenly through the 4 to 1 transition then you might have a big problem. If they can count it then have them clap on each number while they count out loud. After that it's just incremental increases in complexity until they understand basic rhythm.
Comment: Reciting poems - even limericks, or times tables, or singing (chanting?) along with known songs will help somewhat. Follow clapping with finger clicking alternatively, foot tapping. The list is nigh on endless, to expand, also allieviate boredom...
Answer: I teach piano, not guitar, but I have had some success by simply using a metronome to get the student to really hear the rhythm. Some students simply do not have the ability to hear rhythm when listening to a song, and that's fine. It just takes them a little longer. Once they've played a song with a metronome a few times, it becomes easier for them to picture the rhythm in their head, and they eventually won't need the metronome to help them.
Hope this helps!
Answer: Take a look at some of the Suzuki Method techniques used for younger students.  I recall my child's teacher running a variety of group-timing exercises to help the students get a feel for even tempi.


Visual Studio Express 2012 Web debug randomly not refreshing browser cache with changes

Question: Been using Visual Studio Express 2012 Web for a few weeks now learning JavaScript, HTML5 and CSS for a web based application. As a .NET developer its great to have the familiarity of VS (although better JS/HTML intellisense would be nice) and my progress is good, however there is an annoying VS quirk during debugging that I can't resolve. Occasionally VS (or perhaps more specifically IE10) will stop recognizing any code changes and run the previous version of the code. This is annoying but I can get around it by hitting an extra F5 when IE10 launches but it shouldn't be needed. I assume the file cache for IIS express is not being refreshed when the source is updated but I could be wrong. After a while of experiencing this problem I have not been able to pick up a pattern to understand what usage pattern causes the problem.
Has anyone else seen this? Any fixes? Searching the net draws a blank.
I use VS web site project types and have a vanilla installation of VS 2012 express (uses IIS express) on Windows 8 and debugging with IE10.
Thanks.
Answer: Has any web developer using visual studio web found a way around this? I found Chrome to be more reliable at ensuring the cache is refreshed when the code changes however with the IE & VS integration its easier to develop with IE.
This must be a common problem? I have tried IIS Express as well and the same issue (figures as I'm sure its a problem with the browser cache). Typically the problem occurs when running IE for the first time, and if there is a bug in my Javascript code that breaks the execution before the screen is painted its quite a pain as its not as easy to clear the cache manually. The only workaround I have is use F12 and 'clear browser cache for this domain' then F5 to refresh. Workable but annoying.
Any tips to resolve this would be appreciated
Comment: Even better is to append a random query string to the end of the file being loaded. This forces the browser to load a new copy, and you can also insert condition checks in the code so that when running in debug mode the code appends the random query string but when running normally the random append isn't made so you get the benefits of local caching. Even sometimes this doesn't work, especially when running the application for the first time, so open F12 developer tools and select network-always get files from the server and clear the cache, then hit F5 to refresh the page.
Comment: So I tried to update to IE11 via Windows 8.1 to see if this problem goes away. If anything it is now worse! IE11 does not have a "Always Refresh From Server" option and the only way to get this to work is to tell the browser to always reload web pages (via internet options - so a pain to always set). I can't get any of the META tags in the HTML to work but I have tracked the problem further that it is the included or loaded files from JavaScript that are problems and are never reloaded. I don't understand why IE doesn't check the timestamp is different on the include file and not use the cache
Comment: OK, got this to work. The problem is that IE won't check timestamps for files loaded within javascript when the automatic page caching option in IE is used (the default). To make this work, use the meta tag in the HTML being loaded to force a refresh, or in my case where I'm loading SVG files as objects in javascript, I extended the object type information to include the metadata (eg. "image/svg+xml;cache-control: no-cache; pragma: no-cache; max-age=0").
I hope this helps others.
Answer: Add this:
window.applicationCache.addEventListener('updateready', function (e)
{
  if (window.applicationCache.status == window.applicationCache.UPDATEREADY)
  {
    window.applicationCache.swapCache();
    if (confirm('A new version of this site is available. Load it?'))
     window.location.reload();
  }
}, false);

I found this solution somwhere in the Net. Sorry, but I don't remember the author. It works for me when I debug Web App with JavaScript in Visual Studio 2012 using IE.
Please, stop cursing Microsoft. We all use their pruducts, be fair.
I don't work at Microsoft but I would be unhappy without its products. I think all of us would.
Comment: Thanks Alexander. I will try out your code to see if it works (problem is somewhat intermittent). Have updated to Win8.1 / RTM IE11 and the problem is less regular. I have nailed it down to loading files within the original page, sometimes it doesn't get the cache correct. What does work is to append a random parameter to the URL which forces a reload, although you want to remove it for production pages.

           iFrame.setAttribute("src", "dashboard.html?xx=" + Math.random());

Also, BTW I was not cursing Microsoft, I make my living within the Microsoft ecosystem and I think VS is great!
Answer: I am using Chrome myself, but still experienced the same problem. In the end I settled on the solution of completely turning caching OFF on my local WebServer - being VS's IIS Express -. This can be done by adding a UseMaxAge of 0 to the web.config. As follows:
XML
<configuration>
  ...
    <system.webServer>
      ...
      <staticContent>
        ...
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="0.00:00:00" />
      </staticContent>
  </system.webServer>
</configuration>

Notes

This works in regular/full IIS as well.
Be sure NOT to deploy this setting to PRODUCTION. Use a production specific web.config there to allow end users to harness some caching :). Otherwise this could be a performance killer.
Using CTRL+F5 instead of just F5 SHOULD also refresh it, however that somehow did not work either Chrome v39.0.2171.71 m). I found out it DID work to directly open the cached Javascript URL in the same browser (!) tab, press Ctrl+F5 on that and then return to the (HTML) page and use CTRL+F5 there again.
Another option that sometimes works is to restart IIS Express (Taskbar right click and choose 'Exit' from context menu). But that is also pretty cumbersome.. :)


Problema com 'Access-Control-Allow-Origin' no AngularJS

Question: Segue o código
  angular.module('App', [])
    .controller('InstaController',function($scope, $http){
        $scope.busca;
        $scope.buscar = function(){
            $scope.getInsta($scope.busca);
        }

        $scope.getInsta = function(tag){
            var url = 'https://api.instagram.com/v1/media/popular?client_id=6f6a0f971acf482a8dc4f9e66c2ec8b9';
            if(tag !== undefined){
                url = "https://api.instagram.com/v1/tags/"+tag+"/media/recent?client_id=6f6a0f971acf482a8dc4f9e66c2ec8b9"
            }
            $http.get(url)
            .success(function(data){
                $scope.inst = data.data;
                console.log($scope.inst);

            });
        }
        $scope.getInsta();
    });

Segue o erro
XMLHttpRequest cannot load https://api.instagram.com/v1/media/popular?client_id=6f6a0f971acf482a8dc4f9e66c2ec8b9. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Obs: Estou Usando Compilando na Build o .Apk Funciona normal mas no Navegador.
link do App na Web allandasilva.com.br/App/
"resolvi" com um plugin do Chrome
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
Como Resolver sem usar a externação
Answer: Você não tem "allow" no response header da api.instagram.
O único jeito é utilizando GET + JSONP. Da uma olhada em http://instagram.com/developer/endpoints/ na sessão JSONP.
É necessário um CALLBACK no endpoint para JSONP. (&callback=callbackFunction)
Exemplo:
https://api.instagram.com/v1/tags/coffee/media/recent?access_token=fb2e77d.47a0479900504cb3ab4a1f626d174d2d&callback=callbackFunction

Callback function:
callbackFunction({
    ...
});

Comment: Valeu Vou dar uma olhada


What would be the Alias for this 'User Edit' page link?

Question: Working on a User Dashboard (using the Workbench Module), I have a link in a Views Block which the user can click to 'edit' their details. The current link looks messy (as shown below) and I would like to use an Alias to give a much more attractive frontend link Edit profile to reflect the page link and not the one as shown below.
The current path links from the 'Edit Link' field in an Account Views Block and I'm using a 'Rewrite' as user/[name] within the path of the said field.
However, currently changing the link in Alias module gives me multiple errors trying with the likes of 'user/edit' path, what am I doing wrong, or is it an issue with Workbench?
[http://localhost/sitename/user/46/edit?destination=admin/workbench]
Answer: please check this module, which should do the job for you
https://drupal.org/project/path_alias_xt

Extended Path Aliases finishes the job left incomplete by core's Path
  module, fixing all of the above. And it does so automatically, without
  any configuration options or permissions to set and without requiring
  any other modules. Just install and you're away.
Comment: Thank you for the lead, I will install and get back to you later with results. I thought I was going mad! LOL I'm a Drupal 'plumber' so need all the Drupal widgets I can get.


"Flutter create" command doesn't add support for Android and iOS

Question: guys.
When I want to create new Flutter project with the command flutter create --org com.example.myapp myapp it only creates web folder and not android and ios  folders. I also tried to create a Flutter project from Android Studio, but it only created web folder as well. I don't know why is that.
When I tried to add support for Android and iOS inside of the project's folder with command
flutter create --platforms=android,ios .
I receive the following message:
Recreating project ....
Resolving dependencies...
Got dependencies.
Wrote 0 files.

All done!
You can find general documentation for Flutter at: https://docs.flutter.dev/
Detailed API documentation is available at: https://api.flutter.dev/
If you prefer video documentation, consider: https://www.youtube.com/c/flutterdev

In order to run your application, type:

  $ cd .
  $ flutter run

Your application code is in ./lib/main.dart.

but without added support.
flutter doctor returns nothing suspicious:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.10.2, on macOS 13.3.1 22E772610a darwin-x64, locale en-GB)
[✓] Chrome - develop for the web
[✓] IntelliJ IDEA Community Edition (version 2022.2.2)
[✓] VS Code (version 1.78.2)
[✓] Connected device (3 available)
[✓] Network resources

• No issues found!

What could possibly be wrong here?
Comment: your flutter create command `flutter create --org com.example.myapp myapp` looks clean. Are you using the latest/beta version on flutter? it might be a new issue with the relese
Answer: This is how I solved it:
flutter config --enable-android --enable-ios


Como transformar um string em HTML C#

Question: Estou usando um componente e preciso carregar ele com trecho HTML que vem em uma variável. Pra isso criei esse JQuery:
$(document).ready(function(){
    $('.mentions-kinder').html('@HttpUtility.HtmlDecode(Model.FormulaRecover)');
});

Mas mesmo assim quando rodo, ele não carrega o código, e fica assim:

Se o JQuery lesse o código igual o print acima dava certo, mas o código quando inspeciono a página fica assim:
$(document).ready(function(){
    $('.mentions-kinder').html('<span class="mention badge badge-warning" contenteditable="false" serialized-mention="[#Quantidade de Visitas](tag:12)"><span class="tag-trigger">Parametro: </span><span class="tag-value">Quantidade de Visitas</span><span class="delete-mention tag-delete"><i class="icon-remove"></i></span></span> <span class="mention badge badge-primary" contenteditable="false" serialized-mention="(area:104)"><span class="area-trigger">Area: </span><span class="area-value">Alessandro Spricigo</span><span class="delete-mention area-delete"><i class="icon-remove"></i></span></span> *');
});

E fica tudo errado. Alguma ideia pra isso ?
Answer: Quando você tem uma string de html ela não é renderizada no DOM, para que esta string possa ser renderiza é necessário chamar o método Html.Raw() passando a string html. O método Html.Raw() Transforma a string em uma marcação html.
Solução
No seu caso você deve utilizar como abaixo:
@Html.Raw(HttpUtility.HtmlDecode(Model.FormulaRecover))

Como transformar um string em HTML C#


using a Jquery ui Slider to highlight html table row/column

Question: I have a complex html table div that has three sliders.  I also use a jquery script and css to change the color of the cells based on the cell value.
the horizontal slider (Slider 1) controls the display of another html table of the "Y"cross section.
the long vertical slider (Slider 2)controls the display of another html table of the "X" cross section.
The shorter vertical slider controls the "z" layer displayed in the main html table.  (move this slider to have html content appear)
What I would like to do is, when Sliders 1 and 2 are moved, I want the row and column to be highlighted in the main table.  I would prefer to have the border on the row/column to be thicker/different color as to not change the conditional formatting.
Here's the Fiddle
Other than what I want, everything else works fine.  Here's what I put in to try and make it work (I'm trying background color for now for testing, but I would eventually change it to border color/style change):
$('#tab').siblings().css('background-color', '#EAD575');
var ind = $('#tab').index();
$('#tab tbody td:nth-child(' + (ind + 1) + ')').css('background-color', '#EAD575');

Right now it's making a lot of things highlighted where it shouldn't including parts of the page background.
Any help please?  Thanks!
Answer: The table elements are children of the #tab element, so your use of .siblings() is incorrect.
I suggest you declare a CSS class named "highlighted" that you add to a table cell (td) to change the background color and/or border.
You could define a function like the following that highlights the appropriate cell. This function would be called whenever a slider is changed, but only after the input value is changed to match the slider value:
function updateHighlightedCell() {
    var iCol = parseInt($('#amount1').val(), 10) - 1,
        iRow = parseInt($('#amount2').val(), 10) - 1,
        $table = $tab.children();
    $table.find('td').removeClass('highlighted');
    $table.find('tr:eq(' + iRow + ')').find('td:eq(' + iCol + ')').addClass('highlighted');
}

jsfiddle
Note: I scaled down the number of rows and columns in the fiddle.

To highlight the row and column, use:
$table.find('td').removeClass('highlighted');
$table.find('tr').find('td:eq(' + iCol + ')').addClass('highlighted');
$table.find('tr:eq(' + iRow + ')').find('td').addClass('highlighted');

jsfiddle
Comment: @Crimpy - I updated my answer to show how to highlight the row and column.
Comment: That's a great improvement on efficiency too.  Works fantastic! Thanks for the lesson!  Is there a way to highlight the entire row and the entire column with the same border style?
Comment: Another strange thing is that in my html on my bigger project, I get a remnant of the highlighted cell in rows when I scroll. Any ideas on why that might be?
Comment: @Crimpy - As for your remnant issue, I can only guess that the class is not getting removed from all the cells. The code in my answer should remove it from all cells before putting it on the selected cell.


How to find OLE object location in crystal reports 8

Question: I have few pictures on crystal report as OLE object.
is there any way to find the location, from where these pics inserted as OLE object.
I'm using old version CR 8
Answer: If I understood well: choose Edit->Links from the menu. In the window that opens, all the OLE objects are listed. You mark one and below it shows:
Source: location of the object/file
Type: type of the object
Update: date

Comment: unfortunately link option is disabled :( in menu


An inequality without studying variations

Question: How can one prove the following inequality using only concavity of $\log$ function: for any $\alpha>0$, there exists a constant $c_\alpha >0$ such that
$$\frac{\alpha x-1}{\log(\alpha x)} \le c_\alpha \frac{x-1}{\log x}, \qquad x>0.$$
We can prove it by studying the variation of a suitable function, but I found a claim that can be proved using only concavity of $\log$ by discussing the cases $\alpha>1$ and $\alpha<1$.
The point is to take out the constant $\alpha$ from the function on L.H.S and obtain just a multiplicative constant instead.
Comment: What is $c_\alpha$?
Comment: A constant depending on $\alpha$.
Comment: In other words you ask to prove that for any $\alpha>0$ there exists such $c_\alpha$ that the inequality holds, don't you?
Comment: @user Yes, exactly.
Comment: If this wording is correct I would suggest you to edit the question.
Answer: The claim can be in fact sharpened to the statement that the least possible value of $c_a$ is:
$$
\max(1,a),
$$
since the function $\phi(x)=\frac{a x-1}{\log(a x)}\cdot\frac{\log x}{x-1}$ is monotonic and:
$$
\lim_{x\to0}\phi(x)=1;\quad
\lim_{x\to\infty}\phi(x)=a.
$$
For $a<1$ the resulting inequality
$$
\frac{ax-1}{\log(ax)}\le \frac{x-1}{\log(x)}
$$
can be proved from concavity of the $\log(x)$ function.
We start with the following inequality valid for arbitrary concave function $f(x)$:
$$
(x_3-x_2)f(x_1)+(x_2-x_1)f(x_3)\le(x_3-x_1)f(x_2),\tag1
$$
where $x_1< x_2< x_3$.
Let now $f(x)=\log(x)$, $a<1$ and consider the following 3 cases:
I: $0<x<1$
Setting in (1) $x_1=ax,x_2=x,x_3=1$ one obtains
$$
(1-x)\log(ax)\le(1-ax)\log(x)\implies \frac{ax-1}{\log(ax)}\le\frac{x-1}{\log(x)}.
$$
II: $1<x<\frac1a$
Setting in (1) $x_1=ax,x_2=1,x_3=x$ one obtains
$$
(x-1)\log(ax)+(1-ax)\log(x)\le0\implies \frac{ax-1}{\log(ax)}\le\frac{x-1}{\log(x)}.
$$
III: $\frac1a<x$
Setting in (1) $x_1=1,x_2=ax,x_3=x$ one obtains
$$
(ax-1)\log(x)\le (x-1)\log(ax)\implies \frac{ax-1}{\log(ax)}\le\frac{x-1}{\log(x)}.
$$
Above we have used the fact that the product $\log(x)\log(ax)$ is positive in cases I and III and negative in the case II.
For $a>1$ the same argument applied to the convex function $x\log(x)$ results in the inequality:
$$
\frac{ax-1}{\log(ax)}\le a\frac{x-1}{\log(x)}.
$$
Comment: Why $\phi$ is monotonic?!
Comment: @Migalobe This is very nice question, which however is not relevant to my answer. I have mentioned the fact only to justify (motivate) the search for $c_a=\max(1,a)$. A very nice and short proof of the monotonicity of $\phi(x)$ is given in the answer to your follow-up [question](https://math.stackexchange.com/q/3522281).


Metric on $[-\infty,\infty]$ by homeomorphism

Question: I want to precise a topology to use on $[-\infty,\infty]$. This space is homeomorphic to  $[0,1]$ by taking $$f(x) = \tan (\pi(x-1/2))$$ as map. Taking $d(x,y) = |x-y|$, $x,y\in[0,1]$ can I "map" the metric using $f$ to get a metric on $[-\infty,\infty]$? Maybe $\overline{d}(x,y) = d(f^{-1}(x),f^{-1}(y))$ would work?
Comment: Yes, it would. It's a standard way of transporting metrics.
Comment: Another less know isometry is $$\frac{x}{1+|x|}$$
Comment: @PeterTamaroff how is that? From $[-\infty,\infty]$ to $[0,1]$?
Answer: Yes, that works, and is a standard way of getting a metric on some space. We have
Lemma: Let $(X,\,d)$ a metric space, and $\varphi \colon Y \to X$ a bijection. Then $\delta \colon Y \times Y \to \mathbb{R};\; \delta(y,\,z) = d(\varphi(y),\,\varphi(z))$ is a metric on $Y$, and $\varphi$ is an isometry (in particular a homeomorphism) between $(Y,\,\delta)$ and $(X,\,d)$.
Proof: We have $\delta(y,\,z) \geqslant 0$, since $d$ takes only non-negative values, and
$$\delta(y,\,z) = 0 \iff d(\varphi(y),\,\varphi(z)) = 0 \iff \varphi(y) = \varphi(z) \iff y = z.$$
We have $\delta(y,\,z) = d(\varphi(y),\,\varphi(z)) = d(\varphi(z),\,\varphi(y)) = \delta(z,\,y)$, so $\delta$ is symmetric.
We have $\delta(x,\,z) = d(\varphi(x),\,\varphi(z)) \leqslant d(\varphi(x),\,\varphi(y)) + d(\varphi(y),\,\varphi(z)) = \delta(x,\,y) + \delta(y,\,z)$ for all $x,\,y,\,z \in Y$, hence $\delta$ satisfies the triangle inequality, hence is a metric.
By the very definition of $\delta$, $\varphi$ is an isometry $Y \to X$, hence also a homeomorphism for the topologies induced by $d$ resp. $\delta$.
Furthermore, we also have the
Lemma: Let $(Y,\tau)$ a topological space, and $(X,\,d)$ a metric space, and $\varphi \colon Y \to X$ a homeomorphism. Then the metric $\delta$ on $Y$ constructed as above induces the topology $\tau$ on $Y$.
Proof: Let $y \in Y$ and $V$ a $\tau$-neighbourhood of $y$. Since $\varphi$ is open (because it's a homeomorphism), $\varphi(V)$ is a neighbourhood of $\varphi(y)$, hence there is an $\varepsilon > 0$ with $d(x,\,\varphi(y)) < \varepsilon \Rightarrow x \in \varphi(V)$. But that means that $B^\delta_\varepsilon(y) = \{ z \in Y : \delta(z,\,y) < \varepsilon\} \subset V$, i.e. the topology induced by $\delta$ is finer than $\tau$.
Conversely, let $y \in Y$ and $\varepsilon > 0$. Then $\varphi(B^\delta_\varepsilon(y)) = B^d_\varepsilon(\varphi(y))$ is a neighbourhood of $\varphi(y)$, and by continuity of $\varphi$, there is a $\tau$-neighbourhood $V$ of $y$ with $\varphi(V) \subset B^d_\varepsilon(\varphi(y)) \iff V \subset B^\delta_\varepsilon(y)$, which means that $\tau$ is finer than the topology induced by $\delta$.
Comment: Yes, $f$ is a homeomorphism, so the open (closed) sets in $[-\infty,\, +\infty]$ are precisely the images of open (closed) sets in $[0,\,1]$ under $f$.
Comment: Great, thank you very much for your detailed answer!
I'm studying stochastics mostly and I'm pretty disappointed that we never had topology, since we use basic results quite often. This explains my next probably easy question:
If I use $f$ to map open sets from $[0,1]$ (topology induced by $d$), are those the open sets in the topology of $\overline{d}$ (the transported metric)?
Comment: Got it, huge thank you again!


Como transformar uma coluna com valores separados por virgula em linhas usando SQL

Question: Dei uma pesquisada em algumas perguntas do site e não encontrei nada nesse sentido, queria saber se é possível fazer uma consulta SQL, em uma coluna string onde os valores são separados por virgula. Por exemplo:
Tabela usuario
id = int
nome = string
img = string ('https://google.com/img/1, https://google.com/img/2, https://google.com/img/3')

o resultado que eu espero seria algo nesse sentido:
Tabela resultante da query
id | imgs
1  | 'https://google.com/img/1'
1  | 'https://google.com/img/2'
1  | 'https://google.com/img/3'
2  | 'https://bing.com/img/1'
2  | 'https://bing.com/img/2'

O banco que utilizo é Microsoft SQL Server mas gostaria de saber se é possível fazer com SQL puro, caso não seja possível uma solução "universal", aceitaria uma resposta para Microsoft SQL Server
Comment: @Danizavtz `UNNEST` não seria PostgreSQL: https://www.postgresql.org/docs/9.2/functions-array.html#ARRAY-FUNCTIONS-TABLE? Ando por fora de de *Transact-SQL*, mas creio que o que o Julio deseja seja o `STRING_SPLIT`, combinado com `CROSS APPLY` para que os dados se relacionem com a própria tabela.
Comment: tem um comando que eu usava pra fazer isso que era o `UNNEST`. Mas creio que não é padrão do sql.
Comment: Acho que deve procurar por Cross-table
Answer: Se for SQL Server 2016 (13.x) ou superior pode user o STRING_SPLIT
Supondo que originalmente a tabela seja:

Id
Nome
Tags

1
C#
desktop,servidor,linha de comando,jogo

2
PHP
servidor,linha de comando

4
JavaScript
servidor,navegador,linha de comando

5
Java
android,servidor,desktop

Com STRING_SPLIT o nome da coluna de saída é value, então aplique assim na query:
SELECT Id, Nome, value
FROM Tabela
CROSS APPLY STRING_SPLIT(Tags, ',');

terá um resultado como:

Id
Nome
value

1
C#
desktop

1
C#
servidor

1
C#
linha de comando

1
C#
jogo

2
PHP
servidor

2
PHP
linha de comando

3
JavaScript
servidor

3
JavaScript
navegador

3
JavaScript
linha de comando

4
Java
android

4
Java
servidor

4
Java
desktop

Exemplo online no dbfiddle
Comment: Ty, O que seria Tags?
Comment: @JulioHenrique a coluna hipotética que deseja dividir, no seu caso a coluna `img`
Comment: realizei o teste, porem as linhas estão retornando a coluna com o valor integral separado por virgula. tipo 1->php -> servidor, linha de comando. 2->php ->  servidor, linha de comando.
Comment: @JulioHenrique experimente: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=62a034297a9532e3c5b9718e8529835c, ps: editei a resposta, acidentalmente eu tinha removido o `, value` que é o responsável por obter o retorno.
Comment: @JulioHenrique um teste com a sua tabela: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=73785f41fa4984c065f2fb16604adbf5
Comment: Pois é, creio que o problema está na versão do meu Sql, estou testando no microsoft sql server management studio


Homogeneity of a differential equation.

Question: Convert $$\frac{dy}{dx} = \frac{-(2x-4y+6)}{x+y-3}$$ into a homogeneous differential equation.
Any help appreciated!
Answer: $$\frac{dy}{dx} = \frac{-(2x-4y+6)}{x+y-3}$$
Cross multiply to get
$$(x+y-3) \, dy +(2x-4y+6) \, dx =0$$
This can be made into a homogeneous differential equation by a linear transformation of both variables:
$$z=x+a, s=y+b,\text { where $ a, b $ are constants.}$$
Can you see why?
Comment: I can't seem to understand why adding a and b into the mix clears it up, could you elaborate a bit please?
Comment: Show that $(x+y-3), (2x-4y+6) $ are homogenous functions (http://en.m.wikipedia.org/wiki/Homogeneous_function) on this linear transformation.
Answer: The given equation is not a homogeneous equation. In order to make it a homogeneous one you need to eliminate the constant terms (Also note that the coefficients of $x$ and $y$ in the parantheses are not proportional). This can be done by means of the change of variables $x=u+h$ and $v=y+k$, where $h$ and $k$ are constants satisfying the equations $$h+k-3=0$$ $$2h-4k+6=0$$. Solving this system of linear equations we get $h=1$ and $k=2$. So our DE becomes $$\frac{dv}{du}=-\frac{2u-4v}{u+v}.$$ Now set $$U=\frac{v}{u}$$ or $v=uU$ which implies $$\frac{dv}{du}=U+u\frac{dU}{du}.$$ Substituting these into the equation we have $$U+u\frac{dU}{du}=-\frac{2-4U}{1+U}.$$ Thus after a few algebra you arrive at a separable equation in $u$ and $U$, which requires only integration to find the solution:$$\frac{1+U}{3U-2-U^2}dU=\frac{du}{u}.$$

Homogeneity of a differential equation.


KnockoutJS cannot delete object from observableArray

Question: I have the following code:
var testVM = {
  things: ko.observableArray([
    { id: 1, name: "Apple" },
    { id: 2, name: "Banana" },
    { id: 3, name: "Orange" },
    { id: 4, name: "Pineapple" },
    { id: 5, name: "Pear" }
    ]),

  deleteThing: function (data) {
    var things = testVM.things;
    var index = things.indexOf(data);

    // Debug...
    console.log('data', data);
    console.log('index', index);

    if (index > -1) {
        things.splice(index, 1)
    }
  },

  deleteApple: function () {
    this.deleteThing({ id: 1, name: "Apple" });
  }

};

ko.applyBindings(testVM);

With the HTML:

    X |

Delete Apple

Which I've created in a Fiddle. The issue I'm having is that when invoked from a data-bind="click: deleteThing" inside a foreach the deleteThing function works fine, however if (in the case of the deleteApple method) I attempt to manually delete something it never finds the index and subsequently doesn't delete the item from the observableArray.
I'm stumped because in both instances the console.log shows the same data.
Answer: The issue that you are having is related to object references. In your deleteApple function you are passing a new object that does not match the original object reference.
The remove API does accept a function that passes the item in where you can return truthy/falsy whether you want to remove the item.
Example of using remove on an observableArray:
deleteApple: function () {
    this.things.remove(function(item) {
       return item.id === 1 && item.name === "Apple";
    });
}

Updated fiddle: http://jsfiddle.net/rniemeyer/5HPxZ/
Comment: Thanks Ryan, knew I'd see you here :)
Answer: The reason is that you try to delete an object that is not in the array:
this.deleteThing({ id: 1, name: "Apple" });

Although the values of the properties is the same, the objects are different. Objects are references and you need the correct reference, ie you need the find the index of the item and then delete at that index:
for(var i = 0;i<testVM.things.length;i++){
    if(testVM.things[i].id === 1){
        things.splice(index, 1);
    }
}

To test what I mean about references, try and execute the following code:
var x = { id: 1, name: "Apple" };
var y = { id: 1, name: "Apple" };
alert(x === y): // Alerts false


The PDF of the Data (Marginal Likelihood) Given the Prior of a Gamma Distribution with Prior on the $ \beta $ Paraneter

Question: Given a model where $ x_i | \beta \sim \mathcal{Gamma} ( \alpha, \beta ) $ where $ \beta \sim \mathcal{Gamma} ( \alpha0, \beta0 ) $, is there a closed form formula for the PDF of $ x_i $?
Namely, what's $ p ( x_i ) $?
In the Gamma Distribution above I assume the shape ($\alpha$) and rate ($\beta$) variant of the Gamma Distribution.
This is similar to a different question I asked (The PDF of the Data Given (Marginal Likelihood) the Likelihood and the Prior of a Normal Distribution with Prior on the Mean) yet with totally different model (This is about the conjugate prior Gamma Gamma model and the other question about the Normal Normal conjugate prior model).
I am using this to build a model of my data (2 different sets in each question).
Please unlock this question.
Comment: I agree it's a (slightly) different question.  However, it has at least four distinct interpretations: please explain the meaning of your parameters.  (Which is a shape, which is a rate, which is a scale?)
Comment: @whuber, I updated the question to clarify the model of parameters assumed in the question (Link to Wikipedia for clarity).
Answer: Yes it does, the Generalized Beta prime distribution  with shape parameter equal to 1.
We can get there fairly easily by integrating $\beta$ out of the joint distribution of $x$ and $\beta$:
$$f(x,\beta|\alpha, \alpha_0, \beta_0) = {\beta^{\alpha}x^{\alpha-1} \over \Gamma(\alpha)}e^{-\beta x}{\beta_0^{\alpha_0}\beta^{\alpha_0-1} \over \Gamma{\alpha_0}}e^{-\beta_0\beta}$$
Rearranging terms and ignoring everything that isn't related to either $\beta$ or $x$ (as they will all be handled by the constant of integration at the end) results in a great deal of simplification:
$$f(x,\beta|\cdot) \propto x^{\alpha-1}\beta^{\alpha+\alpha_0-1}e^{-(\beta_0+x)\beta}$$
We can integrate out $\beta$ easily enough by noting that the two terms involving $\beta$ are those of a Gamma-distributed variate with shape parameter $\alpha + \alpha_0$ and rate parameter $\beta_0 + x$, so the integral must equal the inverse of the constant of integration of such a distribution:
$$x^{\alpha-1}\int \beta^{\alpha+\alpha_0-1}e^{-(\beta_0+x)\beta}\text{d}\beta = {x^{\alpha-1} \Gamma(\alpha+\alpha_0) \over(\beta_0 + x)^{\alpha + \alpha_0}} \propto x^{\alpha-1} (\beta_0 + x)^{-\alpha - \alpha_0}$$
A slight rearrangement of terms and some minor algebra gets us to:
$$f(x|\cdot) \propto \left({x \over \beta_0}\right)^{\alpha-1} \left(1 + {x\over \beta_0}\right)^{-\alpha - \alpha_0}$$
which clearly matches the formula for the GBPD
(with shape parameter $p=1$) as given by Wikipedia and reproduced here:
$$f(x;\alpha,\beta,p,q) = \frac{p \left(\frac x q \right)^{\alpha p-1} \left(1+ \left(\frac x q \right)^p\right)^{-\alpha -\beta}}{qB(\alpha,\beta)}$$
Comment: Related to inventory control - a common assumption is that demand ~ Negative Binomial, but items are often shipped in case packs that are much larger than the demand rate.   What is the distribution of the time until enough demands have occurred to trigger an order for a full case pack?   If you have that distribution, you can better predict when you need inventory in a distribution center for satisfying store orders on the DC.   $\beta$ = the case pack qty, etc.  You can get there via Poisson demand with rate ~ Gamma and the Gamma scale parameter in turn distributed Gamma.
Comment: This is great. First, Interesting that this is the conjugate of the Bernoulli distribution in its odds variant. Is there a meaning to that? When you mark proportionally, does it mean that the model is equivalent to `GBPD(alpha, alpha0, 1, beta0)`?
Comment: 1) Yes, it is interesting, and I can't for the life of me figure out what it means.  2) Yes, the model is equivalent to a `GBPD(alpha, alpha0, 1, beta0)`.   Remarkably enough, I've actually had occasion to use it in my applied work...
Comment: May I ask for what purpose did you use the model?


Is there any overhead to continually using SELF getter when setting a properties values as opposed to accessing directly?

Question: RE: Objective-C - When to use 'self'
I understand when SELF is actually required 100% to properly set a retained property but is there any overhead to continually calling the getter method, instead of accessing directly even after you've already obtained your retained object? Is the program more efficient not continuously calling it?
Your ViewController contains many retained subviews (ie. multiple retained UIViews) which get added to the root main view.
Inside your viewDidLoad: method is there any overhead doing:
[self.mySubViewA setBackgroundColor:[UIColor blueColor]];
[self.mySubViewA setOpaque:NO];
[self.mySubViewA setAlpha:1.0f];

[self.view addSubView:self.mySubViewA];

[self.mySubViewB setMyCustomPropertyInThisView:[UIColor redColor]];
....

instead of:
// no calls to SELF at all (i.e saving time on method get cycle calls and directly
// accessing the properties currently retained at that address.
// Assumption here is that mySubViewA is loaded through NIB and is already alloc'd.
[mySubViewA setBackgroundColor:[UIColor blueColor]];
[mySubViewA setOpaque:NO];
[mySubViewA setAlpha:1.0f];

// Is this faster? since we just instantly assign the UIView @ mySubViewA to the main view
// as opposed to a method get cycle?
[self.view addSubView:mySubViewA];

[mySubViewB setMyCustomPropertyInThisView:[UIColor redColor]];
....

Answer: Yes, of course there is an overhead. Using self.… means another method call which takes more time than a simple assignment. How much more, depends on how the getter is implemented (e.g. if the property is nonatomic or not).
More importantly, unless you can identify this additional overhead to be a bottleneck in your specific case, you should not care about it. Using the getter has many advantages and you should not prematurely forgo them just to improve performance where it isn't necessary.
Answer: [ self.foo bar ];

is equivalent to 2 method calls:
temp = [ self foo_Getter ];    // first method call
[ temp bar ];                  // second method call

so, of course, there will be more Objective C runtime method dispatch overhead.
However you might only ever find this overhead measurable inside the inner loops of some compute bound routine (numeric, audio, image processing, etc.).  So outside inner loops, write readable maintainable code.  Inside inner loops, use temporary local variables as necessary to avoid any repeated method dispatches that the compiler can't optimize away (except when that violates memory management rules, etc.)


Conditional Probability baffled

Question: I've got a question as follows:
A heavy container with chemical waste has been illegally dumped into the sea, and is now lying in a fixed but unknown position on the bottom of the sea. The container is believed to be situated in British territorial waters with probability 0.8. The Royal Navy are planning a search through the British territorial waters only, to try to find the container. If the container is situated in British territorial waters, then the probability that it will be found by such a search is 0.7 (while the probability that it will be overlooked is 0.3).
(i) Calculate the probability that the container will be discovered by this search through the British territorial waters
(ii) Suppose that this search through the British territorial waters turns out to be unsuccessful, i.e. the container is not found. Given this information, what is now the probability that the container is situated in British territorial waters?
...........
For part (i) I think you use the conditional probability formula (P A given B) = P(A intersection B) / P (B). In this context, P(Found given British) = 0.7 and P(B) = 0.8 hence the answer is 0.8 x 0.7 = 0.56. Can someone confirm this?
For part (ii) I'm quite clueless about what to do
Thanks in advance
Answer: For Your Part  two I would recommend Baye's Theorem.
$P(A)$= Chemical in British Water (0.8)
$P(E)$=Search unsuccessful (0.3)
$$P(A|E)=\frac{P(A).P(E|A)}{P(A).P(E|A)+P(A^{'}).P(E|A^{'})}$$
$$P(A|E)=\frac{0.8*0.3}{0.8*0.3+0.2*1}$$
$$P(A|E)=\frac{6}{11}$$
$P(E|A^{'})=1$ Because Vessel can't search for a vessel which ain't there.
PS: Your (i) looks good enough
  EDIT: Thanx for pointing out the calc. error.
Comment: I believe your final value for P(A|E) should be  6/11
Answer:
I drew a tree diagram concerning this question to help visualize.
Part I.
Yeah, that looks good.
Part II.
In essence, what this question is asking is "GIVEN that the container is not found, what is the probability that it is in British waters?"
The second and fourth branches on the tree diagram are $F'$, which means it isn't found. This means the overall possibility that the container is not found is $0.8 \times 0.3 + 0.2 \times 0.3 = 0.3$. Then, the other part of the question asks for the probability that it is in British waters - that's the second branch only. Now we can define these:
$P(A) =$ Not found $= 0.3$
$P(B) =$ In British waters $=0.8$
$P(A \cap B) =$ Not found and in British Waters $= 0.24$
Thus:
$$P(A|B) = \frac{P(A \cap B)}{P(B)}$$
$$P(A|B) = \frac{P(0.24)}{P(0.8)}$$
$$P(A|B) = 0.192$$
Comment: You have defined P(A) as the probability the waste is not found, but you have not conditioned on the location of the waste being in the British Territorial Waters.  This propagates an error through the rest of your calculation.  P(A) is subject to the Law of Total Probability
Answer: Denote:

Event B as the event the Waste is in British waters
Event F as the search finds the waste
$P(B)=0.8$,$P(B^C)=0.2$,
$P(F)=0.7$,$P(F^C)=0.3$

Part one:

For part (i) I think you use the conditional probability formula (P A given B) = P(A intersection B) / P (B). In this context, P(Found given British) = 0.7 and P(B) = 0.8 hence the answer is 0.8 x 0.7 = 0.56. Can someone confirm this?

Yes: expressing the probability of an event IF some other event does or does not occur, is the application of conditioning on information. Usually we use the word "given".  "A given B occurs".  It is the same as "A if B occurs".
$$P(F | B)= \frac{P(F \cap B)}{P(B)}=0.7$$
$$P(F \cap B) = P(F | B)P(B)=0.7 \times 0.8$$
Part two:
$$P(F^C|B)=0.3$$
Find $P(B|F^C)$
$$P(B|F^C)=\frac{P(B\cap F^C)}{F^C}=\frac{P(F^C|B)P(B)}{F^C}=\frac{P(F^C|B)P(B)}{P(F^C|B)P(B)+P(F^C|B^C)P(B^C)} $$
The denominator in the last fraction makes use of the Law Of Total Probability.
$$P(B|F^C)=\frac{0.3\times 0.8}{0.3\times 0.8+1\times0.2}=\frac{6}{11}$$
Hope you find this useful

Conditional Probability baffled


Completar valores de uma coluna com valores da propria coluna em data.table

Question: Tenho um data.table() com as seguintes colunas: municipio, ano e pib_per_capta. (na verdade tenho mais 30 colunas, mas para exemplo acho que só isso basta)
A base está toda preenchida de 2005 a 2018.
Entretanto, para o ano de 2019 o pib_per_capta está como NA.
Gostaria de atribuir valor a ele da seguinte maneira: obter a taxa de variação de 2017 e 2018, e multiplicar pelo valor de 2018.
Como isso ficaria?
Obs: 2019 = (2018/2017) * 2018
Obs2: Se souberem como melhorar o título da pergunta, só falar
Exemplo dos dados:
structure(list(municipio = c(110001L, 110001L, 110001L, 110037L,
110037L, 110037L, 110040L, 110040L, 110040L, 110034L, 110034L,
110034L), ano = c(2017L, 2018L, 2019L, 2017L, 2018L, 2019L, 2017L,
2018L, 2019L, 2017L, 2018L, 2019L), pib_per_capta = c(19081.43,
21552.47, NA, 23353.6, 21053.93, NA, 14699.7, 15655.57, NA, 15062.51,
17423.49, NA)), row.names = c(NA, -12L), class = c("data.table",
"data.frame"))

Answer: Aqui vai uma solução. Usa uma função f para calcular o novo valor do pib_per_capta (falta um i em capita).
f <- function(x){
  y <- x[["pib_per_capta"]]
  pib <- tail(y, n = 3)[-3]
  new_pib <- pib[2]^2/pib[1]
  pib <- c(y[-length(y)], new_pib)
  pib
}

dados[, pib_per_capta := f(.SD), by = municipio]


How did "one-to-one" come to mean "injective"?

Question: How did a "one-to-one" function come to mean an injective one? I find it so non-intuitive that I often have to backtrack when reading texts that use "one-to-one" because I suddenly discover that I have been internalizing it as "bijective".
If there was were any logic to the terminology, "one-to-one" would mean bijective and injective would be "(zero-or-one)-to-one".
Perhaps I would be able to remember it better if I knew of any way to make "one-to-one"="injective" make some kind of logical sense, however tenuous. Can anyone suggest one, please?
(To clarify, I know (?) that "one-to-one" is older than "injective", but that doesn't in itself explain how the ancients got the idea of using such a strange and illogical term in the first place.)
Comment: "One-to-one" is in opposition to things like "two-to-one" or "three-to-one"; in general, "$n$-to-one" meant functions for which each image had exactly $n$ **pre** images. (Keep in mind that even th *definition* of function was a bit fluid until recently; you also had "one-to-$n$" 'functions' sometimes). In that sense, "one-to-one" just means that each point in the image has exactly one preimage, what we would expect. "Injective" was, I believe, an attempt at clearing that up, trying to capture the idea that an injective function "injects"/"embeds" a copy of the domain in the codomain.
Comment: I believe the view that functions don't come equipped with codomains used to be more popular than it is now. That could explain the problem.
Comment: I wondered once why "Sale" on a sign meant that the price was reduced, since the word *really* means "dirty."
Comment: @Henning: Point the first: $-13$ is not an image of exp; don't confuse "codomain" with "image". Point the second: we're talking terminology that was being used even when the very object to which it was being applied to, functions, was not very clearly defined! It's hardly surprising that the terminology is not exactly logical or perhaps not intuitive to our way of thinking about these objects (functions) which is very different from the way they were thought of then. Not every word in the language means what it "ought to mean by rights". Compare "flammable" vs. "inflammable". (-;
Comment: @Henning: I didn't realize I was taking a "position." The terminology now has a precise meaning ("$f$ is one-to-one" if and only if for all $a,b$, $f(a)=f(b)$ implies $a=b$), which has evolved over time to take into account the evolving understand of what "function" is. I thought you were asking where the terminology came from and why it was used; I gave what my understanding of that is. As the notion of function evolved, the terminology didn't. You seem to complain that the terminology is not "logical", but terminology and language are not always "logical", often they just "are".
Comment: I don't know if this is the historical idea, but this is how I think of it. Every function with specified domain and codomain has a natural "range" - the image of the domain. In that sense every function is *basically* surjective. The real-valued function $x \mapsto x^3$ is obviously not surjective if you set the codomain to be $\mathbb{R} \cup \{\text{monkey, apple, } e^{i\pi/7}, \dots\}$, but why would you? From the function's point of view, any points that are not hit are reasonably unnatural to mention. In this sense, it means "one point $\leftrightarrow$ one point **on the image**".
Comment: Off-topic. I checked [this](http://jeff560.tripod.com/o.html)(see also Georges's answer) and found 1 entry for *one-to-one correspondence*, and none for *one-to-one*. Also, strangely, the website claims that *onto* was first used as a preposition in 1940, and as an adjective in 1942. This term isn't as old I imagined it to be. :) (*One-to-one correspondence* has been around for a while though.)
Comment: @Chris has a good point. The terminology is completely natural for those of us, like me, who don't automatically think of functions as having codomains. To me a function is first and foremost a set of ordered pairs in which distinct pairs have distinct 1st elements; if distinct pairs also have distinct 2nd elements, it's 1-1, and it's a 1-1 correspondence between its domain and its range. I still think of a codomain as an extra bit of machinery, and as a result I don't think of *onto-ness* as a property inherent in the function itself.
Comment: @Bill, I did not specifically have "one-to-one correspondence" in mind (though now that you mention it, the latter does add to the confusion -- with "correspondence" it is always a bijection, right?). I'm asking for some way to make linguistic sense of "one-to-one" meaning "each element of the codomain is the image of either exactly one _or exactly zero_ elements of the domain".
Comment: @Chris, wonderful. That makes even less sense. I always thought the dash in "one-one" (or "$1 - 1$" as some authors write it) was an abbreviation of "to" in the first place. The term for "surjective" that goes most often with "one-to-one" in my experience is "onto", used as an adjective rather than a preposition.
Comment: Are you asking about "one-to-one" vs. "one-to-one correspondence"?
Comment: Not that this'll reduce the confusion, but there used to be a tradition that "one-to-one" and "one-one" meant "bijective" and "injective", in some order.
Comment: @Arturo, but if I have a function exp: $\mathbb R\to \mathbb R$, then it is _not_ the case that each element of $\mathbb R$ has exactly one preimage; for example $-13$ has zero preimages. Yet the exponential function is injective! True, the _image_ is not the entire codomain here, but in my view this is just an argument that when one specifies the codomain independently of the image, "one-to-one" by rights ought to mean _surjective_ rather than merely injective.
Comment: @Arturo, so your position is that "one-to-one" was simply mis-adapted when the old function concepts gave way to "a function $A\to B$ is a subset of $A\times B$ that satisfies such-and-such conditions"? It is uncontestable that today "one-to-one" is used by authors who do view a function as something that has (at least contextually) a codomain distinct from the image of the domain, as witnessed by phrasings such as "... it is clear that $f$ is one-to-one, but we have yet to show it is also onto ..."
Answer: In the old usage, as well as contemporary usage in set theory, one may consider a function without specifying a particular codomain or target set. (The insistence that a function come along with a particular codomain is a comparatively recent innovation, probably arising in Bourbaki.)
That is, if one understands a function merely to be a set of ordered pairs satisfying the function property (that each input is associated to one output), or as a rule associating to every object in a domain an output value, then it is true to say that a function is one-to-one if and only if it is a bijection from its domain to its range. Thus, injective functions really are one-to-one in the sense that you want.
Of course, this one-to-one terminology was long established by the time Bourbaki wanted to insist that functions come along with a specified co-domain, giving the definition of function as a triple consisting of domain, codomain and set of ordered pairs. The fact that in this context the concept of one-to-one doesn't tell the whole story may be part of the reason that they introducted the injective, surjective, bijective terminology.
But meanwhile, a function is one-to-one if and only if it provides a one-to-one correspondence between its domain and its range. This is perfectly logical, and seems to be the explanation that you are seeking. I would think that the one-to-one terminology   begins to seem illogical only when one also insists on attaching to the function a target set or codomain that is not the same as its range, which is, after all, a somewhat illogical thing to do.
Comment: (cont'd) ... Also axiomatic ST cannot easily express everyday inclusion-identifications such as $\mathbb N\subseteq \mathbb Z \subseteq \mathbb Q \subseteq \mathbb R \subseteq \mathbb C$ -- at least not without redefining either equality or membership significantly, which would sort of defeat the entire purpose. None of this is, of course, a relevant criticism of ST for the purpose it was developed to serve, but I think it constitutes a good argument that ST is ill-suited as a final arbiter of which concepts and notations should be considered "logical" in mathematics as a whole.
Comment: Accepted, though I don't agree that it is in any way illogical to consider a function having domain and codomains as separate attributes. It is true that this isn't done in axiomatic set theory, but axiomatic ST is something like the "untyped assembly language" of mathematics; one has to rely on more or less informal typing rules in order to formalize a standard mathematical argument in strict ST. For example, in many developments of ST, $3=\{0,1,2\}$ by definition, but in standard mathematics, if $f(x)=x^2$, then $f(\{0,1,2\}) = \{0,1,4\}$ but $f(3)=9\ne\{0,1,4\}$.
Comment: Thanks for accepting! My remark about "illogical" was tongue-in-cheek; but I believe your "in any way" remark to be over-stated, since of course it is perfectly reasonable to consider a functional rule without specifying a codomain. My view is broad and encompassing; please see my answer at http://mathoverflow.net/questions/30397. It seems inaccurate to suggest that set theorists cannot easily account for the  distinctions you mention, and historically, of course, these issues were first resolved by set theorists.
Comment: We probably shouldn't diverge into too long a debate here, but do note that I'm speaking about set _theory_ rather than set _theorists_. The set theorists I've met have been no less able to work and argue in a variety of styles and traditions than anyone else.
Answer: The terms injectif, surjectif and bijectif are lexical creations of Bourbaki. Their first appearance was in Chapters I  and II  of his  Théorie des Ensembles, published in 1954. (Mac Lane and others knew about them and had used them in print slightly before)
Surjective functions were called fonctions sur in contradistinction to general functions, just called fonctions dans. Bourbaki was very attentive to the quality and beauty  of the French he used and found it shocking to use the preposition "sur", instead of a genuine adjective, to qualify the name "function". Hence the neologisms.
Here is a link, in English, to this theme (look at the entry "Injection, surjection and bijection").
As to the terminology one-to-one, your actual question !, the reference I give attributes its first use to Zeuthen in 1870 (in French). The first appearance in English dates from 1873. There is also a reference to its use by Bertrand Russell in 1903.
The above doesn't really answer your question on the reasons why mathematicians used the terminology "one-to-one" but has the advantage of giving hard facts. As to these  reasons, the suggestions and guesses in the comments look very reasonable and informed and I second them. And, by the way,  your statement that one-to-one predates injective is now proved to be absolutely correct.
Comment: That's a great answer to "How did "injective" come to mean injective?". But that's not the question being asked.
Comment: @Bill: I suppose Jeff Miller is the author of the pages I link to? Then the parenthetical remark in paragraph 1 and section 4 are excerpted from there. On the other hand the linguistic remarks on prepositions, adjectives, and Bourbaki's attention to stylistic elegance are my recollections of  discussions with people  who had been  members of or close to Bourbaki . I didn't mention that since it might look like name-dropping.
Comment: @Georges Thanks for the clarification. That's useful to know, since sometimes the information on JM's pages in not completely accurate.
Comment: Indeed it isn't. The history of "injective" is well documented on the net; that of "one-to-one" is, as far as I can tell, completely opaque.
Comment: @Chris: I have acknowledged what you wrote in my answer.
Comment: @ Henning: the link in my answer gives the history of "one-to-one": I have  edited my text to  make this explicit. As to your remark about the history of "injective" being well documented on the net, it is remarkably  accurate, but I am not sure what this is supposed to imply. My ambition has never been to give information which can't be found anywhere on the net: this would amount to a permanent ban from this site for me, and presumably for others too.
Comment: @Georges It would be helpful to clarify if your entire answer is merely an excerpt of Jeff Miller's pages, or whether it contains something beyond that - perhaps independently researched. This is not clear from what you have written.


own goal from cross

Question: I was playing FIFA, and Bale crossed it in, from where an opposing player tried heading it out, but knocked it into his own goal. The goal was given to Bale. Was that an own goal, or was the game right in giving the goal to Bale?
Comment: I'm voting to close this question as off-topic because it's about a computer game, not the real sport.
Comment: Probably a computer error, then. Note that people have reported events where a GLT screen showed the ball clearly not a goal/clearly a goal, with either (or both of) the commentary track and the scoreline being the opposite.
Comment: You should better ask on Arqade.SE, which is the appropriate venue for questions about video games of any kind. This is a venue for sports questions. Had you asked what rules apply in real-world games, this would be acceptable (and I believe such a question already exists).
Comment: Was the ball going in anyway without the defender's touch?
Comment: no. it came in and if no one had hit it, it would have gone out toward the other wing. https://postimg.org/image/qnkcgwqgf/
Comment: It's about a game about the game... what's the problem?
Answer: Based on current Laws of the Game, there's no official guidance for declaring what constitutes an own goal; that is, declaring the scorer of a goal (regardless of whether it's an attacker or defender) is not part of the "official" rules.
That said, most current leagues rely on the following guideline:

If the ball was struck by an attacker and was headed towards the goal before a defender intervened, then the attacker is credited with the goal.  If the ball was headed wide, or high, or anywhere else not on target after the last attacker touched it, then was touched by a defender or the goalie and went in, it's considered an own goal.

This can be a bit silly, of course.  You've probably seen, for example, free kicks that—while indeed on target—were going to be easily saved by the keeper before they took a deflection and wound up in the goal.  The attacker gets credit for the goal because the initial shot was on target.
And this means that cruelly, a keeper can be credited with an own goal if a ball hits the woodwork and is headed out, then hits the keeper and goes in.
The English Premier League even has a Dubious Goals Committee to rule on goals where the official scorer is in doubt.  This obviously has no effect on the most important fact: the final score of the game, but it is used to keep consistent statistics.

In your case, it sounds like a classic own goal, unless Bale's original cross was headed towards the goal anyway.  Sounds like the game made a scoring error.
Comment: It's a very nice answer. You mentioned "Based on current Laws of the Game, there's no official guidance for declaring what constitutes an own goal". I can understand that. But should there be a guideline or instruction on this? I can't find it on the internet.

own goal from cross


Passar List para ActionResult

Question: Resumidamente:
Tenho uma tela com uma table populada pela lista abaixo, aonde seleciono a linha através de checkbox, preciso passar essa lista para a minha actionResult.
Como não tenho um formulario nessa tela não consigo dar submit nos dados para passar para a actionResult.
ViewModel usado no html com a propriedade lista
    public class DeliveryServiceListViewModel
{
     public List<DeliveryServiceViewModel> DeliveryServices { get; set; }
}

ActionResult:
public ActionResult EditAll()
{
}

Que eu chamo dessa maneira que não sei se é a correta:
<button onclick="email@example.com("EditAll", "DeliveryService")'">
    Salvar
</button>

Como passar a lista para eu tratar no controller?
Tem como eu passar apenas a lista ou eu tenho que passar todo o ViewModel que contem a lista?

Tentei passar a lista usando new { DeliveryServices = Model.DeliveryServices }, mas ela chega no controller vazia.
 @model Dlieve.BackOffice.Areas.BackOffice.Models.DeliveryServiceListViewModel

        Portador
        Cliente
        Data de Cadastro
        Descrição
        Status
        Motivo Entrega Não Realizada
        <input type="checkbox" id="selectAllCheckBoxes" />

                <button onclick="enviarFormulario()">Salvar</button>
                <button id="cancel">Cancelar</button>

    @if (Model != null)
    {

        for (int i = 0; i < Model.DeliveryServices.Count; i++)
        {
            var checkboxChecked = Model.DeliveryServices[i].IsSelected;

                @Html.DisplayFor(modelItem => carrierFullName)
                @Html.DisplayFor(modelItem => shipperCustomerFullName)
                @Html.DisplayFor(modelItem => Model.DeliveryServices[i].Created)
                @Html.DisplayFor(modelItem => Model.DeliveryServices[i].Description)
                @Html.DisplayFor(modelItem => Model.DeliveryServices[i].DeliveryServiceStatusModel.Description)
                @Html.DisplayFor(modelItem => Model.DeliveryServices[i].NonDeliveryDescription)

                @*declaração de variavel local para simplificar o tratamento condicional de "description"*@
                @{var description = Model.DeliveryServices[i].DeliveryServiceStatusModel.Description;}
                @if (description == "Em Andamento" || description == "Roteirizado")
                {
                    @Html.CheckBoxFor(modelItem => Model.DeliveryServices[i].IsSelected)
                }
                else
                {

                }
                        }
                    }

Comment: Sua pergunta está confusa. Um botão `submit` tendo um `Javascript` sem sentido no meu entender, parece ser o problema.
Comment: retirei o submit, o botão chama a `ActionResult` porem não sei passar a minha lista como parâmetro.
Comment: poste o seu `form` completo....?
Answer: Seu problema pelo visto é porque você não está dando o submit no form e sim simplesmente redirecionando para a action no click do botão. Com isso as informações não serão passadas para a controller porque o post não está sendo feito, por isso sua lista chega nula.
Comment: Você tem razão, Editei a minha pergunta.
Answer: Isto não dispara um POST:
<button onclick="email@example.com("EditAll", "DeliveryService")'">
    Salvar
</button>

Aliás, não entendi qual o objetivo de usar o button assim. De qualquer forma, se você realmente precisa que o JavaScript faça o POST pra você, terá que mudar para:
<button onclick="enviarFormulario()">
    Salvar
</button>

E depois:
function enviarFormulario()
{
    $.post("@Url.Action("EditAll", "DeliveryService")", { campo1: $('#campo1'), campo2: $('#campo2'), campo3: $('#campo3') }, function(result) {
        // Faça alguma coisa aqui com result
    });
}

Esse exemplo usa jQuery.

EDIT
A ideia é o seguinte:
function enviarFormulario()
{
    var lista = [];
    $(":checkbox").each(function(index) {
        lista.push({ "Campo1DoDeliveryServiceViewModel": "Valor1",
                     "Campo2DoDeliveryServiceViewModel": "Valor2",
                     "Campo3DoDeliveryServiceViewModel": "Valor3" });
    });

    $.post("@Url.Action("EditAll", "DeliveryService")", lista, function(result) {
        // Faça alguma coisa aqui com result
    });
}

Acredito que você queira mandar o valor das checkboxes para o Controller. Possivelmente será necessário preencher alguma coisa com o Id e o respectivo valor da checkbox.
Comment: Na verdade não preciso que ele faça para min, editei minha pergunta acho que ficou mais clara. O que eu não sei fazer é pegar a lista que popula minha `table` e passar para a `actionResult`.
Comment: Pois então. Isso não muda em nada o conteúdo da minha resposta. Implemente os passos que coloquei e verá a lista ser materializada corretamente no *Controller*.
Comment: fiz do modo que você falou e a chamada deu certo ele bate na `actionResult`, porem a minha lista, que popula a minha ``, que é um propriedade da minha ViewModel, eu não sei passar pelo `$.post`
Comment: É, então. Você terá que construir o objeto usando JavaScript. Editando sua pergunta e colocando o HTML/Razor da ``, posso montar algo pra você.
Comment: entendi, editei colocando o código da ``
Comment: @Vinicius Veja se ficou mais claro agora.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/53133/discussion-between-vinicius-and-cigano-morrison-mendez).

Passar List para ActionResult


Para que serve um scope no Laravel?

Question: Vi na documentação do Laravel uma explanação sobre a utilização do Eloquent. Lá eu vi uma parte onde fala sobre Local and Global Scopes.
Como não domino muito o inglês, fiquei com algumas dúvidas quanto ao uso.

Para que serve esses métodos onde definimos o prefixo scope nos models?
Qual é a diferença entre Local e Global scope?

Exemplo da documentação (local scope):
class User extends Model
{
    /**
     * Scope a query to only include popular users.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }
}

Exemplo documentação (global scope):
class User extends Model
{
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('age', function(Builder $builder) {
            $builder->where('age', '>', 200);
        });
    }
}

Answer:
Para que serve esses métodos onde definimos o prefixo scope nos models?

Tem a finalidade de facilitar rotinas de consultas no seu model (Eloquent), trazendo funcionalidades prévias de consultas SQL, ajudando, então, no  desenvolvimento e padronização de consultas. É divido em Global Scope ou Local Scope.

Qual é a diferença entre Local e Global scope?

Global Scope limita ou restringe o seu model a executar filtros prévios (where, order by) em todas as consultas SQL de um determinado model (Eloquent). Seria uma padronização para esse model que na execução de consultas tenham esse filtro. Um exemplo claro é a exclusão de um determinado registro onde o determinante é uma data com o valor null a consulta traz o registro, diferente de null o registro não aparece, seguindo a lógica do soft-deleting.
Exemplo:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Cliente extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

No caso acima se codificar Cliente::all(), trará a lista de todos os clientes que não foram excluídos, porque, o Global Scope  do traits SoftDeletes tem um filtro restritivo e global a todas as consultas (select * from clientes where deleted_at is null). Se por acaso quiser trazer todos os registros inclusive os excluídos faça o comando Cliente::withTrashed()->get(), sendo uma forma elegante de burlar esse Global Scope. Uma forma radical de elimitar todos os Global Scope seria assim Cliente::withoutGlobalScopes()->get().
Já no Local Scope é um filtro preparado, ou atalho, que só é executado mediante chamada do método, sendo diferente do Global Scope que é sempre chamado de forma automática e transparente. Tem as mesmas características, mas a forma de invocação é o que difere.
Exemplo:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Cliente extends Model
{
    use SoftDeletes;

    public function scopeStatus($query)
    {
        return $query->where('status', 1);
    }

    protected $dates = ['deleted_at'];

}

Existe nesse model Cliente um scopeStatus que eu defini um filtro onde status = 1, mas, eu preciso invocá-lo para que ele passe a ser executado e a consulta receba mais esse filtro.
Cliente::status()->get();
//SQL => select * from cliente where `status = 1`

se eu colocar simplesmente:
Cliente::all();
//SQL => select * from cliente

a SQL não terá o filtro, ou seja, o Local Scope precisa ser invocado para funcionar.
Mesmo com Global Scope e Local Scope, nada impede a continuação de filtros, ordenações, junção de tabelas, etc. esses dois meios são para facilitar a não repetição de código, padronizando e auxiliando no desenvolvimento e manutenção do código.

Para que serve um scope no Laravel?


What happens when a pin slides but does not fall?

Question: Recently, I had a spare attempt with the 7-pin. I bowled a ball that hooked sharply before it hit the 7-pin. As a result, the pin slid toward the middle of the lane, but did not fall. I have seen some occasions in which this would have counted as a spare/fallen pin, but it did not count in my case.
Would this have been considered a spare/fallen pin or an open frame/pin left standing? Generally, what happens when a pin slides but does not fall?
Answer: A pin is only considered fallen when it is knocked down or knocked off the lane surface.  In the case you mentioned, where the pin slid but did not fall during your second ball, the pin would be considered left standing, and it would not be a spare.  If this had happened during your first ball, the pin needs to be left where it was, and if the pinsetter knocked the pin down afterward, the pin would need to be replaced at its original position.
From the United States Bowling Congress Playing Rules, Rule 6a (Pinfall, Legal Pinfall):

6a. Legal Pinfall
  Pins to be credited to a player following a legal
  delivery shall include:

Pins knocked down or off the lane surface by the ball or another pin.
Pins knocked down or off the lane surface by a pin rebounding from a side partition or rear cushion.
Pins knocked down or off the lane surface by a pin rebounding from the sweep bar when it is at rest  on the pin deck before sweeping dead
  wood from the pin deck.
Pins that lean and touch the kickback or side partition. All such pins are termed dead wood and  must be removed before the next
  delivery.

No pins may be conceded, and only pins actually knocked down
  or moved entirely off the playing area  of the lane surface as a
  result of a legal delivery may be counted.

From Rule 7a (Pins, Improperly Set):

No change can be made in the position of any pin(s) left standing
  after the bowler's first  delivery, unless:

The pinsetter moved or misplaced any pin(s), or
Any standing pin(s) is (are) outside the range of the sweep bar.

Any such pin(s) will be respotted where it (they) originally stood
  before the delivery.


include do css em outras páginas

Question: Estou tentando colocar o CSS dentro de uma subpasta com o include, mas não consigo. Já usei ../, .../, todos os tipos possíveis, mas não consigo.
a estrutura do meu projeto está assim:

css[pasta]/css.css
pages[pasta]/anuncios_user[pasta]/anuncios.php
includes[pasta]/menu.php

Eu só consigo chamar o CSS pelo include até os arquivos que estão na pasta "Pages", mas quando chamo o include do menu, onde tem todos os links de CSS e afins, ele não vem.
Comment: Qual o código que você está usando? O `include` é do *PHP* ou do *CSS*?
Comment: é o include do php, nesse include tem a tag html ate o body
Answer: Da algum erro?
quando inspeciona a pagina os links do css estão lá?
você disse: "é o include do php, nesse include tem a tag html ate o body"
vc está dividindo certo os includes para que o conteudo da pagina fique em body?
Outra coisa, pra você subir duas pastas tem que repetir ../../ e assim por diante.

include do css em outras páginas


What kind of a thing is the forgetful thing $\mathrm{Hom}_\mathbf{C}(-,X) \rightarrow \mathbf{C}/X$?

Question: Let $\mathbf{C}$ denote a category and suppose $X$ is an object of $\mathbf{C}$. Then intuitively, there should be a "forgetful something" from the hom-functor $\mathrm{Hom}_\mathbf{C}(-,X)$ to the slice-category $\mathbf{C}/X.$ But its just not clear to me what this forgetful something is. Since the domain is a functor, my first guess would be that it is a "forgetful natural transformation". But since the functors $\mathrm{Hom}_\mathbf{C}(-,X) : \mathbf{C} \rightarrow \mathbf{Set}$ and $\mathrm{id}_{\mathbf{C}/X} : {\mathbf{C}/X} \rightarrow {\mathbf{C}/X}$ aren't parallel, there is no concept of a "natural tranformation" from $\mathrm{Hom}_\mathbf{C}(-,X)$ to $\mathbf{C}/X.$
So, what kind of a thing is the forgetful thing $\mathrm{Hom}_\mathbf{C}(-,X) \rightarrow \mathbf{C}/X$?
Comment: You can see $\operatorname{Hom}(A,X)$ as the fiber over $A$ of the forgetful functor $\mathbf{C}/X \to \mathbf{C}$. I think that makes more sense. Maybe some notion of [fibration](http://ncatlab.org/nlab/show/fibration#fibrations_in_category_theory) can work here (Grothendieck fibration, Cartesian fibration -- I'm not really an expert).
Comment: I'm not sure it is what you're looking for but one link between the two is the following : $\hom(-,X)$ is the colimit of the diagram $\mathbf C/X \to \mathbf C \to [\mathbf C^{\mathrm{op}},\mathsf{Set}]$ (where the first arrow is the forgetful functor and the second the Yoneda embedding). Another way too see it : $\mathbf C/X$ is the category of elements of $\hom(-,X)$.
Comment: I don't think that's very intuitive... $\operatorname{Hom}_{\mathbf C}(-, X)$ is essentially the same thing as $X$, because of the Yoneda lemma (it's part of the subcategory of $\operatorname{Fun}(\mathbf{C}^{op}, \mathbf{Set})$ of representable functors, which is equivalent to $\mathbf{C}$). I don't really see what sort of "transformation" $X \to \mathbf{C}/X$ could be meaningful. And I don't really see what kind of information you could "forget", too...
Comment: @NajibIdrissi The forgetful functor $\mathcal{C}_{/ X} \to \mathcal{C}$ is precisely the discrete fibration corresponding to $\mathcal{C} (-, X)$, via the Grothendieck construction.
Answer: For a functor $F : \mathcal{C} \to \mathsf{Set}$ you may consider its category of elements $\int F$. The objects are pairs $(X,s)$ with $X \in \mathrm{Ob}(\mathcal{C})$ and $s \in F(X)$. It is clear how to define the morphisms.
We have $\int \mathrm{Hom}_{\mathcal{C}}(-,X) \cong \mathcal{C}/X$ and $\int \mathrm{Hom}_{\mathcal{C}}(X,-) \cong X/\mathcal{C}$.


PHP swap 0 with +44

Question: I get the following variable
$inputMobile = $_POST["inputMobile"];

Now numbers can come in a variety of ways e.g.
07714....
+447714...
00447714...

What I need to do is make sure that whatever number I get, I change it to start with +44.  I had something like this
$inputMobile = $_POST["inputMobile"];
    if (substr($inputMobile, 0, 1) === '+44') {
        $inputMobile = $_POST["inputMobile"];
    }
    else {
        $inputMobile = preg_replace('/^0?/', '+44', $inputMobile);
    }

The problem is, if I give it a number like +447714, it returns +44+44714.
How can I stop this from happening?
Thanks
Comment: "If the first character is this sequence of three characters..." might be the crux of your problem here.
Comment: `substr($inputMobile, 0, 1) === '+44'` can never be `true`.
Answer: As others have pointed out, you are using substr incorrectly by comparing a 3-character string (+44) to a 1-character string (substr($inputMobile, 0, 1)). Try this, instead:
$inputMobile = $_POST["inputMobile"];

$inputMobile = preg_replace('/^(0*44|(?!\+0*44)0*)/', '+44', $inputMobile);

What this is does is replace a leading 044 or 44 (as well as any following zeroes) with +44 and, if the number doesn't have a leading 044 or 44, just adds +44 at the beginning.
Here's a demo. The following examples:
07714....
+447714...
00447714...

are all standardized and become +447714.

PHP swap 0 with +44


Find the confidence in an accuracy measurement

Question: I have a dataset with billions of values that either belong to a certain group or not. Let's say for example that I have sports equipment and I'm categorizing as 'tennis' or some other sport. I sample 100 products at random and manually determine whether my model has categorized within the correct category. I find that 95 are correctly categorized.
I then go to my stakeholders and say that my model is 95% accurate. However, I think there is missing nuance. I should probably say something like, "I'm 99% confident that the model is between 94% and 96% accurate" -- not something usually mentioned along with an accuracy metric.
Multiple questions: 1) How do I state my confidence that I'm 95%+ accurate 2) How do I determine my range and state my confidence there 3) Is my experiment sampling 100 items giving me a different metric than I think it is.
I know that standard error (sample std. dev/sqrt(n sampled)) will give me the normal distribution of the error on a metric (e.g. weather temperature). Does this also hold where the metric is an accuracy measurement (i.e. another metric derived based on the data)? And in this case is the n samples the number of accuracy measurements (i.e. I sampled 100 n times) or is n related to the number of samples I took from the population for my accuracy measurement?
Comment: You're on the right track with standard errors, but note that the standard error you mention (sample std. dev/sqrt(n sampled)) is the standard error of one particular parameter, the mean. The standard error of the accuracy proportion will capture the sample-to-sample variability of the accuracy estimate in the way you're looking for, but requires a different formula.
Answer: Assuming appropriate independence, you're looking at estimating a proportion from Bernoulli draws. The standard error of this estimation is
$$\mathrm{se}_p = \sqrt{\frac{p(1-p)}{n-1}}$$
where $n$ is the number of samples you drew to estimate $p$.
In your case, this means the standard error of your 95 % is
$$\mathrm{se}_p = \sqrt{\frac{0.95(0.05)}{99}} = 0.022$$.
You can then be 90 % confident that the population proportion is in the range $p\pm1.645\mathrm{se}_p$, which is the range between 91 % and 99 %.
If you want to be 99 % sure, the appropriate two-sided Z score is around 2.48, meaning the confidence interval is between 89 % and 100 %.
See e.g. chapter 3 of Cochran's Sampling Techniques (1953) for more.


Excel - Looking up a cell in a table and then using if statements to decide which column to use

Question: I am trying to calculate how many standard deviations a particular performance is away from the mean for many different data points.
For example, I have the standard deviation for all kids in a class separated by hair color and then further separated by eye color. Then using each of those as its own group I want to know how many deviations away from the mean any particular height may be.
So in the attached document, I need to write the formula in column F to look up the standard deviation.  Essentially, I want to look up the number in column A to the table in column J, then based on that value lookup the height (column E) and see were it lies with in the the table and have it spout out an answer between k2:Q2
<code>    Hair    Eyes    Mean    Height  SD      Standard Deviation
1   Blonde  green   62" 61" ??          -2  -1  0   1   2
2   Blonde  brown   65" 60" ??      1   58" 60" 62" 64" 66"
3   Blonde  hazel   66" 63" ??      2   57" 61" 65" 69" 73"
1   Blonde  green   62" 66" ??      3   60" 63" 66" 69" 72"
4   Blonde  blue    67" 62" ??      4   61" 64" 67" 70" 73"
2   Blonde  brown   65" 63" ??      5   51" 56" 61" 66" 71"
5   Brown   brown   61" 70" ??      6   53" 58" 63" 68" 73"
6   Brown   hazel   63" 60" ??      7   66" 68" 70" 72" 74"
7   Brown   green   70" 68" ??      8   58" 59" 60" 61" 62"
6   Brown   hazel   63" 65" ??      9   58" 61" 64" 67" 70"
6   Brown   hazel   63" 62" ??      10  64" 66" 68" 70" 72"
8   Grey    green   60" 59" ??
9   Grey    blue    64" 66" ??
10  Grey    hazel   68" 67" ??
9   Grey    blue    64" 61" ??
</code>
Comment: I have a table but i'm not sure how to post it onto here so you all can see it.
Comment: OP, I realize you may just be a scientist but please understand that science doe not live in a vacuum. Please be aware of intersections.
Answer: IN F2:
<code>=INDEX($H$2:$L$2,MATCH(E2,INDEX($H$3:$L$12,MATCH(A2,$G$3:$G$12,0),0)))
</code>
Then copy down.

One note this will throw an error if the height is less than lowest measurement.


For what conditions the integral is a rational function.

Question: I have tried to solve a problem here and I've got an answer but I just don't know if it is the right one.
The problem is: For what conditions
$$\int \frac{ax^2+bx+c}{x^3\left(x-1\right)^2}dx$$
represents a rational function.
First I have calculated the integral and the result is:
$$\left(a+2b+3c\right)\ln\left|x\right|-\frac{2c+b}{x}-\left(a+2b+3c\right)\ln\left|x-1\right|-\frac{a+b+c}{x+1}-\frac{c}{2x^3}+K$$
where $K$ is a constant.
From here I have taken the conditions $$\left(a+2b+3c\:=\:0\right) \mbox{ and } ((b+2c != o) \mbox{ or } (a+b+c != 0))$$ which is the same as
$$\left(a\:=-2b\:-3c\right) \mbox{ and } (b != -2c)$$
So, from my result, the condition above must be satisfied in order for that function to be a rational function.
P.S != means not equal to
Can anyone tell whether the solution is correct or not and if it is not then help me with it ?
Thank you very much!
Answer: The only condition you want is that the coefficient in front of the logarithms are zero, the rest is considered to be a rational function (also, a polynomial is considered to be a rational function). In your case, this means that
$$
a+2b+3c= 0.
$$
(The term $-(a+b+c)/(x+1)$ should be $(a+b+c)/(1-x)$, but that does not change the answer.)
Comment: So the function f(x) = K where K is a constant is considered a rational function(because K is a polynomial of degree 0) ?
Comment: Yes indeed, it is $p/q$ where $p=K$ and $q=1$ (for example).
Answer: Since
$$\frac{1}{x^3\left(x-1\right)^2}=\frac{1}{(x-1)^2}-\frac{3}{x-1}+\frac{3}{x}+\frac{2}{x^2}+\frac{1}{x^3},$$
it follows that the integral of $(ax^2+bx+c)$ over $x^3\left(x-1\right)^2$ is rational iff, in the integrand function, the coefficient of $1/x$, that is $a+2b+3c$, and the coefficent of $1/(x-1)$, that is $-(a+2b+3c)$ are zero.
So the condition should be simply $a+2b+3c=0$.


Prve that $x^4+x^2+x+1$ is irreducible over $\mathbb{Q}$.

Question: I try Eisenstein's Criterion, replacing $x$ as $x+1$, $x+2$ or $x-1$. But they are the forms we need.
Comment: it has no roots since it is always strictly positive on $\mathbb R$. This means it has two couples of complex roots, so you have to check it doesn't split into the product of two quadratic polynomial with rational coefficients
Answer: Let $f(x)=x^4+x^2+x+1$. Suppose that $f$ is not irreducible. $f$ has no rational root by the rational root theorem. Hence $f$ does not factor as $(x-\alpha)(x^3+\ldots)$ where $\alpha \in \mathbb Q$.
Thus $f$ is the product of two polynomials of degree $2$. Since the leading coefficient of $f$ is $1$, and the constant coefficient is $1$ as well, either $\forall x, f(x)=(x^2+ax+1)(x^2+bx+1)$ or $\forall x, f(x)=(x^2+ax-1)(x^2+bx-1)$.
In the first case, equating coefficients of degree $3$ and $1$ yields $0=a+b=1$. In the second case, the same reasoning yields $0=a+b=-1$.


Realizar um Sum geral com todos os campos

Question: Tenho as seguintes tabelas: tb_produto, tb_movimento
COD_PROD  | DESCRICAO | TIPO     |
|01       | CEBOLA    | ALIMENTO |
|02       | ARROZ     | ALIMENTO |
|03       | CARNE     | ALIMENTO |
|04       | COCA-COLA | BEBIDA   |
|05       | PINGA     | BEBIDA   |

COD_MOV | COD_PROD | QUANT.|
|01     |  01      | 5     |
|02     |  05      | 8     |
|03     |  02      | 10    |
|04     |  05      | 4     |
|05     |  03      | 1     |

sql
 select
  CASE WHEN tb_produto.tipo = 'ALIMENTO' THEN
    sum(tb_movimento.QUANT*1)
  ELSE
    SUM(tb_movimento.QUANT*2)
  END
 from tb_movimento, tb_produto
 where (tb_produto.cod_prod = tb_movimento.cod_prod)
 group by tb_produto.tipo

Meu retorno:
|CASE|
|16  |
|24  |

No meu caso gostaria que me retorna-se:
|CASE|
|40  |

Comment: Não é só tirar o group by?
Comment: Seu eu tirar o groyp by ele não roda "Invalid expression in the select list (not contained in either an aggregate function or the GROUP BY clause)."
Answer: Como tem dois tipos de produtos e o select esta agrupando por tipos de
produto é natural que ele exiba o resultado desse modo.

Não tenho o FIREBIRD para testar e estou postando uma resposta testada
  no Oracle, pelo o que me lembro, funciona no seu banco sem problemas.
Se tiver problemas no seu banco poste aqui que corrigimos.

Faça assim:
select sum( total ) from (
 select
  CASE WHEN tb_produto.tipo = 'ALIMENTO' THEN
    sum(tb_movimento.QUANT*1)
  ELSE
    SUM(tb_movimento.QUANT*2)
  END as total
 from tb_movimento, tb_produto
 where (tb_produto.cod_prod = tb_movimento.cod_prod)
 group by tb_produto.tipo ) a

Answer: Faça assim:
select
sum(tb_movimento.QUANT * (case when tb_produto.tipo='ALIMENTO' then 1 else 2 end))
from tb_movimento
inner join tb_produto on tb_produto.cod_prod = tb_movimento.cod_prod
Melhoria:
Case usado para definir o fator  de multiplicação.