Class App\Http\Controllers\Requests\ArticleRequest does not exist Laravel5.3

Question: Actually I'm very new of the php and Laravel5.3,and I have this problem when i want to set request of the form(Doing a simple blog page)
ReflectionException in Route.php line 339: Class App\Http\Controllers\Requests\ArticleRequest does not exist
And this is my controller code(Filename:ArticlesControllers.php):
 <?php

    namespace App\Http\Controllers;
    //namespace App\Http\Controllers;
    use App\Http\Requests\ArticleRequest;
    use App\Article;
    use Carbon\Carbon;
    use Illuminate\Http\Request;

    class ArticlesControllers extends Controller
    {
        //
        public function index(){
            $articles = Article::latest()->get();
            //return 'articles';
            return view('articles.index')->with('articles',$articles);
        }

        public function show($id){
            $article = Article::find($id);
    //        if(is_null($article)){
    //            abort(404);
    //        }
            //dd($artilce);
            return view('articles.show',compact('article'));
        }

        public function create(){
            return view('articles.create');
        }

        public function store(Requests\ArticleRequest $request){
            //dd($request->all());
            //接受post过来的数据
            //存入数据库
            //重定向
            $input=$request->all();

            //$input['published_at']=Carbon::now();
            Article::create($input);
            return redirect('/articles');
        }
    }

And the request File code:(Filename:ArticleRequest.php in the path Requests)
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ArticleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title'=>'required|min:3',
            'content'=>'required',
            'published'=>'require'
        ];
    }
}

My Route/Web.php is:
   <?php

    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */

    //Route::get('/','SiteController@index');

    Route::get('/', function () {
        return view('welcome');
    });

    Route::get('/articles','ArticlesControllers@index');
    Route::get('/articles/create','ArticlesControllers@create');
    Route::get('/articles/{id}','ArticlesControllers@show');

    Route::post('/articles/store','ArticlesControllers@store');

How can i get rid of this nasty problem,I've been searching on StackOverFlow but nearly all the answers may not solve it....
Comment: are you create any authentication system for your project?
Answer: Change it to this to make it work:
public function store(ArticleRequest $request)

Answer: you already imported the class at the top
use App\Http\Requests\ArticleRequest
no need to use a full class name as an argument
just use
public function store(ArticleRequest $request)
or
public function store(\App\Http\Requests\ArticleRequest $request)
Comment: @charliefreak  Charlie, please mark this answer as the correct answer so people won't have to see this question because they are know that it's answered (and to give reputation to the people who give the correct answer) : http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work


Goodness of fit of vector error correction model (VECM)

Question: I am trying to find the relationship between S&P and six macroeconomic variables using vector error correction model (VECM).
What are the criteria for assessing the overall performance of the model?
I got low $R^2$ (see the output below), but this is OK for I(1) time series, I guess.
Comment: You can also use `estat ic`.
Answer: If you got low $R^2$ when the response variable is the first difference of an integrated variable (which I understand is the case), then it is as expected; if you had got that when the response variable were the level (rather than the first difference) of an integrated variable, that would have been less satisfactory.
As for "overall performance", I would do some residual diagnostics to make sure there are no pronounced ugly features such as large spikes/outliers, clear patterns across time, etc.
If you care about forecasting performance, try doing fair out-of-sample forecast evaluation. For example, use rolling windows to determine the model order and estimate the model in-sample and measure forecasting performance out of sample across the rolling windows. You may use root mean squared error or another measure you find relevant for forecast accuracy. You could also compare the performance of your model to that of some simpler benchmark model using the Diebold-Mariano test.


Replace words in a string based on the rules

Question: I have a string like this
"Hello {{firstName}}, this is {{senderName}}."

The rules
rules = {
  firstName: "Alex",
  senderName: "Tracy"
}

Expect result
"Hello Alex, this is Tracy."

I want a generic function to convert any string with the corresponding rules to a new string.
Another example:
let array = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
rules = {
  firstName: "Alex",
  lastName: "James",
  senderName: "Tracy"
}
expectedResult = "Hello Alex James, this is Tracy."

Any help wound be appreciated.
Answer: you can loop through and replace all variable with value
    function resolve_str(rules,str){
      for(let i in rules){
        str = str.replace("{{"+i+"}}", rules[i]);
      }
      return str;
    }

    let array = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
    rules = {
      firstName: "Alex",
      lastName: "James",
      senderName: "Tracy"
    }

    console.log(resolve_str(rules,array));

Answer: You can take advantage of a replacement function that can be passed to String.prototype.replace:

const str = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
const mapping = {
  firstName: "Alex",
  lastName: "James",
  senderName: "Tracy"
}
const compile = (template, rules) => template.replace(/{{(.+?)}}/g, (match, group) => rules[group]);

const result = compile(str, mapping);
console.log(result);


php function returning 0?

Question: ok, so i am creating a php login system and wanted a simple way to get the link to the logout page by calling a function but it keeps returning 0. He's my function:
function logout_link() {
include("auth_vars.php"); //This file contains $auth_path_login
return $auth_path_login+"?status=loggedout";}

and this is how i am using it:
<a href="<?php echo logout_link();?>">logout

However it keeps producing:
logout

What is going wrong ?
Comment: Use `.` to concatenate strings in PHP, not `+`
Comment: What *exactly* does `auth_vars.php` contain?
Comment: Can't say much more without seeing auth_vars.php, but it looks like something in that file may return 0. Try moving the include to the top of the file instead of inside the function. Edit: @Pekka is right,  that's your problem.
Answer: The operator for string concatenation is ., not +.
See http://www.php.net/manual/en/language.operators.string.php
Comment: It's a common mistake; still happens to me sometimes when I switch from Java to PHP.
Answer: In PHP . is the concatenation operator and + is either the addition, or the operator to merge arrays. Because you combine + with simple types (not arrays) PHP down-casts both values to a numeric value. In your case it's just 0+0
Answer: PHP uses . to concatenate strings, not +.
Try this instead:
function logout_link() {
   include("auth_vars.php"); //This file contains $auth_path_login
   return $auth_path_login . "?status=loggedout";
}

Answer: Your PHP code is incorrect. It should be:
function logout_link() {
include("auth_vars.php"); //This file contains $auth_path_login
return $auth_path_login."?status=loggedout";
}

Comment: @luke: note the "." instead of "+".  The arithmetic operator "+" turns logout_link() into a numeric function ... which returns the result "0".
Answer: You meant:
return $auth_path_login."?status=loggedout";

The concatenation operator is . in PHP.

php function returning 0?


Initially hidden items not appearing in overflow menu after shown in EXTJS

Question: I have a toolbar with buttons that are hidden by default, and then shown based on the user's privileges.  They appear and function after I call .show(), but do not appear in the overflow menu when the window is resized.  The items that are initially shown appear in the overflow menu correctly.
Any advice on how I can fix this problem?
Thanks
Edit: Here's the simplest example I could come up with that works with fiddle for the problem.  https://fiddle.sencha.com/#fiddle/877
<code>Ext.onReady(function(){

var toolbar1 = Ext.create('Ext.toolbar.Toolbar', {
    region: 'north',
    layout: {
            overflowHandler: 'Menu'
        },
    items: [{
        xtype: 'textfield',
        emptyText: 'FIX ME'
    },{
        xtype: 'button',
        text: 'Test Lists',
        id: 'testListsButton',
        hidden: true
    },{
        xtype: 'button',
        text: 'All Lists',
        id: 'allListsButton',
    },{
        xtype: 'button',
        text: 'Other Lists',
        id: 'otherListsButton',
        hidden: true
    },{
        xtype: 'button',
        text: 'Email Lists',
        id: 'emailListsButton',
        hidden: true
    }]
});

Ext.getCmp('emailListsButton').show();
Ext.getCmp('otherListsButton').show();
Ext.getCmp('testListsButton').show();

    var viewPort = Ext.create('Ext.container.Viewport', {
        layout: 'border',
        autoRender: true,
        items: [
            toolbar1
        ]
    });
})
</code>
Comment: Try to call [`doLayout`](http://docs-origin.sencha.com/extjs/4.2.0/#!/api/Ext.container.AbstractContainer-method-doLayout) on your toolbar after changing items visibility.
Comment: Tried it, but it didn't appear to do anything.  I also tried updateLayout().
Comment: Is it possible to provide an example?
Comment: Apparently I can't post an image until I have 10 reputation.  There's really nothing much to show code wise. The button's hidden config is set to true, and If (response.ROLE == 'Admin'){ button1.show(); }.  This makes the buttons appear on the toolbar without a problem.  That's really all there is to it.
Comment: try adding some code to your question using https://fiddle.sencha.com/
Comment: Added the fiddle code.
Answer: I found a work-around.
I set the items to be visible initially, hide them before they're rendered, and then show them again when checking the user's privileges.  This properly displays the items in the overflow menu.
It looks like this is a bug, all be it a minor one.


C# How to get the User AppData folder, NOT AppData\Roaming?

Question: I used below code to get the user's AppData folder -
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

But what I got is "C:\Users\(users)\AppData\Roaming". Is there a way to only get "C:\Users\(users)\AppData"?
Comment: Can you please describe why you want this information? I'm not sure if there is any guarantee that the Roaming, Local and LocalLow folders are always sibling folders.
Comment: There is an application that installed under C:\Users\(users)\AppData\LocalLow and I would like to create an update application for it.
Comment: You should have included this information in your question. The answer is here already on StackOverflow:  [Detect the location of AppData\LocalLow](https://stackoverflow.com/questions/4494290/detect-the-location-of-appdata-locallow)
Comment: I had checked that before. As the answer is too much complicated, I gived up to use LocalLow directory. I think it would be easy to just append"LocalLow" string to the AppData.
Comment: Please, for your next question, share what what you already have researched and why the results were not suitable for you. This saves people wanting to help you the time to repeat what you already did. And "too complicated": I would immediately choose the slightly more complicated, but correct solution over a solution that might work in 99% of the cases but fails in 1%.
Answer: First of all, accessing that folder directly is probably not a good idea unless Microsoft has published an API to retrieve its location. This means that there are no guarantees that this folder will even exist.
If you for some reason really want to retrieve this folder, you could probably do something along the lines of
Directory.GetParent(
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))

Then to verify, you could also retrieve e.g.
Directory.GetParent(
    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData))

If the two are the same, it is likely the folder you want to find.
But again, it is probably a good idea to question the motivation on why you need this path in the first place.
Answer: Is this what you are looking for
first get the user name from Environment object.
string userName = Environment.UserName;
then, use that User Name for generating the path.
string path = $"C:\\Users\\{userName}\\AppData";
Comment: It might not be on the C drive, it might not be under `C:\Users`, it might not be named the same as the username.  Just because it is on your machine doesn't mean it's at all like that elsewhere.
Comment: That will result in a path that doesn't exist in many cases
Comment: Did you mean if we are executing this code on Linux, because "path" string is structured  according to windows directory pattern.


How do you return an entity property of 'type' => 'struct'

Question: I am using Drupal 7.x and have a created a custom entity. I am using the Entity API module to extend EntityDefaultMetadataController and override public function entityPropertyInfo() to add properties for displaying when my entity is viewed.
More information on  hook_property_entity_info:
http://www.drupalcontrib.org/api/drupal/contributions!entity!entity.api.php/function/hook_entity_property_info/7
I understand how to return different types of properties such as 'text', 'int', 'list', 'entity', and so on, using callbacks.  However, I have not been able to successfully return a type of 'struct'.  My field is always empty when I try to display it.
Example code:
  $info['properties']['my-structure_property'] = array(
  'label' => t('My Structure Property'),
  'type' => 'struct',
  'getter callback' => ?  // What should this return?
  'property info' => array(
    'sub_field1' => array(
      'type' => 'text',
      'label' => t('Subfield 1'),
      'getter callback' => 'entity_metadata_sub_field1_property_get', // Returns a text field
    ),
    'sub_field2' => array(
      'type' => 'entity',
      'label' => t('Subfield 1'),
      'getter callback' => 'entity_metadata_sub_field2_property_get', // Returns an entity
    ),
  ),
);

What should I be returning in my callback?  I have tried returning an object, an array...?
Answer: Based on entity_metadata_node_entity_property_info_alter() and entity_property_text_formatted_info(), I suppose the getter callback should be the most generic callback the entity API offers: entity_property_verbatim_get.
This should allow you to access the properties as: $custom_entity->structure_property->sub_field1


last entry in home page

Question: I created a content type and created various entries. Each entry has the following fields:
name, photo, date.
How can I put a box on the home page with fields covering only the last entry?
(I would also like a page with squares side by side, sorted by date.)
Answer: You need to use CSS last-child selector to theme last entry as a box ! You need to write css in you active theme style.css.

I would also like a page with squares side by side, sorted by date.

For above you need to use views module and display nodes in grid format sorted by sort filter date.

last entry in home page


Error:(4) No resource identifier found for attribute 'id' in package

Question: I am getting this error for the menu item I have added for the toolbar.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res-auto"
    xmlns:xmls="http://schemas.android.com/apk/res/android">
    <item
        android:icon="@drawable/ic_camera_iris_white_36dp"
        android:id="@+id/video_camera"
        android:showAsAction="always"
        android:title="@string/menu_camera_label"></item>
</menu>

Any idea on how to resolve this issue ? Here are the build errors
> Error:(4) No resource identifier found for attribute 'id' in package
> 'com.google.rabbit'
>
> Error:Execution failed for task ':app:processDebugResources'.
> > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command
> 'C:\Users\sagar_000\AppData\Local\Android\sdk\build-tools\23.0.1\aapt.exe''
> finished with non-zero exit value 1

Comment: try to invalid catch/restart @Savita
Comment: try this `app:showAsAction="always" `
Comment: use `` as root
Comment: @Blackbelt How to use it as root?
Comment: @IntelliJAmiya it didn't work.
Comment: replace your `` with ``
Comment: @Savita follow #Blackbelt sir tips
Comment: @Blackbelt Thanks it worked :)
Comment: you are welcome. I posted it as answer
Answer:
Rectify your Root section with proper Tag

Finally
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

Then Clean-Rebuild-Sync .
 <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools">
    <item
        android:icon="@drawable/ic_camera_iris_white_36dp"
        android:id="@+id/video_camera"
        app:showAsAction="always"
        android:title="@string/menu_camera_label"></item>
</menu>

Answer: <menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.sixmod.MainActivity">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
<item
    android:id="@+id/title"
    android:orderInCategory="100"
    android:title="@string/titlename"
    app:showAsAction="always" />
<item
    android:id="@+id/video_camera"
    android:icon="@drawable/ic_camera_iris_white_36dp"

    android:showAsAction="always"
    android:title="@string/menu_camera_label"/>

</menu>

Answer:
Error:(4) No resource identifier found for attribute 'id' in package
  'com.google.rabbit'

Accordingly to the compile time error, you have the wrong namespace in your xml
<menu xmlns:android="http://schemas.android.com/apk/res-auto"
    xmlns:xmls="http://schemas.android.com/apk/res/android">

should be
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

Answer: Resolved such issue with the following code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/tools"
    xmlns:android1="http://schemas.android.com/apk/res/android">


How to pass multiple IDs to a Views exposed filter?

Question: Is there any way to pass multiple IDs to a Views exposed filter?
We need to pass an array of IDs to the filter.
Notes:

There we can see operator "=" but it not taken 1,2 etc.
We have tried regular expressions to, but it also not working.
We are not using contextual filters.
Comment: Do you pass series of continues id like as 1,2,3... (or) 1,2,4,55..
Comment: There we can see operator "="but it not taken 1,2 etc. We have tried regular expression to. but it also not working.Please note we are not using Contextual filters
Comment: what is your views type? page or block?
Answer: You can pass it using contextual filter,
Remember to choose multiple selection

if we have url http://example.com/test/20+10+12
Answer: You need to use Context Filter to achieve this ....
You can read values from URL , Multiple values can be separated using + or , operator...

Your view path should be  /some-path/%
Add Contextual Filter should be content id or any other id
Select Filter Value, Provide default value and select raw value from URL , Path component 2

Select Multiple Value setting in More settings

You can call your page with path something like http://example.com/some-path/24+25
You can read your multiple values from a text box in a view and on submit simply redirect to url like above.
Comment: Anil  - suramaya post that Please note we are not using Contextual filters
Comment: I said "You need to use Context Filter to achieve this" , OP Did not mention why they don't want to use Context Filter.. Question says how to pass multiple id in drupal 7 view filter? And my answer fits for question...
Comment: Question says How to pass  pass multiple id in drupal7 views exposed filter? May be they checked by exposed filter .. anyway if  they will use context filter in future ..
Comment: Thank you Sentil and Anil for quick reply.
Actually we are not use the contextual filter in the view.We used services views.We have added contextual filter and it not retrieve in query string. Let me know we have done anything wrong. is there any way to get multiple id via exposed filters?
Comment: It would be helpful to know how to pass contextual filters to services views query string.We have used drupal 7 and services 3
Answer: If your filter filter values is not much pass it in URL but if you have custom id and they are very items I render you views programmatically and passed your arguments to it
$array = array(1,2,3,4,66,5,54,33,22,111,222,333,);
$view = views_get_view('yourviewname');
$view->set_display("yourdisplayneme");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render();
print $content;

Answer: Here is what I did to add a multiple select exposed filter of nid to a view, just make a example for you here.

I would like to create a views listing movies('movie' content type).
Movie has a cast field which lists actors('actor' content type).
I want to have search movies by actors, which need to support multiple select.

In above example, actors are nodes. So I need a views exposed filter to pass multiple nids to views.
What I used to achieve that, is 'entity reference' module.
I created a entity reference field in movie content type called 'cast'. Which is referencing to 'actor' content type.
Then in 'cast' field setting, remember to tick 'Render Views filters as select list' as below:

Then you will able to add a nids exposed filter in views!!
In my movies views, add a new filter with Content: Cast (field_cast). Then you will see the select list and multiple options as below:

After adding that filter, you will have a multiple select filter and it should look like this:

NOTE: You may get duplicated result in some case, just enable the views advance 'Use aggregation' setting.

That's it! :)
The last thing I would like to do is make the multi select looks better. What I like to use is a jQuery plugin Sumoselect which you can add if you like.


Exponential distribution -- calculating probability that computer works!

Question: If $X$ is the number of years a computer works, and it follows an exponential distribution with a $\lambda=3$, what's the probability a computer will work in 8 years?
I'm not sure that I'm going about this the right way and would love to get feedback.
I'm following this formula: $P(X \leq x) = 1 - e^{-\lambda x}$
When plugging in values for $x=8$ and $\lambda=3$, I get $P(X\leq 8 ) = .9999$...; and to get $P(X>8)$ I subtracted this from 1.
Final answer .000000000378
Is this correct? It seems like a very small probability and not sure that I'm going about it the right way. Any ideas are greatly appreciated. Thank you!
Comment: **Caution**: There are two parameterizations of the exponential distribution in common use. The difference between a pdf of $\lambda \exp(-\lambda x)$ and $\frac{1}{\lambda} \exp\left(-\frac{x}{\lambda}\right)$ could account for why you believe the final answer is too small.
Answer: Seems that the approach is right.  I haven't checked your final computations.  Keep in mind that since the rate $\lambda$=3 the mean lifetime is 1/3 years. So lasting 8 years is a very long time and therefore P(X>8) should be very small. Note that 8 years is 24 average lifetimes.
Comment: A mean lifetime of 1/3 years is so unrealistic for most computers that we ought to use common sense (as employed admirably by the OP) and interpret "lambda 3" as being a mean of 3 years.
Comment: Michael, the word "rate" appears nowhere in the question.  I agree that the OP was using "lambda" as if it were a rate--but isn't that error precisely the issue that needs to be addressed, rather than being compounded by repeating it?
Comment: I don't understand what you're referring to.  "Too small" compared to what?  Regardless, between the two competing interpretations of $\lambda$ only one is plausible.
Comment: "Low" implies a comparison: it has no absolute meaning.  The value, by the way, is close to 7%.
Comment: We don't know what the OP thought. It was the rate parameter as stated on the question.  I agree that very few computers breakdown in 1/3 of  year.
Comment: Even if we take $\lambda$=1/3 and the mean lifetime=3 years, 8 years is still 2.67 years and P(X>8) is still small.
Comment: i meant to say that 8 years is 2.67 mean lifetime years. So the calculated probability is small.  I am just saying that it is a low probability and not comparing it to anything.


Injected HTML accessing the Chrome API and global variables

Question: I'm working on a Chrome Extension, and I'm new to the process. The extension I'm working on injects an HTML sidebar into the page, injects java-script functions to the header, then let's the user press the buttons on the sidebar to create/save my extension's data.
However, when I want to save the information, I use localStorage, however, the localStorage always saves with respect to the current website. How can I use localStorage to save with respect to our extension?
Furthermore, I would like to use some global javascript variables in the chrome-extension. Where do these belong? I know I can't currently access them from the injected Javascript.
I've looked into message passing, and I've had some trouble with it. I'm not sure how it works in the scope of injected javascript into a page's header. I've tried working with this example, but my extension doesn't seem to catch the message.
<code>// This function is called in the injected header javascript.
function sendToExtension() {
    setTimeout(function() {
    console.log('page javascript sending message');
    window.postMessage({ type: 'page_js_type',
        text: "Hello from the page's javascript!"},
        '*' /* targetOrigin: any */);
    }, 10);
}

// This is installed in a background script.
window.addEventListener('message', function(event) {
    console.log('content_script.js got message:', event);
});
</code>
Comment: Tip: Use [`chrome.storage`](https://developer.chrome.com/extensions/storage.html) instead of `localStorage`. Since postMessage is asynchronous already, you would probably not have any trouble with changing your code.
Comment: Hm, I would look into this more, since it looks like a useful API - but I still have the problem that injected HTML can't access the chrome APIs.
Comment: You've put the right solution in your answer: Use `postMessage` and `onmessage`.
Answer: You have to use Chrome's sendMessage function and onMessage listener. See below:
<code>function sendToExtension() {
    console.log('Sending message');
    chrome.runtime.sendMessage({ext: "myExtension"}, function(response) {
      console.log(response.ack);
    });
}

// Listener - Put this in the background script to listen to all the events.
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.ext) {
        console.log('Message received from ' + request.ext);
        sendResponse({ack:'received'}); // This send a response message to the requestor
    }
});
</code>
Comment: This is almost what I am looking for, but "sendToExtension" is called from an injected HTML script. From there, I can't access the 'chrome.runtime.sendMessage' API.
Comment: What I ended up doing was passing from the window to the content script, and then from the content script to the background script.


How to prove $\sqrt[\pi]{e} < \sqrt[\pi]{\pi}<\sqrt[e]{e}< \sqrt[e]{\pi}$

Question: I was given a challenge of sorting the following numbers. $\Large\sqrt[\pi]{e} < \sqrt[\pi]{\pi}<\sqrt[e]{e}< \sqrt[e]{\pi}$. After some work I was able to figure out the order. How can one prove this by hand?
Comment: The only difficult part here is proving $\sqrt[\pi]{\pi}<\sqrt[e]{e}$, which is equivalent to proving ${\pi}^{e}<{e}^{\pi}$. The answer to that can be found at http://math.stackexchange.com/a/9459/131263.
Comment: What a nice inequality cascade!
Comment: You can see that left and right inequalities are obvious for the one in the middle just consider $x^{\frac{1}{x}}$. Differentiate it.
Answer: HINT: The only non-obvious inequality is $ \sqrt[\pi]{\pi}<\sqrt[e]{e}$. Taking logarithm we obtain
$$
\frac1\pi\ln\pi<\frac1e\ln e
$$
and it remains to show, that
$$
\frac{\ln x}{x}
$$
has its maximum at $x=e$, but it is a standard calculation.
Comment: At $x=e$, I presume. Good typo ! Cheers :-)
Comment: @ClaudeLeibovici Certainly. Thank you!
Comment: It would have been interesting, for sure. If I was given a cent for every typo of mine, I should be a millionaire ! Cheers :-)
Answer: If you take each expression to the power $e \cdot \pi$, most of the order is obvious. The only non-obvious part is comparing $e^{\pi}$ and $\pi^e$ (without a calculator).
That last is a classic problem with many solutions. There are examples here and here. Here is another way, given in "Calculus: Graphical, Numerical, Algebraic" by Finney et al.
Consider the line through the origin tangent to the graph of $y=\ln x$, which has slope $1/e$. Find the equation of the tangent line and use the concavity downward of $\ln x$ to see the tangent line is above the graph. This shows that $\ln(x^e)<x$ for all positive $x \ne e$. Therefore, $x^e<e^x$ for all positive $x \ne e$, so $\pi^e<e^{\pi}$.
Comment: I really liked the idea from the other thread. We know that $\pi > e$ and $e^x > 1+x$ for $x>0$. From the first bit we know that $\pi/e>1$ and $e^{\pi/e-1}>\pi/e$. Which implies that $e^{\pi/e}>\pi$. Raising both sides to $e$ completes the proof.
Answer: Clearly, $\sqrt[\pi]e<\sqrt[\pi]\pi$, and $\sqrt[e]e<\sqrt[e]\pi$. (That's because $e<\pi$.)
The only hard part is showing that $\sqrt[\pi]\pi<\sqrt[e]e$.
I'm going to do this by using my favorite inequality involving $e$:
$$e^x\ge x+1$$
with equality iff $x=0$. (Look at a graph to see why this is. It's basically another way of saying that the derivative of $e^x$ at $0$ is $1$.)
Substitute in $x=\frac\pi e-1$. You'll see why I'm using this particular value in a moment.
\begin{align}
e^{\pi/e-1}&>\left(\frac\pi e-1\right)+1\\
e^{\pi/e-1}&>\frac\pi e\\
e^{\pi/e}&>\pi\\
e^{1/e}&>\pi^{1/\pi}\\
\sqrt[e]e&>\sqrt[\pi]{\pi}\tag*{$\blacksquare$}
\end{align}
You might have noticed that, in the above argument, there's nothing special about $\pi$. In fact, the above argument can be modified to show that $\sqrt[x]x\le\sqrt[e]e$ for any $x$ (with equality iff $x=e$). In other words, the maximum of $\sqrt[x]x$ is at $x=e$.
Comment: The inequality I gave at the start, $e^x\ge x+1$, actually works pretty well as a definition of $e$. (It allows you to prove many $e$-related results without calculus.) As I've shown, this is equivalent to saying that the maximum of $\sqrt[x]x$ is at $x=e$. That means that that also works pretty well as a definition of $e$.


How to get Webform Field data for a custom module?

Question: I'm trying to set up a view permission based on a webform field.  I've been able to get to my custom module using hook_webform_submission_access().
So I have an email field in the webform, and I want to check that based on the current user's email address.  Should be pretty simple, I just can't get the field data.  Anyone know?
Example:
<code>if ($submission->data['field_email'] == $user->mail)
</code>
What is the correct syntax instead of $submission->data['field_email']
I'm on Drupal 7 and Webform 4.x branch.
Answer: Provided Token is installed, you can use token_replace to access Webform submission values by field name.
<code>$email = token_replace('[submission:values:email]', array('webform-submission' => $submission));
</code>
Note: The Devel module can be useful for exploring object properties and tokens (among other things).
Comment: Thanks Labracadabrador.  I do indeed have Token installed.  I'll check this out at work tomorrow and let you know!


Set the boundary for calculating the expectation of joint probability density function

Question: From the joint pdf below, I need to find $E(X)$.
$$f(x,y) = \begin{cases}
8x^2e^{-2y}, & 0<x<y\\\
0, &\text{otherwise}
\end{cases}$$
I know that
    $$E(X)=\int xf(x)dx$$
so I calculate $f(x)$ first. Since $0<x<y,\,$ I set the boundary $y>0$ or $0<y<\infty$. But I'm not sure I got it right.
$$f(x)=\int_0^\infty 8x^2e^{-2y} \,dy= 4x^2$$
I subtitute this result to $E(X)$ by setting the boundary from $0$ to $\infty$. But I got diverge result.
 $$E(X)=\int_0^\infty x4x^2\,dx=\int_0^\infty 4x^3\,dx=\text{diverge}$$
I guess I set the boundary wrong. But I'm not be able to figure it out.
How am I supposed to set the right boundary? Did I get the step correctly?
Comment: No, the marginal pdf $f_X(x)$ equals $\int_{-\infty}^\infty f_{X,Y}(x,y) \; dy = \int_{-\infty}^\infty 8x^2 e^{-2y}  \cdot \mathbf{1}[0 < x < y ] \; dy$
Answer: The boundary should be $x<y<\infty$
Therefore:
$f(x)= \int^{\infty}_{x}{8x^2e^{-2y}}dy=8x^2 \int_{x}^{\infty}e^{-2y}dy=8x^2[-\frac{1}2e^{-2y}|^\infty_x]=4x^2e^{-2x}$
Now you should be able to find $E(X)$ (Which should be $\frac{3}2$)
Comment: So, as for f(y), the boundary is 0<x<y, correct?
Comment: Correct. to find $f(y)$ the integral would look like $\int^y_0{f(x,y)}dx$


Como fazer um botão "leia mais" e um "leia menos" em um texto que vem dinamicamente do banco de dados com JavaScript Puro?

Question: Eu gostaria de fazer um botão "leia mais" e "leia menos" com JavaScript Puro (sem jQuery).
Porém, esse texto vem dinamicamente do banco de dados e uso um foreach do PHP para preencher as divs com esses textos que vem do banco.
Esses textos podem ter até 3000 caracteres, porém, eu gostaria de só mostrar 1000, e caso o usuário clicasse no "leia mais" então os 3000 caracteres seriam mostrados. Então se logo depois eu clicasse no "leia menos", então o texto da div voltaria a ter 1000 caracteres.
Consegui ver uns exemplos, porém o texto não era preenchido dinamicamente e era usado uma tag "span" abraçando o texto que seria retirado ou mostrado.
Só que no meu caso não é possível colocar essa tag "span" justamente porque o texto é dinâmico e vem do banco de dados.
Segue meu código:
<?php foreach ($feed['posts'] as $data) { ?>

           <?php echo nl2br($data->body['body']); ?>

<?php } ?>

O meu conteúdo (texto) está naquele $data->post['body'].
Segue abaixo meu código de uma forma mais verificável. Vamos imaginar que aquele texto ali dentro da div tenha vindo do banco

    (IMAGINEM QUE ESSE SEJA UM TEXTO COM 3000 CARACTERES) Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Tem esse exemplo aqui da w3Schools:
Exemplo:
Porém reparem que é um texto estático e eles usam um span. Se no meu caso fosse um texto estático, seria bem mais fácil.
Então como ficaria um código JavaScript para mostrar e recolher o texto de acordo com o seu número de caracteres ?
Comment: Acho que vale uma lida no [mcve]. Verificável, minimo e completo é se eu pegar o código, salvar como PHP aqui (ou abrir num ideone) e sair o HTML do jeito que vc tem hoje. Que é pra gente ter o mesmo resultado que vc, mas sem criar um banco pra isso (ex, com uma variável no lugar). E o "minimo" significa tirar tudo que não muda o problema. Se dominar o conceito, você faz com que seu tempo no site renda mais pra você e todos envolvidos.
Comment: Vou dar uma olhada. Obrigado. Pesquisei bastante e estava achando nada que se aproximasse da minha labuta. Vou ver.
Comment: Você perguntou na outra pergunta se o "texto morre". Sim, morre. A ideia é ter duas `div`. A com o texto completo você deixa oculto, e a com texto cortado você deixa exibindo. Quando clicar no link, você exibe a do texto completo e oculta a outra.
Comment: _"Eu gostaria de fazer um botão "leia mais" e "leia menos" com JavaScript Puro (sem jQuery). Porém, esse texto vem dinamicamente do banco de dados e uso um foreach do PHP para preencher as divs com esses textos que vem do banco"_ não consigo ver onde isso muda algo, depois que o PHP rodou o resultado é um HTML estático. O JS só roda depois.
Comment: Chegou a ver o exemplo CSS? Tem muitas maneiras de adaptar, dá pra trocar a classe com JS se quiser evitar o checkbox. Melhor que apagar seria [edit] e por o exemplo minimo verificavel, aí seria útil pra um público amplo
Comment: Relacionada: https://pt.stackoverflow.com/a/169912/4995
Comment: Relacionada: https://pt.stackoverflow.com/questions/117961
Comment: Inclusive, incluí a tag [php], já que a maioria das soluções podem ser encontradas no próprio php, que é usado na pergunta.
Comment: @Bacco , então. Eu tive a visão que muda, pois quando são textos estáticos, nós podemos encaixar tags como span dentro desses textos. Então, podemos ocultar esses textos que estão dentro dessas tags facilmente, e então depois mostrá-los através de um evento JS. Porém, com o texto dinâmico vindo do banco via PHP, esse texto já vem montado e não teria como colocar tags no meio dele para ocultar parte do texto. Não sei se conseguir me expressar bem...
Comment: @WallaceMaxters, mas essa sua ideia foi uma ótima. Vou tentar aplicá-la aqui e retorno com o resultado. Acho que inclusive você poderia elaborar uma resposta com base nisso que você falou. Não precisa codificar. Explicando de forma contextual eu já a aceito. Obrigado!
Comment: @GatodeSchrödinger entender entendi, só não sei como fazer isso caber no site, a pergunta não tem um [mcve], outras alternativas já foram postadas com CSS no site, da forma como está ficou um "faz pra mim", mesmo que não seja a intenção. Um [mcve] seria fundamental para manter o post aberto (ter como alguem copiar seu PHP com um texto real (igual do banco) montando UMA div.
Comment: Com CSS eu acredito já tem solução no site, inclusive (limitando espaço com CSS da div e pondo  overflow:hidden) - inclusive para browsers modernos nem precisa do JS https://pt.stackoverflow.com/a/110958/70
Comment: @Bacco , eu vou apagar o post. De boas
Comment: A minha intenção não era um faz pra mim. É pq eu não sabia mesmo. E eu queria realmente em JS Vanilla. Por isso deixei claro no título da pergunta.
Comment: Então. O Exemplo Mínimo e Verificável ajuda todo mundo. Até pq em cima dele nós podemos bolar uma resposta oficial que resolva o que vc precisa e sirva pra quem pesquisar isso depois. Essa a idéia do site. E é algo que você faz em um tempo minimo,
Comment: @Bacco , mas o exemplo mínimo e verificável é apenas aquele ali que tenho. Somente a string sendo exibida via PHP e como vem do banco. Fora isso, não teria mais código útil.
Answer: Você pode fazer com as seguintes etapas:

Verificar se o texto passa o tamanho desejado com um if em PHP.
Limitar o texto com o tamanho desejado dentro de uma div caso o tamanho passe o limite pelo PHP.
Criar uma div com o conteúdo completo, porém oculta.
Criar um link para expandir junto ao texto cortado e um link para reduzir no texto completo.
Aplicar o Javascript.

Exemplificando, o seu código PHP poderia ficar parecido com isso:
<?php foreach ($feed['posts'] as $data) { ?>

           <?php if (mb_strlen($data->post['body'], 'UTF-8') > 1000): ?>

                   <?php echo nl2br(mb_substr($data->post['body'], 0, 1000, 'UTF-8')); ?>
                   ...
                  leia mais

               <?php echo nl2br($data->post['body']) ?> ler menos

           <?php else: ?>
               <?php echo nl2br($data->post['body']) ?>
           <?php endif ?>

<?php } ?>

Com o Javascript, você poderia fazer isso:

document.querySelectorAll('.post-body').forEach(function (el) {

   var fullText = el.querySelector('.full-text');
   var shortText =  el.querySelector('.short-text');

   if (! shortText) return;

   el.querySelector('.read-more').addEventListener('click', function () {
      fullText.style.display = '';
      shortText.style.display = 'none';
   })

   el.querySelector('.read-less').addEventListener('click', function () {
      fullText.style.display = 'none';
      shortText.style.display = '';
   })
})
a {
   color: blue;
   cursor: pointer;
}

     Meu texto está ... ler mais
     Meu texto está aqui firme e forte ler menos

     Meu texto está ... ler mais
     Meu texto está aqui firme e forte ler menos

     Meu texto pequeno

Note que na última div, simulei o caso de cair no else do PHP e o texto ser exibido normalmente, pelo fato de não ultrapassar 1000.
Não vou explicar sobre mb_string ao invés de substr, porque essa resposta do Bacco já explica tudo.
Comment: Muito obrigado!
Answer: Bom achei muita coisa parecida assim como apontaram nos comentários, olha você pode fazer algo como o códico abaixo Js (mais pode fazer com a mesma sintaxe do php ou javascript mesmo:
function readMoreRome() { //finds function
var dots = document.getElementById("dots"); //returns element that has the ID attribute with value, searches for dots
var moreText = document.getElementById("more"); // '' '' searches for more
var btnText = document.getElementById("myBtn"); // '' '' searches for myBtn

if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more"; //button says read more to show more text
    moreText.style.display = "none";
} else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less"; //button says read less to show less text
    moreText.style.display = "inline";
}
}

function readMoreBuda() { //finds function
var dots = document.getElementById("dots2"); //returns element that has the ID attribute with value
var moreText = document.getElementById("more2"); // '' '' searches for more2
var btnText = document.getElementById("myBtn2"); // '' '' searches for myBtn2

if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Read more"; //button says read more to show more text
    moreText.style.display = "none";
} else {
    dots.style.display = "none";
    btnText.innerHTML = "Read less"; //button says read less to show less text
    moreText.style.display = "inline";
}
}

HTML:

Visit Budapest

  November 12, 2019  2 comments

Széchenyi Thermal Baths

    Budapest is the capital city of Hungary. It is best known for its arts and culture. It is a relatively small city, however there are much to see and do.
    ...
    Situated on thermal springs, there are many naturally heated baths to relax in, the Széchenyi baths are the largest with 15 indoor baths and 3 outdoor. There are many spectacular viewpoints in Budapest, great for capturing the views of the city. From 360 panoramic views up at St Stephens Basilica to a wide view of the parliament and the River at Fisherman's Bastion. Visit the Museum of Fine Arts and enjoy a day amongst famous European art. Classical music lovers will appreciate a performance at the Academy of Music.

<button onclick="readMoreBuda()" id="myBtn2">Read more</button>

Visit Barcelona

  December 06, 2019  5 comments

Park Güell

    Barcelona, framed for its individuality, cultural interest, and physical beauty, home to art and architecture. Facing the Mediterranean to the southeast,
    ...
     the city is one of a kind. Upon visiting make sure you visit the spectacular and unique Park Güell which was firstly designed for a town up in the mountains by artist Antoni Gaudí. Gaudí's work is admired by architects around the World as being one of the most unique and distinctive styles in modern architecture. Other places worth visiting is the La Sagrada Família, is a giant basilica. With beaches on your doorstop, and art and city culture, this diverse city has everything to offer.

<button onclick="readMoreBarca()" id="myBtn3">Read more</button>

Não importa se seus dados vier de um banco de dados ou não, para mostrar exibir e exibir "menos" a lógica é sempre a mesma, pega a ideia no exemplo :)

Tá inglês mais tem até mais de uma resposta e explicação caso queira entender melhor referência:
https://stackoverflow.com/questions/59360119/how-to-make-multiple-read-more-read-less-buttons-in-the-same-one-page
Comment: Eu agradeço a tentativa, Herick Eduardo, porém o exemplo que você citou é com textos estáticos. É mais ou menos conforme o exemplo da w3Schools que eu citei ali na minha pergunta. Esse seu exemplo não me serviria.
Comment: Ok, desculpe, vou deixar o códico pra caso alguém daqui um tempo tenha o mesmo problema talvez o exemplo sirva pra outro contexto etc.
Comment: Nada. A tentativa de ajuda é sempre válida.
Answer: Seguindo a resposta e dicas nos comentários do Wallace Maxters, consegui adaptar meu código e fazê-lo funcional, me baseando somente no JS (com um mínimo de PHP).
Vou deixar meu código só para ajudar alguem que, futuramente, tiver passando por algo semelhante ao que passei.
O meu código ficou assim:
<?php foreach ($feed['posts'] as $data) { ?>

            <?php echo nl2br(mb_strimwidth($data->post['body'], 0, 1000, ' ...')); ?>
            <button class="ler-mais">Ler mais</button>

            <?php echo nl2br($data->post['body']); ?>
            <button class="ler-menos">Ler menos</button>

<?php } ?>

O JS ficou assim:
//Código do botão leia mais
document.querySelectorAll('.ler-mais').forEach(function (el) {

   el.addEventListener('click', function () {
      let divBoxBody = el.closest('.box-body');
      let divPostBody = divBoxBody.querySelector('.post-body').style.display = "none";
      let divPostBody2 = divBoxBody.querySelector('.post-body-2').style.display = "block";
   })

})

//Código do botão leia menos
document.querySelectorAll('.ler-menos').forEach(function (el) {

   el.addEventListener('click', function () {
      let divBoxBody = el.closest('.box-body');
      let divPostBody = divBoxBody.querySelector('.post-body').style.display = "block";
      let divPostBody2 = divBoxBody.querySelector('.post-body-2').style.display = "none";
   })

})

Tenho duas div's. Uma eu deixo aparente (com o texto parcial, exibindo somente 1000 caracteres [para isso usamos o mb_strimwidth() do PHP] dos dados que vem do banco). E a outra eu deixo escondida (com display:none) com o texto inteiro, exibindo todo o texto que vem do banco de dados.
Quando clico no botão "ler mais", a div com o conteúdo parcial passa a ficar escondida (com display:none) e a div com o conteúdo inteiro passa a ficar visível (com display:block).
Quando clico no botão "ler menos" é feito o inverso do que foi feito acima.
Obrigado aos que ajudaram e espero ajudar também.
Answer: Ai está o exemplo, você pode usar função map((dados, id)) para manipular os dados dentro do array e o substring para determinar o tamanho do texto, criei 2 exemplos para te ajudar, no segundo exemplo eu criei a função getData como se eu tivesse pegando os dados da API.

const data = [
  {
    titulo: 'hello',
    text: 'hello world com 3000 caracteres',
  },
];

const leiaMais = () => {
  document.getElementById('leia').innerHTML = 'Leia Menos';
  document.getElementById('leia').onclick = leiaMenos;
  data.map(({ text }, id) => {
    document.getElementById('textoApi').innerHTML = `<p>${text.substring(0, text.length)}</p>`;
  });
};

const leiaMenos = () => {
  document.getElementById('leia').innerHTML = 'Leia Mais';
  document.getElementById('leia').onclick = leiaMais;
  data.map(({ text }, id) => {
    document.getElementById('textoApi').innerHTML = `<p>${text.substring(0, 11)}</p>`;
  });
};

// exemplo com async

async function getData() {
  return data;
}

const leiaMaisAsync = () => {
  document.getElementById('leiaAsync').innerHTML = 'Leia Menos Async';
  document.getElementById('leiaAsync').onclick = leiaMenosAsync;
  getData().then((data) => {
    data.map(({ text }, id) => {
      document.getElementById('textoApiAsync').innerHTML = `<p>${text.substring(0, text.length)}</p>`;
    });
  }).catch(() => {
    // algo errado aconteceu
  });
};

const leiaMenosAsync = () => {
  document.getElementById('leiaAsync').innerHTML = 'Leia Mais Async';
  document.getElementById('leiaAsync').onclick = leiaMaisAsync;
  getData().then((data) => {
    data.map(({ text }, id) => {
      document.getElementById('textoApiAsync').innerHTML = `<p>${text.substring(0, 11)}</p>`;
    });
  }).catch(() => {
    // algo errado aconteceu
  });
};
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
      crossorigin="anonymous"
    />

    <title>Javascript Teste</title>

          <button
            class="btn btn-link collapsed"
            onclick="leiaMais()"
            id="leia"
            data-toggle="collapse"
            data-target="#collapseTwo"
            aria-expanded="false"
            aria-controls="collapseTwo"
          >
            Leia Menos
          </button>

        <button
          class="btn btn-link collapsed"
          onclick="leiaMaisAsync()"
          id="leiaAsync"
          data-toggle="collapse"
          data-target="#collapseTwo"
          aria-expanded="false"
          aria-controls="collapseTwo"
        >
          Leia Menos Async
        </button>


Iterar um lista dentro de switch

Question: bom galera eu gostaria de saber como eu faco para iterar uma lista em um switch em python, tipo eu tenho uma lista com dez valores lista = [1,2,3,4,5,6,7,8,9,11] agora eu quero acessar essa lista valor por valor e criar um laco condicional para cada valor como e que eu faco? agradeco a ajuda de vocês
Comment: Python não tem a cosntrução `switch` - vocẽ deve usar  `if` e  `elif`
Comment: tipo eu quero ler cada valor da minha lista eg se o valor for 1 eu executo uma funcao, agora se for 2 eu executo outra funcao acho que e isso
Comment: Oque é um "laço condicional para cada valor"?
Answer: update 2021: Na versão 3.10 do Python está sendo introduzida a construção match/case, que também pode funcionar como o switch/case do C, embora não seja o objetivo principal. Confira em: Como funciona o pattern matching estrutural (declaração match) em Python?
Resposta original
Python não tem uma construção com o nome de switch (e o complementar  case) - pelo simples motivo de que a forma como o if (e os complementares elif e else)  podem fazer o mesmo trabalho - com algumas vantagens.
Mesmo em linguagens que derivam a sintaxe de C, que tem o switch, hoje em dia ele é apenas "mais um jeito de fazer a mesma coisa" - que seria factível com encadeamento de if e else ifs. O motivo histórico de existir uma construção separada é que no tempo em que computadores  tinham muito menos recursos do que hoje (da ordem de 1 milhão de vezes menos memória) - o switch-case era uma forma do programador explicitar para o compilador C uma "tabela de saltos" que geralmente seria mais eficiente do que uma sequẽncia de ifs quando transformada em código nativo. Já há algumas décadas que os compiladores (e mesmo as CPUs)  incorporaram estratégias de otmização o suficiente para tornar isso redundante.
Mas, voltando ao Python, o jeito mais simples e direto de fazer o que vocẽ quer é simplesmente:
for elemento in lista:
    if elemento == 1:
        funcao1()
    elif elemento == 2:
        funcao2()
    ...
    else:
        funcao_nao_encontrado()

Perceba que ao contrário do que acontece com o switch em qualquer linguagem, a expressão de "verdeiro ou falso" da sequẽncia de if's não está limitada a comparar igualdades - vocẽ pode fazer qualquer comparação, chamar outras funções, etc... - como o Python tem a notação de atalho de comparação de intervalos - a mesma que usamos em matemática - que traduz a <  x  < b para a < x and x < b - você pode facilmente incorporar intervalos nas suas comparações:
    ...
    elif 2 <= elemento < 5:
        funcao_para_numeros_medios()
    elif elemento == 5:
    ...

Se parecer que escrever as comparações dos if é muita coisa, - se tudo o que você deseja fazer para cada opção é chamar uma função separada, é possível usar a vantagem de que funções em Python são objetos que podem ser passados como parâmetros e usados em outras estruturas de dados - nesse caso, você pode simplesmente criar um dicionário onde as chaves são os números que você colocaria no case e os valoes as funções que deseja chamar:
def funcao1():
    ...
def funcao2();
    ...
...
funcoes = {
1: funcao1,
2: funcao2,
...
}

for elemento in lista:
    funcoes[elemento] ()

Pronto - essa última linha chama  a função apropriada, que foi recuperada de dentro do dicionário que eu chamei de funcoes acima.
Comment: caraca mlk essa eu nao, sabia aprende mais uma agora se eu quiser passar algum argumento na funcao como e que eu faco? +1
Comment: Usando o esquema de dicionários? Se o argumento for fixo, você pode usar o objeto retornado por uma chamada a `functools.partial` para montar seu dicionário de funções: `from functools import partial; funcoes =  {1: partial(funcao_numerica, 1), ...} ;...; elemento=1; funcoes[elemento]()` por exemplo, vai chamar a `funcao_numerica` passando o parâmetro "1" - que vai ser "congelado" quando você fizer a chamada a `partial`.
Answer: Python não tem uma função switch pelo que eu saiba, se isso for crucial para o programa você pode usar esse pacote: (https://pypi.python.org/pypi/switch/1.1.0) que é similar às linguagens C, C++, Java, etc... Mas com pequenas diferenças.
Edit: como eu não pensei nisso enquanto eu lia? Você também pode (aparentemente) implementar C e C++ em Python (https://docs.python.org/2/extending/extending.html)

Iterar um lista dentro de switch


Updating a table row, jQuery

Question: I need to update a certain row in table, already did "validators" to assure 1 row edit when checkbox is checked after clicking some other button, so far i wrote something like:
$("#btnsavechanges").click(function(){

    $("#meetingspanel tr td").find(":checked").parent().parent().children)(.eq(0).append(document.getElementById("modsub").value);
    $("#meetingspanel tr td").find(":checked").parent().parent().children)(.eq(2).append(document.getElementById("modwhere").value);
    $("#meetingspanel tr td").find(":checked").parent().parent().children)(.eq(3).append(document.getElementById("modwhen").value);
    $("#meetingspanel tr td").find(":checked").parent().parent().children)(.eq(4).append(document.getElementById("modtime").value);
    $("#meetingspanel tr td").find(":checked").parent().parent().children)(.eq(5).append(document.getElementById("modwho").value);
    $("#tblmod").fadeOut("slow");

});

The table looks like this:

Enter Subject<input type="text" id="modsubject" width="15%">

Enter Location<input type="text" id="modwhere" width="15%">

Enter When<input type="text" id="modwhen" width="15%">

Enter Time<input type="text" id="modtime" width="15%">

Enter With Who<input type="text" id="modwho" width="15%">

<button type="button" id="btnsavechanges" value="Save New Changes" >Save Changes</button>

Comment: You need to explain what you have tried, what errors you are finding, what your question actually is, what your table update html+js looks like.
Comment: im trying to update a row in a table with data taken from the following table.
and nothing happens.thats the problem..no compailer/debugger errors..working with eclipse 4.1.
Answer: I would recommend using a data-binding framework.  I have been using knockoutjs recently and I like it.  The amount of code I write to do complicated UIs is far smaller when using Knockout.
Basically, you would bind the HTML by just adding a data-bind property to the element.  Then, when someone changes a value, it is immediately updated in your viewmodel.  If you pull in new data from an AJAX request, it will update your UI too.
More info here: http://knockoutjs.com/
I strongly suggest this as it will help you write cleaner, more manageable code, and do so faster.  You are going to be "reinventing the wheel" by handling everything "manually" as you are asking to do.
Comment: im a beginner with jQuery, so if there isn't a way to do that in jQuery ill go and try you suggestion..i really want to stay between the boundaries that i set at the moment.
thanks a lot though.
Comment: @OriGavrielRefael It can definitively be done using only jQuery, it's just going to be much more difficult to cover every corner case.  In contrast, a framework like Knockout handles those for you.  I understand the reluctance to take on too many new things at once, but, I think you would be better off learning it now.  BTW, jQuery and Knockout are totally compatible.  They are meant to solve very different issues.  Knockout is data-binding, jQuery is lower level API that handles DOM manipulation and cross-browser compliance.
Comment: @OriGavrielRefael Is what working with Eclipse?  Are you using Eclipse as an IDE for whatever you are writing JS/jQuery for?
Comment: yes, im working with Eclipse.
andi want to know  if Knockout is supported by Eclipse..i mean if there is a way to add a reference between eclipse 4.1 and knockout or smth like that?
Comment: @OriGavrielRefael I only use Eclipse for Android development.  I use gedit/vim for everything else, so, I am not familiar with it past Android.  Knockoutjs is **just** a javascript library, you include it just like jQuery.  There should not be any special support needed for it.

Updating a table row, jQuery


Exact sequence of $R$-modules

Question:
Let $0\longrightarrow N\overset{f}{\longrightarrow}M\overset{g}{\longrightarrow}L\longrightarrow0$
  be a short exact sequence of $R$-modules. Prove that this chain splits iff
  $f(N)$ is direct summand of $M$.

Thanks a lot.
Comment: And what have you attempted so far?
Answer: Suppose $\;M=f(N)\oplus K\;$ , and define $\;F:M\to N\;$ by $\;F(m) = F(f(n)+k):=n\;$ . Show that $\;F\;$ is a well defined $\;R- $ homomorphism and $\;F\circ f=\text{Id}\,_N\;$ .
The other direction: suppose there exists an $\;R-$ homom. $\;F:M\to N\;$ s.t. $\;F\circ f=\text{Id}\,_N\;$. Show that
$$\begin{align*}(1)&\;\;\ker F\cap f(N)=\{0\}\\
(2)&\;\;M=f(N)\oplus\ker F\end{align*}$$
Note: Point (2) above may be a little tricky but not too much if you understand what's going on here.
Comment: Thanks for your hint. I will continue to try to prove
Comment: Can you explain more precise on the point (2)?
Comment: For $\;m\in M\;$, let $\;F(m)=n\in N\;$ , so take a peek at $$m=f(n)+\left(m-f(n)\right)\;\;\ldots\ldots$$

Exact sequence of $R$-modules


How to replace specific values in a dataset with randomized numbers?

Question: I have a data column that contains a bunch of ranges as strings (e.g. "2 to 4", "5 to 6", "7 to 8" etc.). I'm trying to create a new column that converts each of these values to a random number within the given range. How can I leverage conditional logic within my function to solve this problem?
I think the function should be something along the lines of:
df<-mutate(df, c2=ifelse(df$c=="2 to 4", sample(2:4, 1, replace=TRUE), "NA"))

Which should produce a new column in my dataset that replaces all the values of "2 to 4" with a random integer between 2 and 4, however, this is not working and replacing every value with "NA".
Ideally, I am trying to do something where the dataset:
df<-c("2 to 4","2 to 4","5 to 6")

Would add a new column:
df<-c2("3","2","5")

Does anyone have any idea how to do this?
Answer: We can split the string on "to" and create a range between the two numbers after converting them to numeric and then use sample to select any one of the number in range.
df$c2 <- sapply(strsplit(df$c1, "\\s+to\\s+"), function(x) {
         vals <- as.integer(x)
         sample(vals[1]:vals[2], 1)
})

df
#      c1 c2
#1 2 to 4  2
#2 2 to 4  3
#3 5 to 6  5

data
df<- data.frame(c1 = c("2 to 4","2 to 4","5 to 6"), stringsAsFactors = FALSE)

Comment: @lmo Done.  Just out of curiosity, how do both differ? Does any one have advantage over the other? except that one expects integer to be returned and other numeric ?
Comment: It is not 100% clear in this case, but `as.integer` creates a vector that is 50% the size of as.numeric. A further benefit in this case, and probably the primary one, is that `sample` and `:` expect integer arguments. The `as.integer` removes the need for a copy. Again, not super important in this case, but can be important in working with large datasets.
Comment: A silly improvement: replace `as.numeric` with `as.integer`.
Comment: Although, I did have to add `unlist()` and `as.character()` to get it to work in practice:

 `vals<-as.integer(unlist(strsplit(as.character(x), "\\s+to\\s+")))`
Answer: We can do this easily with sub.  Replace the to with : and evaluate to get the sequence, then get the sample of 1 from it
df$c2 <- sapply(sub(" to ", ":", df$c1), function(x)
                sample(eval(parse(text = x)), 1))
df
#      c1 c2
#1 2 to 4  4
#2 2 to 4  3
#3 5 to 6  5

Or with gsubfn
library(gsubfn)
as.numeric(gsubfn("(\\d+) to (\\d+)", ~ sample(seq(as.numeric(x),
        as.numeric(y), by = 1), 1), df$c1))

Or with read.table/Map from base R
sapply(do.call(Map, c(f = `:`, read.csv(text = sub(" to ", ",", df$c1),
         header = FALSE))), sample, 1)

data
df <- structure(list(c1 = c("2 to 4", "2 to 4", "5 to 6")),
 class = "data.frame", row.names = c(NA, -3L))


prove $[Av]_s = P^{-1} AP[v]_s$

Question: Let $S= \{v_1,...,v_n\}$ be a basis for $ \Bbb R^n $ and $P = [v_1\cdots v_n] $ where $v_j$ is column vector . Prove that for any square matrix A of order n and column vector V,
$$[Av]_s = P^{-1} AP [v]_s$$
I don't even know how to start, can someone kindly give a hint? Thanks!
Sorry for the formatting if it is wrong...
Comment: Latex is much simpler as it seems on the first spot, you can learn it in 5 minutes.
Comment: @peterh sorry it was sent before I finish. Thx for ur comment
Answer: That looks like my homework (which is probably late by now). The hint states that $P$ is the transition matrix from $S$ to the standard basis $E$.
This means that for any column vector $u$:
$$P[u]_S=u$$
Hence:

 $[Av]_S=P^{-1}P[Av]_S=P^{-1}Av=P^{-1}AP[v]_S$
Comment: haha, yes it's homework. Anyway, I summit alr. ;P

prove $[Av]_s = P^{-1} AP[v]_s$


Reinstall package from package-lock.json file

Question: Consider this scenario:
I installed some packages like jquery and bootstrap with npm install.
After this npp make a package-lock.json file that describes installed package info.
When I push folder project to git server node_modules folder wasn't sent because of gitignore and only json file is placed on server.
If someone clone this repo he only has json file. How we can restore or reinstall all dependencies from package-lock.json file?
I tried npm install, npm ci, npm i but nothing restored.
Any idea?
Comment: `npm ci` installs dependencies solely based on package-lock.json.
Comment: @akx no such file package.json error returns.
Comment: Your package.json _and_ your package-lock.json should be in the repo.
Comment: "node_modules folder wasn't sent because of gitignore and only json file is placed on server" you [generally don't want to commit node_modules](https://stackoverflow.com/a/18129049/6243352). You can restore it from package.json.
Answer: Simply you need to run 'npm i' from your project folder. Also make sure, that all your dependencies are in your package.json file. And you need to track changes in your package.json file in future, because commiting 'node_modules' is a real bag thing. it will be always ignored by *.gitignore settings.
Also use "npm i %package% --save" to add current package to package.json.
Comment: Create a folder. Run```npm install bootstrap```. Then remove node module folder. Now with a package-lock.json how you can restore bootstrap?
Comment: Running `npm install`, as Paul suggested, will restore the files in the `package-lock.json` by default. You can read more in the documentation at https://docs.npmjs.com/configuring-npm/package-locks.html.


Is it mandatory for $F$ to be divergence free to have surface independent property?

Question: I was trying to solve the problem to find $\int_{C}F\cdot dr$ where $C$ is the curve of intersection of cone $z^2=x^2+y^2$ and plane $z=1$. Also $F(x,y,z)=y\vec{i}+z\vec{j}+x\vec{k}$

So here we have two possible surfaces $S_1$ and $S_2$ with same boundary $C$ oriented positively.
I tried verifying for above $F$ which is divergence free and successfully showed that $$\iint_{S1}\text{curl}(F) \cdot dS_1=\iint_{S_2}\text{curl}(F)\cdot dS_2$$
But in this link:
https://mathinsight.org/stokes_theorem_examples
they have taken $F=\left(\sin x-\frac{y^3}{3}, \cos y+\frac{x^3}{3}, xyz\right)$ and its been told that
$$\iint_{S_1}\text{curl}(F)\cdot dS_1=\iint_{S_2}\text{curl}(F)\cdot dS_2$$
any clarification?
Comment: i corrected it by editing the post
Answer: The field $F$ in your first example is "by coincidence" divergence free. This has no avail for the line integral $\int_C F\cdot dr$.
By Stokes' theorem this line integral is equal to the surface integral $\int_S{\rm curl}(F)\cdot dS$ for any surface $S$ with $\partial S=C$, in particular for the two surfaces $S_1$, $S_2$ in your figures:
$$\int_{\partial S} F\cdot dr=\int_S{\rm curl}(F)\cdot dS\ .$$
There is no divergence appearing here.
On the other hand the curl of any field $F$ is divergence free: $${\rm div}\,{\rm curl}(F)\equiv0\ .$$ This plays a rôle in your second example: The two surfaces $S_1$, $S_2$ together bound a three-dimensional cone $K$, whereby $\partial K=S_1-S_2$. By Gauss' theorem we therefore have
$$\int_{S_1}{\rm curl}(F)\cdot dS-\int_{S_2}{\rm curl}(F)\cdot dS=\int_{\partial K}{\rm curl}(F)\cdot dS=\int_K {\rm div}\,{\rm curl}(F)\>dV=0\ .$$


Bug em um código em C

Question: Eu sei, esse código é bem simples e ta meio feio tbm, sou iniciante e estou tentando facilitar essa função, alguém pode me dizer qual o erro?
Imagem do bug:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
char tempo[5],a[25];
int op;

printf("EAE MEN\n\n1.Apagar o bixin\n2.Desligar e ligar dnv\n3.Tirar uma sonequinha\n");
scanf("%d",&op);

switch(op){
case 1:
a=="shutdown -s -t ";
printf("Desliga em qts segundos msm?\n");
scanf(" %s",tempo);
strcat(a,tempo);
break;
case 2:
a=="shutdown -r -t ";
printf("Reinicia em qts segundos msm?\n");
scanf(" %s",tempo);
strcat(a,tempo);
break;
case 3:
a=="shutdown -h -t ";
printf("Sonequinha em qts segundos msm?\n");
scanf(" %s",tempo);
strcat(a,tempo);
break;
default:
printf("Numero Invalido, bro, sabe ler n eh?\n");
return 0;
}
system(a);

return 0;
system("pause");
}

Comment: Ao invés de fotos do erro você pode copiar o erro e colar diretamente aqui, fora que isso não é um BUG e sim um erro seu, BUG seria se fosse falha no compilador C que você usa, mas o caso ae é um erro seu. **Leia:** [Postar código como imagem](https://pt.meta.stackoverflow.com/a/5485/3635)
Comment: Seria bom [edit] e colocar o código na pergunta. Referências externas só devem ser usadas como complemento (e isso é melhor para quem for te ajudar já ver o problema todo num lugar só). Além disso, é melhor postar o erro como texto, e não como imagem.
Answer: Você está usando o operador relacional ==em vez do operador de atribuição =, em todas as declarações em que  a, string de caracteres, é operador da esquerda.
A string a trata-se de um array do tipo char. Em C, você não pode fazer um declaração de atribuição para este tipo de dado. Você precisa usar a função strcpy(arrayDeDestino, arrayFonte).
Comment: errei ali na hora de mandar o código, eu tava colocando com = msm (como pode ver no erro no cmd), coloquei == só pra testar msm sabendo q tava errado e mandei o errado, ce sabe me dizer qual o erro msm com um =
Comment: Eu editei a resposta para ficar mais amplo.

Bug em um código em C


URI Rest com HttpServlet

Question: Eaí galera, estou desenvolvendo um mini framework para fins de estudos, usando o pattern front controller em java, e me deparei com o seguinte problema.
Antes de mais nada vou explicar como está funcionando.
Eu embuti o servidor jetty dentro do framework, quando eu starto minha aplicação(usando o mini-framework) ele vai varrer as classes do meu projeto verificar se existe duas anotações que eu criei nas minhas classes que são @Rest (define que a classe é um controller) e @Get (faz o mapeamento da request) e joga em um hashMap com o mapeamento como chave e a classe controller como valor.
@Rest
public class UserController {

    @Get("/books")
    public String getBook() {
        Book book = new Book();
        book.setAuthor("NetoDevel");
        book.setTitle("RileyFramework");
        book.setPrice(0.0d);
        return JsonReturn.toJson(book);
    }

    @Get("/book/:id")
    public String findOne(String id) {
        return id;
    }
}

Quando eu recebo a requisição, jogo ela na key do meu map e pego o valor que é a classe controller e instancio e invoco o metodo beleza?
Até aqui tudo bem funcionando perfeitamente, mas eu quero definir parametros na minha URI, na arquitetura REST.
Formato que eu quero implementar:
http://localhost:8080/books/:id

e não
http://localhost:8080/books?id=1

Minha pergunta é: Como pegar lá no meu servlet que está implementado o valor de :id ?
Eu posso ter mais de um param nesse formato abaixo:
http://localhost:8080/books/:id/author/:id

Segue o link do projeto no github:
https://github.com/NetoDevel/riley-framework
Comment: A resposta te ajudou ou precisa de mais detalhes?
Answer: Obtenha o mapa com todos os parâmetros enviados no request através do seguinte código:
Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

Comment: Não funcionou e essa classe HandlerMapping é do spring? a ideia é implementar o próprio.
Comment: @JoseVieiraNeto Entendi, então veja este link http://stackoverflow.com/a/8715566/5230740.
Comment: eu até tinha visto já essa pergunta, mas é algo difícil de manipular por que ele faz split por barra, vai ficar difícil saber quem é os parâmetros na uri. ex: /books/1/author/1 quando eu fizer o split ele vai quebrar em 4 índices books, 1, author, 1 blz? eai como saber quem é os param da uri?
Comment: Em cada URI tu tem um formato esperado. Neste caso, os param é o book=indice[1] e author=indice[3]

URI Rest com HttpServlet


What is the official documentation of Scala?

Question: I see two links whenever searching up official documentation for Scala:
This: https://www.scala-lang.org/
And this link: https://www.scala-lang.org/api/2.13.3/
What is the difference between the two? Which one is the official documentation for the language, or is there some other link?
Comment: One is the auto generated Scala doc will cover everything, the other is the language's website that has tutorials etc.
Comment: All of the official documentation is ultimately reachable starting from https://www.scala-lang.org/
Answer: docs.scala-lang.org gives links to main sources of documentation, for example,

Scala Language Specification (SLS)
Scala Library API

The source code of SLS is at https://github.com/scala/scala/tree/2.13.x/spec which can be useful for searching for a particular symbol in SLS via IDE (because browsers make it hard). SLS is the authoritative reference on Scala. contributors.scala-lang.org and scala/contributors is where in-depth discussion on design of Scala happen.
For a more approachable user guide from the designer of Scala consider Programming in Scala which is authored by Martin Odersky et al.


Is conic programs with exponential cone solvable in polynomial time?

Question: I'm trying to find out some theoretical guarantees of time complexity for my problems.
My problem is to minimise a log-sum-exp function.
I found that the minimisation of log-sum-exp function can be transformed into a conic program with exponential cone as described in Mosek documentation.
Is the conic program with exponential cone solvable in polynomial time? If so, which algorithms can be used to solve the problem in polynomial time?
Is the minimisation of log-sum-exp function actually transformed into an equivalent conic program with exponential cone in real-world solvers? (e.g., cvxpy)
Sorry for my lack of background.
Comment: One of the reasons people study convex optimization problems so extensively is be cause we have fast algorithms for solving them.
Comment: @CyclotomicField I agree with you. That's why I study convex optimisation. But obviously not all convex optimisation problems can be solvable in polynomial time complexity. I'd like to know the specific problem (the minimisation of log-sum-exp function) is also in the category that we can say "we have fast algorithms for this", and "which algorithms are fast enough for this".
Comment: You say that they obviously can't when I just told you we can. Convexity is a strong property and essentially turns every problem into linear regression. It's super fast.
Comment: @CyclotomicField If you don't mind, could you share any references for that?
Comment: https://web.stanford.edu/~boyd/cvxbook/ is a good start and there are a series of video lectures by Boyd as well that covers the material extensively. Also, if you find it defies intuition I would simply say that convexity and lines are intimately linked from a geometric standpoint. This should at least hint as to why we can linearize these problems.
Comment: I found the video lectures. They're excellent. https://see.stanford.edu/Course/EE364A
Comment: @CyclotomicField What do you think of [these counterexamples](https://mathoverflow.net/questions/92939/can-all-convex-optimization-problems-be-solved-in-polynomial-time-using-interior)?
Comment: One algorithm isn't all algorithms.
Answer: In a DCP (Disciplined Convex Programming) tool like CVXPY, CVX or similar, a function like log-sum-exp will be converted to conic form as in the modeling link you found, because that is the form accepted by the underlying solvers.
The algorithm used by MOSEK for exponential cone optimization is presented in this paper https://link.springer.com/article/10.1007/s10107-021-01631-4. There is no polynomial complexity proof like for SOCP known for this algorithm. The algorithm seems to perform well in practice though.


Change virtual QEMU image location

Question: I've got an existing QEMU Virtual Server running on Fedora 11.  Having troubles trying to find out how to change the location of where the Virtual Images are stored.
Can anybody provide any help please?
Thanks in advance!
I'm also new to Linux Server Administration - n00b in other words - so this might seem lazy but I need to know commands or where to look
Answer: QEMU is usually run from shell, even if a number of GUI exist all around. Try doing a ps aux | grep qemu and see if you can find in the output the commandline for qemu binary (look for -hdc option).
Answer: I searched this question when I moved an img file to a different place causing virt machine mgr to not be able to find it.
The fix was to change the associated xml file in /etc/libvirt/qemu/:
<disk type='file' device='disk'>
  <driver name='qemu' type='raw'/>
  <source file=[new location/name].img'/>

For the change to take effort you need to reboot.
Answer: Figured it out looking at the manuals for a fair few commands, the following command has worked
virt-install --name=WindowsXPIE6 --ram=512 --file=/media/Filestore/virtual_machines/WindowsXPIE6.img --import
--name is the name (label) of the Virtual Machine
--ram is the amount of RAM in mb
--file is the location of the .img file
--import is to tell QEMU to use an existing disk image
Answer: You may find the the location of your server image:

$ find / -iname server.img

After run qemu from command line as :

$ qemu -boot c -hda server.img -net nic -net tap

Change virtual QEMU image location