How to get the current viewed users uid

Question: If I am viewing a users profile page, how do I obtain and display (in a block) their uid? NOTHING to do with the current logged in user. I need to display the users id in a block on their page.
Answer: If you are showing a standard drupal user profile page this should get you going:
  $user = user_load(arg(1));
  $user->uid; // access user id

This assumes the path is user/uid. If your path looks different adjust the arg(position_in_path) to your needs.
Comment: I am unsure why BetaRite uses the user ID (already in the path) to load the user object only then to output the user ID.
Use this instead. `if (arg(0) == 'user' && is_numeric(arg(1))) $userid = arg(1);`
Answer: A better option would be to use template_preprocess_user_profile(&$variables) and add the user id from here - that way you're not relying on any URL arguments (arg() is a recipe for fail).
Pop the following in your template.php
function MYTHEME_preprocess_user_profile(&$variables) {

  $account = $variables['elements']['#account'];
  //Add the user ID into the user profile as a variable
  $variables['user_id'] = $account->uid;
  // Helpful $user_profile variable for templates.
  foreach (element_children($variables['elements']) as $key) {
    $variables['user_profile'][$key] = $variables['elements'][$key];
  }

  // Preprocess fields.
  field_attach_preprocess('user', $account, $variables['elements'], $variables);

}

This will make the UID available to the user-profile.tpl.php template as a variable called $user_id.
This means that you can then copy user-profile.tpl.php from the modules/user directory to your theme directory and change it to the following:
<div class="profile"<?php print $attributes; ?>>
  <?php print $user_id; ?>
  <?php print render($user_profile); ?>

Obviously you'll want to style it and add extra DIVs and whatnot, but at it's most basic this will put the user id at the top of the user profile page.
Comment: I'm not sure it is the answer on @Jamie's question. Anyway, `user-profile.tpl.php` already has User Id available.
Comment: Aah...I missed the 'display in a block' part.  I did a `print_r` on the `$user_profile` variable and didn't see the UID there.  If it was part of the render array, then surely it would be rendered.  Either way, the above code works fine and does allow for the UID to be rendered onto the page.
Comment: Yup, just checked.  By default, UID is not part of the `$user_profile` render array.
Comment: nobody forbids you to `print $variables['elements']['#account']->uid;` in `user-profile.tpl.php`, but it's not the answer I think. Your code is useful, so I haven't downvoted it :)
Answer: You can use this function menu_get_object('user')
Answer: probably not the best approach in drupal 8 but this work
$current_path = \Drupal::service('path.current')->getPath();
    $exploded_path= explode('/',$current_path);
    $uid=end($exploded_path);
    if (prev($exploded_path) =='user')
      $user=User::load($uid);

Answer: as BetaRide in the page profile you can use arg(1) it will give you user profile and then you can use user_load()
Comment: OP says: NOTHING to do with the current logged in user. But global $user does give you exactly this.
Comment: yey I think the question need the logged in user sorry

How to get the current viewed users uid


What does 128-bit file system mean?

Question: In the introduction to ZFS file system, I saw one statement:

ZFS file system is quite scalable, 128 bit filesystem

What does 128-bit filesystem mean? What makes it scalable?
Answer: ZFS is a "128 bit" file system, which means 128 bits is the largest size address for any unit within it. This size allows capacities and sizes not likely to become confining anytime in the foreseeable future. For instance, the theoretical limits it imposes include 2^48 entries per directory, a maximum file size of 16 EB (2^64 or ~16 * 2^18 bytes), and a maximum of 2^64 devices per "zpool". Source: File System Char.
The ZFS 128-bit addressing scheme and can store 256 quadrillion zettabytes, which translates into a scalable file system that exceeds 1000s of PB (petabytes) of storage capacity, while allowing to be managed in single or multiple ZFS's Z-RAID arrays. Source: zfs-unlimited-scalability
Answer: TLDR it can hold much larger files then a 64 bit F. such as. EXT.
ZFS is a 128-bit file system, so it can address 1.84x10^19 times more data than 64-bit systems such as Btrfs. The limitations of ZFS are designed to be so large that they should not be encountered in the foreseeable future.
Some theoretical limits in ZFS are:

2^48 — Number of entries in any individual directory
16 Exbibytes (264 bytes) — Maximum size of a single file
16 Exbibytes — Maximum size of any attribute
256 Zebibytes (278 bytes) — Maximum size of any zpool
256 — Number of attributes of a file (actually constrained to 248 for the number of files in a ZFS file system)
2^64 — Number of devices in any zpool
2^64 — Number of zpools in a system
2^64 — Number of file systems in a zpool

More here.

What does 128-bit file system mean?


Node testing.test is not a function

Question: Im trying to call a function in another file but no matter what I do, it will not recognize that function. I get

uncaughtException: testing.test is not a function

//testing.js
module.exports = function(){
    return{
        "test" : function(){
            return new Promise(function (resolve, reject) {

            console.log('worked!')
                resolve(resolve({'data': "success"}))
            })
        }
    }
}

And then in any other file:
//other file
var testing = require("testing.js");
testing.test().then(function(data){
   console.log(data)
})

I know the directory is correct, my IDE even shows that what I'm trying to call is a function. Where did I go wrong?
Answer: Your variable testing is a function (that's what you are exporting).  You have to call it in order to get the object you want.
//other file
var testing = require("testing.js");
testing().test().then(function(data){    // added parens after testing()
   console.log(data)
})

Or, change the export to just export the object directly so you don't have to call a function first to get the object:
//testing.js
module.exports = {
    "test" : function(){
        return new Promise(function (resolve, reject) {

        console.log('worked!')
            resolve(resolve({'data': "success"}))
        })
    }
}

// then, this will work because testing is the actual object
var testing = require("testing.js");
testing.test().then(function(data){
   console.log(data)
})

Choose one or the other of these two options.  Keeping the export as a function allows you to fetch a new object (like calling a constructor or factory function), each time you call the function.  Exporting the object directly allows all users or your module to have access to the same object.  So, which way to go ultimately depends upon what type of design you want.  You just have to make sure the caller and the callee are acting in concert to use the exported value appropriately.
Comment: The wizards have spoken. Thanks :) Worked!
Answer: Change testing.js to the following:
module.exports = {
    "test" : function() {
        return new Promise(function (resolve, reject) {

            console.log('worked!')
            resolve(resolve({'data': "success"}))
        })
    }
}

Now a object with a property called test is being exported, so you can use it in the way you intended in the other file:
Comment: What did you change and why?
Comment: Now a object with a property called `test` is being exported, so you can use it in the way you intended in the other file
Comment: Please put that explanation in your answer.
Comment: Thanks for this solution! This makes sense. The codebase I was working with is quite complex in how it chooses to do things.

Node testing.test is not a function


Image styles to make all user inserted images appear as circles

Question: Users can insert images on my site...i want that all of them are displayed in a similar fashion. So i created a new style under Image Styles. However, how can i make sure that all images appear as circled. Even if a user inserts a square image, the final display should appear in a circle. I do not find any option to do so. Any help or advice.
Thanks
Comment: What method are users using to "insert" an image onto your site?
Comment: i have create a field called for inserting them as images but i do have media module installed
Answer: To create the image style you want, you'll need to install the ImageCache Actions module to get the "Rounded Corners" effect.  Note that when you install this module, you need to turn on several different modules in drupal (and I'm not sure which one provides "Rounded Corners"):  image_styles_admin, imagecache_canvasactions, image_effects_text, imagecache_customactions, imagecache_coloractions, imagecache_autorotate, imagecache_actions.
Once you have the Rounded Corners effect, you should be able to create the behavior you are looking for.  Here's an example:

The only thing that you can't see on the screenshot is the "radius" setting for the rounded corners effect.   To get a truly round image, it should be set to half of the height/width used in the scale & crop step.  In the example, scale & crop is set to 100x100 and radius is set to 50.  If you set scale & crop to 500x500, you'd set radius to 250.
Once you've got the image style you want, go to Administration > Structure > Content Types, and choose the content type that has the image field.  Go to the "Manage Display" tab, and click on the settings icon for the image field.  This will allow you to select the image style to be used for this image field.
You may need to do this for multiple display modes for your content type, for example "Default" and "Teaser."
Comment: i know that but how can i make them appear in circle, i.e, how to create a style for that
Comment: Okay, I thought from your original post that you had already created the image style.  I've updated the answer-- to create that image style, use the ImageCache Actions module.
Comment: hey...i tried creating a style but there is no option to create a circular image style..would really appreciate some help
Comment: More details added.  If this doesn't solve the problem, maybe a description of where you're running into trouble would help.
Comment: i have added that style...in the preview its showing a rounded image...however when i go to the node it still appears as a square... i have cleared all the cache but still no effect...
Comment: Did you set the display mode of the content type to use your new image style?  Can you post some screenshots of your image style, content type, and the display that doesn't appear as expected?
Comment: imagecache_canvasactions is the one that you need. And you must set the radius to the image width divided by two. So a 200x200 square, would need a radius of 100.
Answer: You can create png masks for your user pictures above them and clip visually actual user pictures. Masks should be in the color of background and added with css above the bare image tag in some of existing field wrappers.
But, there may be different sizes showing up in your site. So you need a mask and css style for every appearance. User should be forced to enter x=y image, or their images should be cropped or they would not fit circle.
It needs more investigation, planning and some precise design photoshop effort,  but on the bright side you won't use any extra module.
From the other side, if you can spend some more computing power/installing few modules, proposed way to do it drupal way is more "secure".
Comment: Actually, if you are going to use CSS to do it, it's probably better to use border-radius: 50% instead of a PNG mask.  Certainly less work!


A class of functions dense in $L^2$

Question: Suppose $f\in L^2([0,1],\Sigma,\mu)$. Is the class of all $$f=\sum_{i=1}^n \alpha_i (\chi_{A_i}-\chi_{[0,1]/A_i} )$$$A_i\in \Sigma$ to be  dense in $L^2([0,1],\Sigma,\mu)$?
Thanks.
Answer: Suppose $g\perp (\chi_{[0,x)}-\chi_{[x,1]})$ for all $x\in [0,1].$ Then $\int_0^x g = \int_x^1g, x \in [0,1].$ By the Lebesgue differentiation theorem, $g(x)=-g(x)$ for a.e. $x.$ Thus $g=0$ a.e. This shows that the subspace you defined is dense in $L^2.$
Comment: Hi, is it diffrentiation theorem and approach also apply for other measurable space if [0,1] is replaced by  X and  with other measure?

A class of functions dense in $L^2$


Fatal error ao criar um novo módulo Zend Skeleton Application

Question: Estou tentando criar um módulo "Livraria" dentro de meu Zend Skeleton Application, porém dá um erro muito grande que não sei como lidar:

Fatal error: Uncaught exception 'Zend\ModuleManager\Exception\RuntimeException' with message 'Module (Livraria) could not be initialized.' in C:\xampp\htdocs\zf2-tutorial\vendor\zendframework\zend-modulemanager\src\ModuleManager.php:203 Stack trace: #0 C:\xampp\htdocs\zf2-tutorial\vendor\zendframework\zend-modulemanager\src\ModuleManager.php(175): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent)) #1 C:\xampp\htdocs\zf2-tutorial\vendor\zendframework\zend-modulemanager\src\ModuleManager.php(97): Zend\ModuleManager\ModuleManager->loadModule('Livraria') #2 C:\xampp\htdocs\zf2-tutorial\vendor\zendframework\zend-eventmanager\src\EventManager.php(271): Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent)) #3 C:\xampp\htdocs\zf2-tutorial\vendor\zendframework\zend-eventmanager\src\EventManager.php(143): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent)) #4 C:\xampp\htdocs\zf2-tutorial\vendor\zendframework\zend-moduleman in C:\xampp\htdocs\zf2-tutorial\vendor\zendframework\zend-modulemanager\src\ModuleManager.php on line 203

Obs: Se eu não adiciono 'Livraria' no arquivo modules.config.php a página abre normalmente, porém dá um erro APENAS na pagina localhost/livraria (a página localhost/application abre normalmente). O seguinte erro aparece:

A 404 error occurred
  Page not found.
  The requested URL could not be matched by routing.
  No Exception available

Configuração do module.config.php:

namespace Livraria;

use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;

return [
    'router' => [
        'routes' => [
            'livrariahome' => [
                'type' => Literal::class,
                'options' => [
                    'route'    => '/livraria',
                    'defaults' => [
                        'controller' => Controller\IndexController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
            'application' => [
                'type'    => Segment::class,
                'options' => [
                    'route'    => '/livraria[/:action]',
                    'defaults' => [
                        'controller' => Controller\IndexController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
        ],
    ],
    'controllers' => [
        'factories' => [
            Controller\IndexController::class => InvokableFactory::class,
        ],
    ],
    'view_manager' => [
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => [
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'livraria/index/index' => __DIR__ . '/../view/livraria/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ],
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
    ],
];

Configuração do Module.php:

namespace Livraria;

class Module
{
    const VERSION = '3.0.2dev';

    public function getConfig()
    {
        return include __DIR__ . '/../config/module.config.php';
    }
}

Configuração do modules.config.php:

return [
    'Zend\Router',
    'Zend\Validator',
    'Application',
    'Livraria',
];

Configuração do IndexController.php:

namespace Livraria\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $nome = 'Olá Livraria';
        return new ViewModel(array('nome' => $nome));
    }
}

Caminhos das pastas:

module/
  Livraria/
     config/
        module.config.php
     src/
        Controller/
            IndexController.php
        Module.php
     view/
        error/
            404.php
            index.phtml
        layout/
            layout.phtml
        livraria/
            index/
               index.phtml

Agradeço desde já a ajuda, e eu precisava muito da solução.
Answer: Creio que o problema esteja na sua pasta "src". O correto seria ter uma pasta com o nome do módulo e, ai sim, ter a pasta controller e o arquivo Module.php, exemplificado abaixo.
module/
      Livraria/
         config/
            module.config.php
         src/
            Livraria/
                Controller/
                     IndexController.php
                Module.php
         view/
            error/
                404.php
                index.phtml
            layout/
                layout.phtml
            livraria/
                index/
                   index.phtml

Answer: Seu arquivo Module.php está no local errado, ele precisa ficar na raiz da pasta do seu módulo:
module/
    Livraria/
        config/
            module.config.php
        src/
            Livraria/
                Controller/
                    IndexController.php
        view/
            error/
                404.php
                index.phtml
            layout/
                layout.phtml
            livraria/
                index/
                    index.phtml
        Module.php


How to pick media files in Xamarin forms for both iOS and Android?

Question: I am trying to find some way which can be used to pick photos within forms without writing platform specific code in both iOS and Android.
Answer: You can use the package xam.Plugin.Media from NuGet.
//...
using Plugin.Media;
//...

async void Button_Clicked(object sender, System.EventArgs e)
{
   await CrossMedia.Current.Initialize();

   if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
    {
      await DisplayAlert("No Camera", ":( No camera available.", "OK");
      return;
    }

   var file = await CrossMedia.Current.PickPhotoAsync();

   if (file == null)
     {
       return;
     }

   else
     {
       await DisplayAlert("File Location", file.Path, "OK");
     }

}

Don't forget add Privacy

in iOS (info.plist)

<key>NSCameraUsageDescription</key>
<string>This app needs access to the camera to take photos.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to photos.</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app needs access to microphone.</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>This app needs access to the photo gallery.</string>

in Android

if your users are running Marshmallow the Plugin will automatically prompt them for runtime permissions. You must add the Permission Plugin code into your Main or Base Activities:
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

For more detail you can access here


Enable regular PC keyboard for direct recording Synth1 VST in REAPER?

Question: I'd like to record Synth1 and play wit it in REaper using my PC typing keyboard. I open Synth1 and the keyboard doesn't work as a playing keyboard.
How can I enable it to do so having Synth1 opened?
Answer: There are a few things you should do:

Ensure the track is armed for recording In most DAWs, a track will not "play" unless armed, this is to help avoid MIDI inputs triggering every track all the time by default
Enable the Virtual MIDI keyboard Per this post on the forums, one user posted that this is in the "view" menu of Reaper
Set the track to receive it as input There may be an In/Out section on the track, you will want to make sure the "In" is coming from either "All Ins" or "Virtual MIDI Keyboard" specifically, and the "Out" should be going to a mix bus or your Master track. In either case, make sure the receiving channel is routed correctly and at the correct volume.

From how it sounds, it sounds like the virtual MIDI keyboard will automatically receive input from your computer keyboard. I haven't used Reaper personally, so I apologize if these instructions aren't exact, but the process is pretty similar across most DAWs.


JQuery datepicker adds a new button next to textbox

Question: I have a textbox and a dropdown menu. Based on the selected value from dropdown menu, I change the textbox to a datepicker field, if necessary. The functionality works fine, but I am seeing that there is a small button between the textbox and dropdown when the datepicker is activated. It vanishes when the datepicker is destroyed.
When I used firebug to look at the HTML, I am seeing the following lines being added
<button class="ui-datepicker-trigger" type="button">

</button>

Any idea how I can get rid of this button and just trigger the datepicker calendar when user clicks on the textbox?
Comment: Can you please share your code?
Answer: I think that comes from using this option to datepicker:
buttonImage: '/images/drop-down.gif'

If you don't want a button, don't use that option.
Answer: Make sure you don't give the following propeties when you bind the textbox with datepicker
 buttonImage: 'images/icon_calendar.gif',
 buttonImageOnly: true,


Encoding a PHP script in UTF-8 gives funny characters

Question: I've changed the encoding of the PHP script (as in the encoding of the actual .php file) to UTF-8, which I did by convert encoding in Notepad++, and this has resulted in  being echoed at the beginning of the script. I can't get rid of it. I can't see any such characters in the script. I even tried copy & pasting into a new file but it's still there.
Any ideas how to get rid of it?
Comment: Change encoding to UTF-8 __WITHOUT__ BOM and then save again
Comment:  this is UTF8-bom signature :(
Comment: Create new file in UTF-8 WITHOUT BOM and after put there a text
Comment: OK, thanks guys. Someone please post this as an answer so I can accept it.
Answer: As stated in the comments  is the UTF-8 bom signature:

Change encoding to UTF-8 WITHOUT BOM and then save again


Software Configuration Management - Has Google Got it Wrong?

Question: I am learning about SCM - I have looked at the usual places like wiki and google. But Google Code University gives a funny description of SCM: Google Code University
It is completely void of any mention of build tools such as ANT which I thought were a key factor in SCM, has Google got it wrong?
Comment: You can version just about any content and it is not always related to build tools. Example: An artist may keep version history on a piece of electronic art.
Answer: Well, wikipedia http://en.wikipedia.org/wiki/Software_configuration_management says this
In software engineering, software configuration management (SCM) is the task of tracking and controlling changes in the software. Configuration management practices include revision control and the establishment of baselines.
So that includes tools like SVN, not necessarily ANT


Enumerative Combinatorics

Question: Sam has $255$ cakes, each labeled with a unique non-empty subset of $\{1, 2, 3, 4, 5, 6, 7, 8\}$. Each day, he chooses one cake uniformly at random out of the cakes not yet eaten. Then, he eats that cake, and all remaining cakes that are labeled with a subset of that cake (for example, if he chooses the cake labeled with $\{1, 2\}$, he eats that cake as well as the cakes with $\{1\}$ and $\{2\}$). The expected number of days that Sam eats a cake before all cakes are gone can be expressed in the form ${p\over q}$, where $p$ and $q$ are relatively prime natural numbers. Find $p+q$.
Comment: Calvin, what's the story here? This is a cute but not hard question, and I know you are usually strongly opposed to posting contest problems here, so why did you put a bounty on this?
Comment: What's the source of this question?  Is it Project Euler or anything like that?
Comment: Looks like Brilliant Math. @mjqxxxx
Comment: @david I'm not opposed to posting of past contest problems, but am opposed against those who want to want an answer to live problems without having to do work, thereby claims credit. I do answer past problems at times, if you look at my answers. This is a NIMO problem, but I didn't like another solution of it that I saw.
Comment: @CalvinLin Thanks for the answer. I was also misreading the question: I missed that he always chooses a cake which is available to eat. Without that proviso, the question is just how many times you can choose a random subset of $\{ 1,2,\ldots,8 \}$ before you choose the whole set.
Comment: @CalvinLin This is an OMO problem, not a NIMO problem.
Answer: Fix $n>1$. Let $S=\{1,\ldots,n\}$.  In the end, we will set $n=8$ to solve the problem.
Let $\{X_i\}_{i\ge 1}$ be the sequence of random sets as described in the problem. $\{X_i\}$ is a random sequence with random finite length. Let $N$ be the number of days on which cake is eaten, i.e., the length of this sequence.
We will construct a different random sequence of sets $\{X'_i\}_{i\ge 1}$ that is equivalent to $\{X_i\}_{i\ge 1}$, but that is much easier to analyze.
Let $\{X'_i\}_{i\ge 1}$ be an i.i.d. sequence of random sets in which $X'_i$ is chosen uniformly from $2^S$, the power set of $S$ (null set included).  Define $I_i$ as follows:
\begin{eqnarray}
I_1 &=& \begin{cases} 1\text{ if } X'_1 \ne \emptyset\\
0 \text{ otherwise} \end{cases}\\
I_i &=& \begin{cases}1\text{ if } X'_i \not \subset X'_{j} \mbox{ for all } j<i \\
0 \text{  otherwise}.
\end{cases}
\end{eqnarray}
Let $M_i$ be the $i^{\text{th}}$ smallest index $j$ such that $I_j=1$. For example, if $I_1=I_2=I_4=I_6=0$ and $I_3=I_5=1$, then $M_1=3$ and $M_2=5$. Then the random sequence $\{X'_{M_i}\}$ has exactly the same probability distribution as $\{X_i\}$.
Intuitively, $\{X'_i\}$ generates $\{X_i\}$ by repeatedly sampling $2^S$ until the next element of $X_i$ is found. At each step, if the generated $X'_i$ is a subset of some previous $X'_j$, $j<i$, then $X'_i$ is essentially ignored. This is reflected in setting $I_i=0$. Each time a new set $X'_i$ is generated with $I_i=1$, the next element of the sequence $X_j$ is generated.
Let
$$
N' = \sum_{i=1}^{\infty} I_i.
$$
Observe that, by the argument above, $N'$ has precisely the same distribution as $N$.
We will calculate $\mathbb{E}(N')$. By definition, we see
$$
\mathbb{E}(I_i) = \mathbb{P}(I_i=1).
$$
Thus,
$$
\mathbb{E}(I_1) = 1 - 2^{-n}.
$$
For $i>1$, we may condition on the size $s$ of $X'_i$ and use the facts that $X'_i$ are i.i.d. and that a subset of $S$ with $s$ elements has $2^{n-s}$ supersets in $S$, and so
$$
\mathbb{P}(X'_i\not \subset X'_j|X'_i\mbox{ has $s$ elements}) = 1 - 2^{-s} \ \mbox{ if $i\ne j$}.
$$
We have
\begin{eqnarray}
\mathbb{P}(X'_i\not\subset X'_j \mbox{ for all }j<i) &=& \sum_{s=0}^n 2^{-n} \left(\begin{array}{c}n\\s\end{array}\right) (1-2^{-s})^{i-1}.
\end{eqnarray}
Thus,
\begin{eqnarray}
\mathbb{E}(N) &=& \sum_{n=1}^{\infty} \mathbb{E}(I_i) \\
&=& 1 - 2^{-n} + \sum_{i=2}^{\infty} \sum_{s=0}^n 2^{-n} \left(\begin{array}{c}n\\s\end{array}\right) (1-2^{-s})^{i-1} \\
&=& 1 - 2^{-n} + \sum_{s=0}^n \sum_{i=2}^{\infty} 2^{-n} \left(\begin{array}{c}n\\s\end{array}\right) (1-2^{-s})^{i-1} \\
&=& 1 - 2^{-n} + \sum_{s=0}^n 2^{-n} \left(\begin{array}{c}n\\s\end{array}\right) (2^s - 1) \\
&=& \frac{3^n - 1}{2^n}.
\end{eqnarray}
For $n=8$, this reduces to
$$
\mathbb{E}(N) = \frac{205}{8} = 25.625.
$$

Enumerative Combinatorics


How Do I Get Total 1 Time for Multiple Rows

Question: I've been asked to modify a report (which unfortunately was written horribly!! not by me!) to include a count of days. Please note the "Days" is not calculated using "StartDate" & "EndDate" below. The problem is, there are multiple rows per record (users want to see the detail for start & enddate), so my total for "Days" are counting for each row. How can I get the total 1 time without the total in column repeating?
This is what the data looks like right now:
ID          Description     startdate   enddate        Days
REA145681   Emergency       11/17/2011  11/19/2011      49
REA145681   Emergency       12/6/2011   12/9/2011       49
REA145681   Emergency       12/10/2011  12/14/2011      49

REA146425   Emergency       11/23/2011  12/8/2011       54
REA146425   Emergency       12/9/2011   12/12/2011      54

I need this:
ID          Description     startdate   enddate        Days
REA145681   Emergency       11/17/2011  11/19/2011      49
REA145681   Emergency       12/6/2011   12/9/2011
REA145681   Emergency       12/10/2011  12/14/2011

REA146425   Emergency       11/23/2011  12/8/2011       54
REA146425   Emergency       12/9/2011   12/12/2011

Help please. This is how the users want to see the data.
Thanks in advance!
Liz
--- Here is the query simplified:
    select id
,description
,startdate     -- users want to see all start dates and enddates
,enddate
,days = datediff(d,Isnull(actualstardate,anticipatedstartdate) ,actualenddate)
    from table

Comment: if you post your current query, it'd be easier for us to edit it. Also, please clarify which Database Engine you are using.
Comment: Hi sorry, am using SQL Server 2008.
Comment: What is the actual table structure? The exiting query that you posted contains columns that don't exist in the data you provided.
Comment: Kevev22 -- table has following fields:  ID, Description, StartDate,EndDate, ActualStartDate, AnticipatedStartDate, ActualEndDate
Answer: As you didn't provide the data of your tables I'll operate over your result as if it was a table. This will result in what you're looking for:
select *,
  case row_number() over (partition by id order by id)
    when 1 then days
  end
from t

Edit:
Looks like you DID added some SQL code. This should be what you're looking for:
select *,
  case row_number() over (partition by id order by id)
    when 1 then
      datediff(d,Isnull(actualstardate,anticipatedstartdate) ,actualenddate)
  end
from t

Comment: Mosty Mostacho!!! THANK YOU!! This worked pefectly!!! Thank you thank you for your help!
Answer: That is a task for the reporting tool. You will have to write something like he next code in teh Display Properties of the Days field:
if RowNumber > 1 AND id = previous_row(id)
  then -- hide the value of Days
       Colour = BackgroundColour
       Days = NULL
       Days = ' '
       Display = false
       ... (anything that works)

Answer: So they want the output to be exactly the same except that they don't want to see the days listed multiple times for each ID value? And they're quite happy to see the ID and Description repeatedly but the Days value annoys them?
That's not really an SQL question. SQL is about which rows, columns and derived values are supposed to be presented in what order and that part seems to be working fine.
Suppressing the redundant occurrences of the Days value is more a matter of using the right tool. I'm not up on the current tools but the last time I was, QMF was very good for this kind of thing. If a column was the basis for a control break, you could, in effect, select an option for that column that told it not to repeat the value of the control break repeatedly. That way, you could keep it from repeating ID, Description AND Days if that's what you wanted. But I don't know if people are still using QMF and I have no idea if you are. And unless the price has come way down, you don't want to go out and buy QMF just to suppress those redundant values.
Other tools might do the same kind of thing but I can't tell you which ones. Perhaps the tool you are using to do your reporting - Crystal Reports or whatever - has that feature. Or not. I think it was called Outlining in QMF but it may have a different name in your tool.
Now, if this report is being generated by an application program, that is a different kettle of Fish. An application could handle that quite nicely. But most people use end-user reporting tools to do this kind of thing to avoid the greater cost involved in writing programs.
We might be able to help further if you specify what tool you are using to generate this report.
Comment: Yes, they want the results exactly like that (which drive me batty because WHY do you need to see the repeating data). I've tried to argue, but no win. I'm using SQL Server 2008 and SSRS for the final ouput. My guess is that they will doing some sort of calculation on the DAYS field, so if they total the field as it is now, they will be definately over counting.


Quando usar tabela de endereços no banco de dados

Question:
Estou desenvolvendo um sistema onde várias entidades terão endereço.
Exemplo: o colégio tem endereço, o aluno tem endereço, a professora tem endereço, os fornecedores tem endereço e etc.
Estou querendo utilizar uma tabela para armazenar todo endereço utilizado no sistema. E então, toda vez que precisar de um endereço, irei me referenciar a ele pelo seu id na tabela de endereço.
Considerando que o sistema não é muito grande, essa seria uma boa forma de se trabalhar com endereços?
O que estava soando ruim, era todas essas entidades ter os campos: cidade, bairro, estado e etc.
Existe alguma melhor implementação da entidade endereço nesse caso?
Comment: http://pt.stackoverflow.com/questions/22069/quando-%C3%A9-interessante-desnormalizar-o-banco-de-dados/22120#22120 Você está fazendo uma sistema para a padaria do seu Manuel ou um Mega Hiper ERP? Isto faz toda a diferença.
Comment: Não chega a ser um HIPER ERP. Mas um ERP em estado inicial. E que não será tão gigante assim.
Comment: Neste caso sim pois é comum irmãos no mesmo colégio e professores terem filhos estudando lá. Endereço como entidade na minha opinião só quando ele for relevante para a aplicação.
Answer: Na minha opinião, a melhor opção é ter uma tabela só de endereços, a qual se relaciona com uma tabela de bairros que se relaciona com uma tabela de cidades e que, finalmente, se relaciona com uma tabela de estados.
Entidades que possuem endereços teriam uma relação n-para-n com a tabela de endereços. Na figura abaixo dá para entender melhor.
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54606/discussion-on-answer-by-rodrigo-rigotti-quando-usar-tabela-de-enderecos-no-banco)
Answer: Você deveria criar uma tabela de pessoas onde cada pessoa tem (alem de seus dados pessoais como nome e documentos pessoais) sua quadra,lote,numero da casa e o nome da rua ou avenida. O bairro seria o id de outra tabela bairros onde dentro da tabela bairros teria o id da cidade do bairro e depois dentro da tabela cidade teria o id do estado da cidade. Assim ficaria mais facil para nao ter dados duplicados porque poderia verificar a quadra, lote, bairro, nome da rua. A pessoa poderia ser qualquer coisa dentro do sistema como fornecedor,cliente,empregado,etc.


Como obter um único valor do banco de dados através do AngularFirestore e mostrar seus dados via Observable?

Question: Esse seria o template

    <form [formGroup]="animalForm" fxLayout="row">
      <mat-form-field>
        <input matInput placeholder="Microchip" formControlName="IdChip" #IdChip>
      </mat-form-field>
      <button mat-icon-button (click)="searchAnimal()" color="accent">
        <mat-icon>search</mat-icon>
      </button>
      <mat-form-field>
        <input matInput placeholder="Tutor" formControlName="Tutor">
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="DataNasc" formControlName="DataNasc">
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Especie" formControlName="Especie">
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Nome" formControlName="Nome">
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Observações" formControlName="Observacoes">
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Raça" formControlName="Raca">
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Tamanho" formControlName="Tamanho">
      </mat-form-field>
    </form>

Esse é o component.ts
import { Component, OnInit } from '@angular/core';
import { AnimaisService } from '../shared/animais.service';
import { MatSnackBar } from '@angular/material';
import { iAnimais } from '../models/animais.model';
import { Observable } from 'rxjs';
import { FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-animais',
  templateUrl: './animais.component.html',
  styleUrls: ['./animais.component.css']
})
export class AnimaisComponent implements OnInit {

  animal$: Observable<iAnimais[]>;

  animalForm = this.fb.group({
    IdChip: ['', [Validators.required]],
    Tutor: ['', [Validators.required]],
    DataNasc: ['', [Validators.required]],
    Especie: ['', [Validators.required]],
    Nome: ['', [Validators.required]],
    Observacoes: ['', [Validators.required]],
    Raca: ['', [Validators.required]],
    Tamanho: ['', [Validators.required]],
    Ocorrencias: ['']
  })

  constructor(
    private fb: FormBuilder,
    private snackBar: MatSnackBar,
    private animaisService: AnimaisService,
  ) { }

  ngOnInit() {

  }

  searchAnimal() {
    this.animal$ =
      this.animaisService.getAnimal(this.animalForm.value.IdChip);
    console.log(this.animal$);
    console.log('Setando formulario')
    this.animalForm.setValue(this.animal$);

  }

E o código que eu utilizo para buscar os dados no Firebase é atráves do serviço é esse:
getAnimal(IdChip: String): Observable<iAnimais[]> {
    return this.afs.collection<iAnimais>('animais',
      ref => ref.limit(1).where('IdChip', '==', IdChip))
      .valueChanges();
}

O que eu consegui identificar é que o getAnimal() está retornando um valor indefinido.
Answer: async searchAnimal() {
    this.animal$ = await
      this.animaisService.getAnimal(this.animalForm.value.IdChip);
    console.log(this.animal$);
    console.log('Setando formulario')
    this.animalForm.setValue(this.animal$);

  }


Why are all openGL objects stored in GLuints?

Question: My best guess is that GLuint holds a pointer rather than the object, and hence it can "hold" any object, because its actually just holding a pointer to a space in memory
But if this is true why do I not need to dereference anything when using these variables?
Comment: These values are *not* pointers, and thus should not be dereferenced. How they are mapped to "objects" in OpenGL is a mystery black box which we don't really need to know about.
Comment: OpenGL is holding "handles" (indexes to internal data structures) in `GLuint`s - they could reference something in the OpenGL driver or on the Video card etc.  They should not be "de-referenced" or otherwise manipulated.  The OpenGL driver knows what these "handles" represent and they should only be passed to the correct API calls.  If you pass them to incorrect API calls then you break the API contract.
Comment: https://en.wikipedia.org/wiki/Handle_(computing)
Comment: Short answer: it is not true.
Answer: OpenGL object names are handles referencing an OpenGL object. They are not "pointers"; they are just a unique identifier which specifies a particular object. The OpenGL implementation, for each object type, has a map between object names and the actual internal object storage.
This dichotomy exists for legacy historical reasons.
The very first OpenGL object type was display lists. You created a number of new display lists using the glNewList function. This function doesn't give you names for objects; you tell it a range of integer names that the implementation will use.
This is the foundational reason for the dichotomy: the user decides what the names are, and the implementation maps from the user-specified name to the implementation-defined data. The only limitation is that you can't use the same name twice.
The display list paradigm was modified slightly for the next OpenGL object type: textures. In the new paradigm, there is a function that allows the implementation to create names for you: glGenTextures. But this function was optional. You could call glBindTexture on any integer you want, and the implementation will, in that moment, create a texture object that maps to that integer name.
As new object types were created, OpenGL kept the texture paradigm for them. They had glGen* functions, but they were optional so that the user could specify whatever names they wanted.
Shader objects were a bit of a departure, as their Create functions don't allow you to pick names. But they still used integers because... API consistency matters even when being inconsistent (note that the extension version of GLSL shader objects used pointers, but the core version decided not to).
Of course, core OpenGL did away with user-provided names entirely. But it couldn't get rid of integer object names as a concept without basically creating a new API. While core OpenGL is a compatibility break, it was designed such that, if you coded your pre-core OpenGL code "correctly", it would still work in core OpenGL. That is, core OpenGL code should also be valid compatibility OpenGL code.
And the path of least resistance for that was to not create a new API, even if it makes the API really silly.


c++ does virtual function always got to be a const?

Question: I just wonder if all virtual function has got to be a const?
I'm having some issue with them as the area always return 0 for my square when ever i wanna print them out. would appreciate if someone could enlighten me.
shapetwod.h
class ShapeTwoD
{
    protected:
        string name, warpSpace;
        bool containsWarpSpace;
    public:
        //constructor
        ShapeTwoD();
        ShapeTwoD(string, bool);

        //accessors/set function
        void setName(string);

        //mutator/get function
        string getName();

        //methods
        virtual double computeArea();
        virtual void view();
};

shapetwod.cpp
ShapeTwoD::ShapeTwoD()
{
    string name = "";
}

ShapeTwoD::ShapeTwoD(string ShapeName)
{
    name = ShapeName;
}

void ShapeTwoD::setName(string shapeName)
{
    name=shapeName;
}

string ShapeTwoD::getName()
{
    return name;
}

double ShapeTwoD::computeArea()
{
    return 0;
}

void ShapeTwoD::view()
{
    cout << "Area is: " << endl;
}

square.h
class Square:public ShapeTwoD
{
    private:

        int xVal,yVal;
        int length, breath;
        double area;

    public:

        Square();
        Square(string, int, int, double);

        //acessor method
        //int getSquareDetails();
        int getxCord();
        int getyCord();
        double getArea();

        virtual double computeArea();
        void view();

        int xvalue[4];
        int yvalue[4];

};

square.cpp
Square::Square()
{
    xVal = 0;
    yVal = 0;
    area = 0;
}

Square::Square(string ShapeName, bool warpspace, int xval, int yval, double areas):ShapeTwoD(ShapeName, warpspace)
{
    xVal = xval;
    yVal = yval;
    area = areas;
}

void Square::setSquareCord()
{
    for (int i=0; i<4; i++)
    {
        cout << "Please enter x-ordinate of pt " << i+1 << ": ";
        cin >> xVal;
        xvalue[i] = xVal;

        cout << endl;

        cout << "Please enter y-ordinate of pt " << i+1 << ": ";
        cin >> yVal;
        yvalue[i] = yVal;
        cout << endl;
    }
}

double Square::computeArea()
{
    int xmax = xvalue[1];
    int xmin = xvalue[1];

    int ymax = yvalue[1];
    int ymin = yvalue[1];

    for(int i=0; i<4; i++)
    {
        if(xvalue[i]>xmax)
        {
            xmax = xvalue[i];
        }
        else if(xvalue[i]<xmin)
        {
            xmin = xvalue[i];
        }
    }

    for(int i=0; i<4; i++)
    {
        if(yvalue[i]>ymax)
        {
            ymax = yvalue[i];
        }
        else if(yvalue[i]<ymin)
        {
            ymin = yvalue[i];
        }
    }
    length = xmax - xmin;
    breath = ymax - ymin;

    area = length * breath;
    return (area);
}

int Square::getxCord()
{
    return xVal;
}

int Square::getyCord()
{
    return yVal;
}

double Square::getArea()
{
    return area;
}

void Square::view()
{
    cout << "Name: " << getName() << endl;
    cout << "Area is: " << area << endl;
}

Sorry but I don't really know how to phase my question. i'm actually using Polymorphism &
Virtual Functions here and my computeArea and view function are virtual.
so in my square.cpp under the "view" function the programme would always return me 0 and i'm not sure why is this so..
this is how i call the view function. not sure if it's helping here..
void Shape2DLink::InputSensor()
{
    string shape,type;

    cout<<endl<<"\n"<<"[ Input sensor data ]"<<endl;

    cout << "Please enter name of shape: " << endl;
        cin >> shape;
        shape2D.setName(shape);

    cout << "Please enter special type : " << endl;
        cin >> type;
        shape2D.setWarpSpace(type);

    if(shape == "Square")
    {
            square.setSquareCord();
            square.computeArea();
            square.isPointOnShape();
            square.isPointInShape();
            Square *mySquare = new Square;
            shapeobject.push_back(mySquare);
            //shapeobject.push_back( new Square );
    }
}
void Shape2DLink::Display()
{
    vector<ShapeTwoD*>::iterator vectorIt = shapeobject.begin();
    while(vectorIt != shapeobject.end())
    {
        (*vectorIt)->view();
        vectorIt++;
    }
}

Comment: I'm sure all the code you included is essential to your question.
Comment: I'm guessing you are not using pointers, but you need to show where/how you are calling `getArea` and `computeArea`.
Comment: @DanielDaranas sorry, i'm just wondering why my square area always returns me a 0..
Comment: You're missing the most important code, where you actually create and object and call its functions.
Comment: Maybe you can tell us *what* issues you have, instead of posting code that's probably not relevant. If we need to see more code we will ask you for it.
Comment: What a manual (!) code bloat!
Comment: @user2900611 Aha. That explains everything.
Answer:
I just wonder if all virtual function has got to be a const?

No.

I'm having some issue with them as the area always return 0 for my
  square when ever i wanna print them out.

Hmm, ok, let's take a look.
double ShapeTwoD::computeArea()
{
    return 0;
}

Yup, uh-huh.

I've got my Magic Monkey Hat on, and I predict that the problem you're having is caused by Object Slicing.  Consider:
void foo (Shape2D shape)
{
  cout << shape.compute_area() << "\n"
}

int main()
{
  Square sq;
  foo (sq);
}

Since foo above takes a Shape2D by-value, all the Squareness of whatever is passed to it is sliced away, leaving only a Shape2D.  Of course since Shape2D::compute_area just returns 0, that's what is computed.
To fix this particular problem, don't copy the object or take it by-value, but take it by-reference instead:
void foo (Shape2D& shape)
{
  cout << shape.compute_area() << "\n"
}

Now the object isn't sliced.
Look for similar problems in the code you haven't shown us.
Answer: No a virtual method may or may not be const. Your problem is somewhere else, but not in the code you have included.


I am setting a cookie's expiration time 10 mins which is working fine in local system but on server, it's not working

Question: I am setting a cookie's expiration time 10 mins which is working fine in local system but on server, it's not working.
Comment: its not working at all ? or its not keep 10min ? If its not working at all check the cookies settings on web.config and make sure for the correct domain value
Comment: Can you show relevant parts of your code? Are you setting the cookie manually? web.config?
Answer: have u check global IIS setting?
if u set your app to be more than global setting, then the setting will not effect.
Comment: I have checked global IIS setting which is fine, Can you tel me some other solution.Vinay
Answer: Did you try this ASP.NET cookie expiration time is always 1/1/0001 12:00 AM


Finding $P_{\theta}(X_1 + X_2 > X_3)$ when $X_1, X_2, X_3 \stackrel{\text{i.i.d.}}{\sim} Bernoulli(\theta)$

Question: I know that $P_{\theta}(X_1 + X_2 > X_3) = 1 - P_{\theta}(X_1 + X_2 < X_3),$ but how do I find $P_{\theta}(X_1 + X_2 < X_3)$ when the right hand side of the inequality is a random variable?
Comment: In general, you can move the random variable on the right to the left hand side, and then find another random variable such that it is equivalent in distribution to the combination of three random variables that you'll have on the left hand side. Then calculate the probability this random variable is $<0$
Comment: After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark $\checkmark$ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/), [What should I do if someone answers my question?](https://math.stackexchange.com/help/someone-answers).
Answer: So, they all are Bernoulli, so they take value in $\{0,1\}$. For us, that means $X_1+X_2 > X_3$ if, and only if,

$X_3 = 1$ and $X_1=X_2=1$; or
$X_3=0$ and not both $X_1$ and $X_2$ are $0$.

Since they are all independent, we have
$$
\mathbb{P}\{X_3 = 1,  X_1=X_2=1\}
= \mathbb{P}\{X_3 = 1\}\cdot\mathbb{P}\{X_1=1\}\cdot\mathbb{P}\{X_2=1\}
= \theta^3
$$
and
$$\begin{align*}
\mathbb{P}\{X_3 = 0,  X_1+X_2\geq 1\}
&= \mathbb{P}\{X_3 = 0\}\cdot(1-\mathbb{P}\{X_1=X_2=0\})\\
&= \mathbb{P}\{X_3 = 0\}\cdot(1-\mathbb{P}\{X_1=0\}\mathbb{P}\{X_2=0\})\\
&= (1-\theta)\cdot(1-(1-\theta)^2)
\end{align*}$$
and therefore, since both events are disjoint,
$$\begin{align*}
\mathbb{P}\{X_1+X_2> X_3\}  &= \mathbb{P}\{X_3 = 1,  X_1=X_2=1\} + \mathbb{P}\{X_3 = 0,  X_1+X_2\geq 1\}\\
&= \boxed{\theta^3 + (1-\theta)\cdot(1-(1-\theta)^2)}
\end{align*}$$
which you may then simplify a bit if you want.
Comment: Fixed (that was literally changing two characters, and doesn't affect the result nor derivation). Thanks, @StubbornAtom, for catching that.
Comment: Don't we also have $X_3=0$ and $X_1=X_2=1$ or did you include this part?
Comment: It's included in the second. If they are both 1, then in particular "they are not both 0", @StubbornAtom. But you are right, I wrote the wrong expression for that somewhere after (just an which should be a $\geq$)
Answer: For Bernoulli I would write out all the possibilities (there's 8 of them) and from there conclude the probability is equal to $\theta^2 + 2\theta(1-\theta)^2$. For other distrubutions and in general, Slades comment is the better approach.


Hiding Field(s) if Date is Expired

Question: I'm using Drupal 7 date field. Using views, when the date has expired, the page goes to a section labeled 'past events.' In the template page, the date and time are both separated for instance. $date_output and $time_output. I need to hide the time field after the date has expired. any ideas?
Comment: You probably need to explain this a little more. Is there any specific reason why you can't compare with the current date and hide the date/time fields?
Comment: thats what I'm looking for apparently. How to do the compare. I've followed a few tuts but not seem to work.
Comment: Can you show us the template page you are referring in the question?
Answer: If your date is in one of the supported date/time formats, you can use strtotime() and date() to compare.  Wrap the printing of $time_output in an if statement.  For example:
<code>if ( strtotime($date_output) > date() ) {
  // $date_output is greater than now, eg, not expired
  print($time_output);
}
</code>
If $date_output is already a timestamp, no need to use strtotime()
Comment: ok. figured it out. thought i'd share.     date('U') ):?>

Time
Comment: Ok so this is what I'm working with. The 'time' div should be hidden if the date has past. This is what I have.  Trying to see if this works also. I want to show my div based on a date expiration. Here is what I have

Time
";
    } else {
      echo "";
    }  ?>
Comment: include in your existing if statement, so it shows as:
if (isset($_POST['org']) && $_POST['org'] == "yes" && strtotime($date_output) > date()) {
Comment: Or do you mean to say that $date_output is not available in the script rendering $time_output? In that case, is this your time field template? The template should have access to the node or entity containing the date field, you may have to check that to get the date output value.
Comment: its all relative to the date. if the date has past, then the time shouldnt show.
Comment: hence using the date in your if statement.  does the script you posted, that prints $time_output, have access to $date_output?

Hiding Field(s) if Date is Expired


Help me prove CLT $\implies$ error term in OLS regression is distributed normally

Question: How can I prove that the central limit theorem implies that error term in an OLS regression is normally distributed? (A statement to this effect has been mentioned in Econometrics p. 33 by Fumio Hayashi (2000)).
Comment: Under what assumptions about the regression and error term?
Comment: Are the regressors fixed or random?  If random, what do you assume about their distribution?
Comment: Thank you @Dave. The assumptions are: 1.)  linearity of regression in dep. var; 2.) strict exogeneity of regressors; 3.) no multicollinearity; 4.) homoskedasticity; 5.) no correlation between observations.
Comment: The regressors (X) are assumed to be random. Hayashi mentions that no particular distribution needs to be specified for X, especially for hypothesis testing if conditional distribution of error term conditional on X is normal.
Answer: The linear regression model may be written as
$$
y_i=x_i'\beta+u_i
$$
The reference says

In many applications, the error term consists of many miscellaneous
  factors not captured by the regressors. The Central Limit Theorem
  suggests that the error term has a normal distribution.

So, Hayashi asks why $u_i$ ought to be assumed to be normally distributed.
In my understanding, the logic goes as follows:
The error term $u_i$ captures all influences on $y_i$ that are not already accounted for by the regressors $x_i$. Now, you could think of a great many influences that have not been accounted for. Ideally, the important influences have already been included via the regressors, so that $u_i$ captures "unimportant" factors. The CLT roughly says that a suitably scaled average of many small factors behaves like a normal random variables. So, $u_i$, collecting these factors, would be normally distributed.
Personally, I do not find this logic to be too appealing, though. First, we do not need this normality assumption on the errors once we (as does Hayashi later on, see also the second quotation below) resort to asymptotic approximations (as $n\to\infty$), which is pretty much all we can do once we leave this fairly restrictive setup of the linear model anyhow.
Second, I believe the error term $u_i$ is just the error associated with person/observation $i$, and there is exactly one error for that observation. To me, it is quite a stretch of the imagination to interpret that single error as the average of infinitely many "sub-errors" that would justify a CLT. (Letting $n\to\infty$ is far more plausible to me, as we can conceivably collect more data, though.)
Third (also see below), it is unclear why that logic should be applicable in the practically very relevant case of omitted variables (i.e., important factors being left in the error term).
Indeed, in Chapter 2, Hayashi writes

However, not very often in economics are the assumptions of the exact
  distribution satisfied. The finite-sample theory breaks down if one of
  the following three assumptions is violated: (1) the exogeneity of
  regressors, (2) the normality of the error term (my emphasis), and (3) the linearity
  of the regression equation.
Comment: So, in any case, I would argue that there is no such thing as a proof of the statement in the title of your question. I'd rather think of it as a somewhat heuristic justifcation of an assumption.
Comment: Yes, I did not ask for or provide a proof, and your explanation in your first comment above has clarified my doubt on an intuitive level (wish my reputation allowed giving +1). Btw, I think $\sum_{j=1}^m\epsilon_j \sim N(\mu,\sigma^2)$, and not $N(m\mu,m\sigma^2)$.
Comment: I agree with your explanation of CLT, but am still left wondering how $u_i$ would be normally distributed, given that it is generally not scaled (or am I wrong here?). Thank you for filling the gaps for me.
Comment: Since it is not really clear what is being averaged over here (viz. unobserved and presumably "unimportant" factors), it is indeed (at least to me) also not clear if these things are scaled or not. To an extent, that question is maybe a little moot if one is willing to refer to the approximative implication of the CLT that the *sum* of r.v.s $\epsilon_j\sim (\mu,\sigma^2)$, $\sum_{j=1}^m\epsilon_j$, then is $N(m\mu,m\sigma^2)$.
Comment: Actually, if each r.v. has mean $\mu$, then their sum has $m$ times that mean. Think tossing $m$ dice with expectation 3.5 each, and similarly for the variance of the sum of (additionally, uncorrelated) r.v.s.
Comment: Sorry, my bad! I was actually thinking "summation" but imagining "mean". Got it now!
Answer: There is no such thing as proof that the error term in OLS regression is normally distributed as it's an assumption. It just needs to be stated when we want to test for statistical significance of the $\beta$'s. In fact, the Gauss-Markov theorem doesn't even mention normality of the error term.
What we can do, however, is to conduct model diagnostics (likea q-q plot) in order to verify that such assumption holds.


How to map XML to POJO

Question: I have the following result:
<Result xmlns="urn:buscape" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" totalResultsAvailable="1" totalResultsReturned="1" totalPages="1" page="1" totalLooseOffers="0" xsi:schemaLocation="http://developer.buscape.com/admin/lomadee.xsd">

    <applicationID>999999999999999</applicationID>
    <applicationVersion>1.0</applicationVersion>
    <applicationPath/>
    <date>2016-09-12T23:50:19.722-03:00</date>
    <elapsedTime>19</elapsedTime>
    <status>success</status>
    0
    <message>success</message>

  <lomadeeLinks>
    <lomadeeLink>
      <id>1</id>
      <originalLink>link</originalLink>
      <redirectLink>link2</redirectLink>
      0
      </lomadeeLink>
  </lomadeeLinks>
</Result>

Looking at "2.7.4 Retrieving XML data via HTTP GET", I have to map this XML to POJO-like object in Java, here is the question, I can't find the @Root and @Element annotation and I'm not sure how to correctly map the XML into a Java object.
Comment: 2.2.4 Object to XML Marshaling:
Object to XML marshaling in Spring for Android RestTemplate requires the use of a third party XML mapping library. The Simple XML serializer is used to provide this marshaling functionality.
Comment: It already answered. Please find the below [link](http://stackoverflow.com/questions/15881876/mapping-xml-entities-to-java-objects)
Answer: If you are using spring/springboot then simply you can use
    (YourPOJO)getWebServiceTemplate().marshalSendAndReceive(yourSOAPService);
POJO :-
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "getOrdersResponse"
})
@XmlRootElement(name = "nameOfTag", namespace = "http://example.org/yourResource")
public class GetOrdersByDateResult {
@XmlElement(name = "GetOrdersResponse")
protected GetOrdersResponseType getOrdersResponse;

getter();
setter();

}

How to map XML to POJO


How to get response from Jquery Ajax

Question: I wanna get the response result from ajax request, when I click a button with value "Accept" to send server.
Thank you for help.
I get the error 419 POST http://localhost:8000/posts/list_post_ajax 419 (unknown status)

View:

            Post ID
            User ID
            Name User
            Title
            Content
            Datetime
            Status
            Accept

            @foreach ($posts as $row)

post_id }}">
                {{$row->post_id}}
                {{$row->user_id}}
                {{$row->users->name}}
                {{$row->post_title}}
                {{$row->post_content}}
                {{$row->post_datetime}}
                {{$row->post_status}}

                <button class="btn btn-success accept-btn" data-postID="{{$row->post_id}}">Accept</button>

            @endforeach

Script:

-- Route:
Route::post('/list_post_ajax','PostController@list_post_ajax')->name('posts.list_post_ajax');

Controller:

public function list_post_ajax()
    {
       return response()->json('success');
    }

Comment: You get error 419 because you send a request without csrf token to an url that is protected by csrf.
Comment: Possible duplicate of [Laravel 5.5 ajax call 419 (unknown status)](https://stackoverflow.com/questions/46466167/laravel-5-5-ajax-call-419-unknown-status)
Comment: Yes, I have fixed that problem. Thank you so much
Answer: You need to send CSRF token in your post request. So set up the ajax fist like:
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

And Send the Request now
    $.ajax({
        type: "POST",
        url: "{{route('posts.list_post_ajax')}}",
        data: { postId: postId },
        dataType: 'JSON',
        success :function(response) {
            alert("thank u");
        },
    });

Set the meta tag in your
<meta name="csrf-token" content="{{ csrf_token() }}">

Comment: Yes, I have fixed that problem. Thank you so much
Answer: send also the token
data : {postId:postId,_token:'{{ csrf_token() }}' }
Comment: Yes, I have fixed that problem. Thank you so much
Answer: You are missing csrf-token.
You can read about it here: https://laravel.com/docs/5.8/csrf
Long story short: you have 3 ways of solving this:
1. Fix it globally:
Add this to your ajax setup (so it's executed on every page in your project):
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

and add this to your main layout:
<meta name="csrf-token" content="{{ csrf_token() }}" />
and you will have that ready on every request from now on..
2. fix it just for current endpoint:
add _token to payload of your request:
data: {
        "_token": "{{ csrf_token() }}",
        "id": id
}

3. or exclude your route from the middleware that is blocking it (it's probably VerifyCSRF):
protected $except = [
        'route/*',
    ];

Comment: Yes, I have fixed that problem. Thank you so much

How to get response from Jquery Ajax


there are at most finitely many points

Question: I have the formula $\frac{2a_{i}}{a^{2}_{i}+1}=-b_{i}$ and I want to show that $|a_{i}|=1$ only when $|b_{i}|\geq1$ which is easy to prove but my question is how I can prove the statement " there are at most finitely many $|a_{i}|=1$ ?"
I appreciate any help..
Comment: In your heading, is "infinitely" a typo for "finitely"?
Comment: @bof: The title is the only reason I clicked on this, so maybe this was intentional to get more people to look at the question. I suspect that was not the case here, but it got me to wonder whether anyone has actually tried something like that in Stack Exchange.
Comment: Is $a_i$ a real number? In that case the only $a_i$ that fulfill the condition are $a_i = \pm 1$, which is a finite set.
Comment: how about if they are complex?
Comment: You have a degree 2 polynomial in $a_i$ : b_ia_i^2+2a_i+b_i$ which has a finite number (actually 2) of roots.
Comment: but if we have an inequality then we are not restricted to only two roots :)
Comment: sorry I should correct the title it is my mistake the correct is "finitely" ..\
Comment: Yeah, but what's the difference between "finitely many" and "at most finitely many"? Is there such a thing as "less than finitely many"?
Answer: You have a degree 2 polynomial in $a_i$ : b_ia_i^2+2a_i+b_i$ which has a finite number (actually 2) of roots.

there are at most finitely many points


jquery offset method doesn't always work / exist

Question: Good morning and happy new year everyone!
I've run into a snag on something and need to figure out a solution or an alternative, and I don't know how to approach this. I actually hope it's something easy; meaning one of you all have dealt with this already.
The problem is that I'm doing rollovers that contain information. They're divs that get moved to the absolute location. Now I've tried this with jquery 1.6 - 1.9.1. Of course this has to work in multiple browsers.
What needs to happen is on rollover show a div, and when you rollout of that div, make it hide.
...
// .columnItem is class level and works
$(".columnItem").mouseleave(function() {
    $(this).css("display", "none");
});
...

$(".column").mouseenter(function() {
    var currentItem = $(this)[0]; // this is where the problem is

    // hide all .columnItems
    $(".columnItem").css("display", "none");

    // i get this error: Object #<HTMLDivElement> has no method 'offset' (viewing in chrome console)
    var offsetTop = currentItem.offset().top;

    var columnInfoPanel = $("#column" + currentItem.innerText);
});

So the immediate thought of some would be don't use $(this)[0]. Instead, I should use $(this), and you are correct! Where the other problem comes into play is by removing the array index, currentItem.innerText is now undefined.
The only thing I can think of is I'll have to mix both, but it seems like there should be a way to use the selector and get both options.
What have you all done?
Thanks,
Kelly
Answer: Skip the [0] at the beginning as you are saying.
But then change the last line to:
 var columnInfoPanel = $("#column" + currentItem[0].innerText);

De-referencing the jQuery selector gives you the DOM-object.
If you want to stick to pure jQuery, the .text() / .html() methods will give you the same functionality.
Answer: Replace:
var currentItem = $(this)[0];

With:
var currentItem = $(this).eq(0);

This creates a new jQuery object containing only the first element, so offset will work.
Then you can use either currentItem[0].innerText or currentItem.text(), whichever you prefer.
Comment: Thanks for telling me about that, I really appreciate it. I had no idea about the `eq()` method. Also I changed to call `text()` to keep things common.


I added this into my product.custom.liquid (section)

Question: {% comment %} File upload {% endcomment %}
 Logo
        {% comment %} input {% endcomment %}

          Nom de votre établissement sur Google
          <input required type="text" id="custom_business_name" name="properties[Nom du business]" data-type="add-to-cart-form" />

But the line items are not displaying in the cart when I add line-items
Answer: Make sure your code between the <form> and </form> tags [product form].
For more you can checkout this reference
https://ui-elements-generator.myshopify.com/pages/line-item-property


Create 2 separated taxonomy pages with views

Question: I have 2 nodes type "Article" and "Page", I also have 2 taxonomy for each node type are "Taxo 1" for Article and taxo 2 for "Page", is there any way to create 2 seperated views so,
<code>with "taxonomy/term/%" for Article I have grid views
</code>
and
<code>"taxonomy/term/%" for "Page" I have "Unformated List",
</code>
beside 2 node types have alot of different fields.
Is there any way to handle that?
Answer: Your template file name should be like this -> taxonomy-term--tid.tpl.php
Source
Answer: I really appreciate the Taxonomy Views Integrator module for things like that. https://www.drupal.org/project/tvi


increase Memory Translation Table (MTT) for mellanox Connect-IB card

Question: I have a fat node which has 2TB memory. With the new Connect-IB card, I want to increase the MTT, so I could register a large memory region. I found this post for HowTo Increase Memory Size used by Mellanox Adapters , but it didn't mention how to increase that for Connect-IB. Could anyone give me any suggestion?
Comment: Did you try allocating memory with 1 GB hugepages and then registering it? I am not sure if this will help, though.
Comment: As far as I know the Connect-IB driver doesn't have a similar feature. You should try @AnujKalia's suggestion.
Answer: You did not specify the OS, however the Connect-X recipe you pointed to is linux specific, so I assume we are speaking about linux openib stack.
AFAIK, Connect-IB driver allocates memory from the kernel for MTT and other cashes dynamically.
(See drivers/net/ethernet/mellanox/mlx5/core/pagealloc.c and uses of public functions defined in this module by other drivers/net/ethernet/mellanox/mlx5/core/* modules)


Herdar módulos e variáveis de inicialização em um script Python para outro script Python com Gtk3

Question: Boa Noite!
Estou trabalhando com Gtk3 e Python3 e estou estruturando meu projeto para construção de um ERP para plataforma GNU/LINUX. Estou utilizando o Glade para construção da interface gráfica e utilizando o Builder do Gtk para manipular os componentes da interface gráfica. No exemplo abaixo eu pretendi exemplificar minha ideia de forma bem genérica com dois aquivos .py um para cada janela, pois os quero estruturar o meu projeto em módulos separados aonde eu possa chamar um de cada vez para não sobrecarregar as máquinas aonde ele vai rodar, sempre levando em conta que eu preciso construir um sistema leve para maquinas que já estão ultrapassadas :(.
Arquivo 1 (Janela 1) :
<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import gi
import base64
import zlib
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

ui = Gtk.Builder()
ui.add_from_string(zlib.decompress(base64.b64decode(b'eJyNksFSwjAQhu88xbpXp0D14qGtM86IL6DjsbNNFhpZE0xSkEfyOXwxgxUBYdRbJvn23/33T3H9+iywZB+MsyXmwzECW+W0sbMSH+4n2RVeV4PiLMvgji17iqxhZWILMyHNcDm8uBjmkGUJMjayn5LiagBQeH7pjOcAYpoSZ3F+jrtGqWyMo0/ONU+sIiihEEq8i/NHY7VbIRhd4hNZFspxQyZ24d2CfVyDpWcuUZGtp051AasJSeBitAW++GBmluSL1hyid2uElqwW9iWSqwMZX/dd6hwhrGix4NTYun68JKJaI7o/b0aQZLB1otlvgdEe8YM+MnfTxehsb66J9aG/Ux6FGhaE6MkGoUiNpMs1J8u3IRK8vwFBrwL5T/+n9JYmmKSB1b3vjhb2x5L/W+JZsVlyqDVPqZP4S+VBQkqMmrPeS2hz47rvNZ3KZxNAv+ajOHYPxWjvc34Ayi/vWQ==')).decode("utf-8"))

class Janela1(object):

    def __init__(self, *args, **kwargs):
        super(Handler, self).__init__(*args, **kwargs)
    # --> Inicialização
        self.usuario = "TESTE" # --> Gostaria de herdar a variável de inicialização dessa janela1 para janela2

    # -- ao sair da janela1 destroy a aplicação
    def ao_sair_janela_1(self, *args):
        Gtk.main_quit()

    # -- Ao clicar no botão da janela1 é impresso na saida padrão a
    # -- mensagem e posteriormente chamo a janela2
    def clicou_janela1(self, *args):
        print("Clicou janela 1")

        import janela2 as janela #--> Aqui importo o script da janela2 e apelido de "janela"
        janela.execucao(classe=janela.Janela2) #--> Chamo minha função na janela2 aonde ligo os sinais
                                               #--> da janela e crio um loop do Gtk para segunda Janela

ui.connect_signals(Janela1())
window = ui.get_object("janela1")
window.show_all()

if __name__ == '__main__':
    Gtk.main()
</code>
Arquivo 2 (Janela 2):
<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import gi
import os
import base64
import zlib
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
ui = Gtk.Builder()
# --> (Dúvida: da linha 4 a 10 não queria importar esses módulos novamente,
# --> gostaria de herdar eles da primeira janela)

# --> Arquivo da janela2
def modulo(string=b'eJyNkk1SAjEQhfecou2tNfy5cTEDVVYJF8BySfUkDQSaBJMMyJE8hxczOFCgQ6G7VPK9/nkv+fB9LbBlH4yzBfbaXQS2ymlj5wW+TEbZIw4Hrfwuy2DMlj1F1rAzcQFzIc3w0O732z3IsgQZG9nPSPGgBZB7fquM5wBiygLncXWP50ZJ1sXON+fKJasISiiEAsdx9WqsdjsEowtckmWhPh7IxG6827CPe7C05gIV2enMqSrgYEQSOO+cgOv82mkSHEx81USDmVuSI6g5RO/2CAuyWtgXSG4ayPjpaSAIO9psOI1oXb1IqqEWRnR9PjSXZMXCiWZ/AjoXxC+6YcNTFaOztQ1lPDbu4UnQ3E6oZEGInmwQilRKutxzMuc5RILPDyCoq0D/9/rX6m1NMKnGdb/+iOO/Es+KzZbDVPOMKok3lD8CUmLUivVFQIcbV93M5xBAbXMjjvND3rn4xl9Nhv2k'):
    return string

# --> Conexão dos sinais e criação do Loop para janela
def execucao(classe=None):
    ui.connect_signals(classe())
    Gtk.main()

class Janela2(object):
    def __init__(self, interface=modulo(), *args, **kwargs):
        ui.add_from_string(zlib.decompress(base64.b64decode(interface)).decode("utf-8"))
        super(Janela2, self).__init__(*args, **kwargs)
    # --> Inicialização
        self.janela2 = ui.get_object("janela2")
        self.janela2.show_all()

    # -- Fecha a janela2
    def ao_sair_janela2(self, *args):
        Gtk.main_quit()

    # -- Exibe a mensagem quando clicado no botão da janela2
    def clicou_janela2(self, *args):
        print("Clicou na janela 2")
</code>
Minha dúvida é mesmo como herdar os os módulos já importados na janela1 para  janela2, assim como as variáveis de inicialização da janela1 para janela2
Se alguém puder me dar uma força agradeço!
Valeu!
Answer: Especificamente sobre a sua dúvida:
Se o seu programa tem varias vezes o mesmo import em arquivos .py diferentes,
o Python não carrega  outras cópias do módulo importado. Apenas o primeiro import traz o código para a memória. Outras importações de "zlib" ou "base64", pra falar desse exemplo, somente criam variáveis novas, no ponto onde está o comando de 'import', referenciando o mesmo objeto na memória.
Agora, alguns comentários sobre a sua arquitetura:
Ter o código para 1 ou 20 janelas em uma única aplicação Python não vai "aumentar o peso" do seu sistema  - não se preocupe com isso: o código usado pela pilha sistema Operacional, + ambietne gráfico + conectores de banco de dados + runtime do Python deve precisar de entre 600 e 800MB pra funcionar. Cada módulo do seu sistema, mesmo se for bastante complexo, vai usar de memória o equivalente ao que a descrição do módulo em código fonte usa  - ou seja, mesmo um arquivo muito complexo dificilmente vai passar dos 100KB de "peso" extra.
Você só consegue "gastar memória" de forma significativa se tentar, por exemplo, carregar o movimento de caixa de vários dias de operação em memória, e ficar operando com isso.
Resumo até aqui: você não precisa dividir sua aplicação por "questão de performance" - você pode dividir os módulos para se preocupar com manter o sistema organizado e mantível. Se isso for aumentar a complexidade, você está indo na contramão.
Agora-a forma como vocẽ optou por manter a interface gerada pelo glade
no seu sistema também não é prática: você tem essencialmente
código compilado dentro dos seus arquivos de código fonte -
o ideal é manter os arquivos XML em uma pasta, próximos dos seus arquivos .py
mesmo, e carregar de um arquivo.
O "ganho de performance" de ter a descrição da interface numa string
base-64 encode, zipada, embutida no seu código fonte é
negligível - isso se houver qualquer ganho,e é muito possível
que não. Por outro lado, você perde muito, mas muito mesmo, em
o quanto fica fácil manter o seu código: qualquer mudança na interface você
tem que usar o glade, gerar a string com a interface,e "colar" ela dentro
do seu código fonte do app. é muito mais simples se os arquivos que
o glade gera ficarem no sistema de arquivos direto -- você altera o que precisa
e seu arquivo .py continua funcionando sem precisar de nenhuma alteração.
Se você quer entregar um único arquivo para o usuário final, depois vendo sobre
empacotamento, você vai ver que pode criar um arquivo ".egg" ou ".wheel" que contém o seu código junto com os xml e pode ser usado de forma direta - embora
idealmente voĉe mnta as coisas de forma que em cada máquina é executado um "pip install"  do seu projeto - e isso já copia todos os arquivos necessários para sua execução na instalação de Python onde foi feito o comando "pip".
--
Ultima dica: você está chamando "gtk.main()" em mais de um ponto - isso não está certo - gtk.main deve ser chamado uma única vez na aplicação - você pode esconder uma janela e apresentar outra, com chamadas por dentro do gtk.
Comment: Boa Tarde jsbueno!
Comment: obrigado por responder acredito que estou no caminho certo então, estava com um pouco de receio de ficar importando módulos para cada janela e causar um problema de excesso de memória usada.
Comment: A respeito do gtk.main() irei restruturar o processo e qualquer dúvida volto a perguntar.
Comment: agora a respeito de variáveis de inicialização por exemplo quando eu chamar um novo módulo quero passar para ele algumas informações, exemplo o usuário que chamou este módulo entre outras coisas, quando estou trabalhando em um projeto que existe um único arquivo do Glade eu utilizo somente chamadas do Gtk para as janelas agora quando eu parti para uma estruturação separadas em módulos tive essa dúvida, e acabei montando essa gambiarra para funcionar em parte.
Comment: Não sei se existe algum conteúdo que aborde essa questão em especifico, utilizando Python ou C para que eu possa estudar.
Comment: você não pode passar variáveis paa "módulos'  -mas já que está definidno suas janela sem classes - sim, quando você cria uma classe, pode passar parâmetros, que viram parametros no métod 'init" - e esses parâmetros podem ser controles gtk na primeira janela, onde métodos da segunda janela podem ler os valores, por exemplo  - não precisam ser valores congelados.
Answer: Boa Noite Pessoal!
Acredito ter chegado a um modelo funcional para resolução do meu problema, queria somente a orientações de vocês se estou no caminho certo.
As modificações que realizei foi que ao invés de utilizar o add_from_string do Gtk.Builder eu passei a utilizar o add_from_objects_string pois ele se aptou melhor ao meu modelo de estruturação do projeto. Também consertei o problema de ter que criar um novo loop do Gtk.main() para construção da segunda janela, agora como o amigo @jsbueno orientou eu faço chamadas somente do Gtk, e as propriedades que preciso herdar na segunda janela viraram parâmetros de classe da mesma. Abaixo segue os dois arquivos que realizei as modificações:
Arquivo 1 (Janela1):
<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import gi
import base64
import zlib
import sqlite3

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

ui = Gtk.Builder()
janela1 = (zlib.decompress(base64.b64decode(b'eJyNksFSwjAQhu88xbpXp0D14qGtM86IL6DjsbNNFhpZE0xSkEfyOXwxgxUBYdRbJvn23/33T3H9+iywZB+MsyXmwzECW+W0sbMSH+4n2RVeV4PiLMvgji17iqxhZWILMyHNcDm8uBjmkGUJMjayn5LiagBQeH7pjOcAYpoSZ3F+jrtGqWyMo0/ONU+sIiihEEq8i/NHY7VbIRhd4hNZFspxQyZ24d2CfVyDpWcuUZGtp051AasJSeBitAW++GBmluSL1hyid2uElqwW9iWSqwMZX/dd6hwhrGix4NTYun68JKJaI7o/b0aQZLB1otlvgdEe8YM+MnfTxehsb66J9aG/Ux6FGhaE6MkGoUiNpMs1J8u3IRK8vwFBrwL5T/+n9JYmmKSB1b3vjhb2x5L/W+JZsVlyqDVPqZP4S+VBQkqMmrPeS2hz47rvNZ3KZxNAv+ajOHYPxWjvc34Ayi/vWQ==')).decode("utf-8"))
ui.add_objects_from_string(janela1, ["janela1"])

class Handler(object):
    def __init__(self, *args, **kwargs):
        super(Handler, self).__init__(*args, **kwargs)
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # --> Inicialização
        self.window = ui.get_object("janela1")
        self.window.show_all()

        self.conexao = sqlite3.connect("banco.db")
        self.cursor = self.conexao.cursor()

    def ao_sair_janela_1(self, *args):
        Gtk.main_quit()

    # -- Sinal conectado a um GtkButton
    def clicou_janela1(self, *args):
        print("Clicou janela 1")
        from janela2 import Janela2
        Janela2(construtor=ui, conexao=self.conexao, cursor=self.cursor)

ui.connect_signals(Handler())
if __name__ == '__main__':
    Gtk.main()
</code>
Arquivo 2 (Janela2):
<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import gi
import base64
import zlib

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk

janela2 = (zlib.decompress(base64.b64decode(b'eJyNkk1uAjEMhfecwvW2Gv666WIGpEqFC1B1iTyJgYBJaJKBcqSeoxdr6ICgHUS7i5zvOfZ7yYfva4Et+2CcLbDX7iKwVU4bOy/wZTLKHnE4aOV3WQZjtuwpsoadiQuYC2mGh3a/3+5BliXI2Mh+RooHLYDc81tlPAcQUxY4j6t7PD+UZF3sfHOuXLKKoIRCKHAcV6/GardDMLrAJVkW6uOBTOzGuw37uAdLay5QkZ3OnKoCDkYkgfPOCbjOr50mwcHEV000mLklOYKahSNnvGUbERZktbAvkNw0kPHT01QQdrTZcJrTunqb1EgtjOj6fJhAkh8LJ5r9CehcEL/ohhdPVYzO1l6U8fhwD0+C5opCJQtC9GSDUKRSUnHPyaHnEAk+P4Cg7gL93x5c67c1waQe1037I5P/SjwrNlsOU80zqiTeUP5ISYlRK9YXAR0qrrqZzyGA2uZGHOeLvHPxl78AjX7/XA==')).decode("utf-8"))

class Janela2(object):
    def __init__(self, construtor, usuario=None, conexao=None, cursor=None, *args, **kwargs):
        super(Janela2, self).__init__(*args, **kwargs)
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # --> Inicialização
        self.construtor = construtor
        self.construtor.add_objects_from_string(janela2, ["janela2"])
        self.construtor.connect_signals(self)
        self.conexao = conexao
        self.cursor = cursor

        self.cursor.execute(" create table if not exists login("
                            " usuario text not null,"
                            " senha text not null)")
        self.conexao.commit()
        self.window = self.construtor.get_object("janela2")
        self.window.show_all()

    # -- Sinal conectado a uma GtkWindow
    def ao_sair_janela2(self, *args):
        jn = self.window
        jn.destroy()
        return True

    # -- Sinal conectado a um GtkButton
    def clicou_janela2(self, *args):
        print("Clicou na janela 2")
</code>
Na segunda janela eu até demostrei oque eu precisava herdar na verdade da primeira janela, e esta funcionando, agora se esta correto a ponto de se tornar um modelo para construção de vários módulos seguindo o mesmo molde não tenho certeza, precisava da ajuda de vocês.
Agradeço desde já!


Multiple same user creation with same username on multiple server

Question: Below is the script which i use to create single user on server(I use another scpect script to copy below script on server and run script),But i want to create multiple user.
So,only once i will enter username on line 4 and it will create multiple user with increment user1,user2 and so on...

#!/bin/bash

#Script to Add User

tail /etc/passwd | cut -d: -f1
read -p 'Please Enter The Username To Add: ' name
echo "$name" > /tmp/userlist.txt
clear
echo -e "Hello $name\nYour Name Is Added To The List."
userfile=/tmp/userlist.txt
username=$(cat /tmp/userlist.txt | tr 'A-Z' 'a-z')
for user in $username
do
useradd $user -N -s /bin/bash
usermod -aG sudo $user
passwd $user
#echo "AllowUsers ${user}" >> /etc/ssh/sshd_config
sed -i "s/tui/tui $user/g" /etc/ssh/sshd_config
sed -i "s/$user.*$user/$user/g" /etc/ssh/sshd_config
sed -i "s/tui/tui $user/g" /etc/security/access.conf
done
echo "=================================="

echo "User $name Have Been Created."

echo "=================================="
tail /etc/passwd | cut -d: -f1

Comment: You would make your live a lot easier if you would use a configuration management system like Ansible, Chef, Puppet etc.
Comment: Hey @Gerald, I know about the tools.Tools are being set up till then we have to use script. Kindly help
Comment: You can install ansible on your laptop.  It doesn't require "setup" that most admins can't handle in a few minutes.  Bash is wonderful, but in this case it should be used to invoke ansible.
Comment: I answered this 2 weeks ago: https://serverfault.com/questions/1032355/run-local-bash-script-on-multiple-remote-machine/1032770#1032770
Answer: You can try with this:

#Script to Add User

tail /etc/passwd | cut -d: -f1
read -p 'Please Enter The Username To Add: ' name

for COUNTER in {1..4};
do
        echo $name$COUNTER >> /tmp/userlist.txt
        echo -e "Hello $name$COUNTER\nYour Name Is Added To The List."
done

clear

userfile=/tmp/userlist.txt
username=$(cat /tmp/userlist.txt | tr 'A-Z' 'a-z')
for user in $username
do
useradd $user -N -s /bin/bash
usermod -aG sudo $user
passwd $user
#echo "AllowUsers ${user}" >> /etc/ssh/sshd_config
sed -i "s/tui/tui $user/g" /etc/ssh/sshd_config
sed -i "s/$user.*$user/$user/g" /etc/ssh/sshd_config
sed -i "s/tui/tui $user/g" /etc/security/access.conf
done
echo "=================================="

echo "User $name Have Been Created."

echo "=================================="
tail /etc/passwd | cut -d: -f1```


Assigning variables based on string data

Question: I have a inefficiently constructed form that is obviously sending one type of data per SELECT element. For simplicity's sake, here's an example.
The form posts data from 2 SELECT elements, but it actually needs to contain 3 pieces of data. To the user, the SELECTs do contain 3 pieces of data; one SELECT denotes quantity and the other SELECT denotes an item name AND a price using text between the OPTION tags.
So, the form is sending only $quantity and $itemname
In processing, I am trying to construct a bunch of IFs or a SWITCH to provide for the missing prices.  Being that the string associated with $itemname is unique, I am trying to make a "key" that provides the price.  My logic is, if $itemname contains "One Inch Nut" I could find for $price with something like:
if ($itemname = "Once Inch Nut;") { $price = .25; }

And if $itemname were something else, I would add another IF or IF else or CASE in a switch.
In fact, I am doing just that, yet when I select another OPTION from the SELECT, the $price and even the $item name are defined as the last "IF" in my stack of "IFs"
So if I were to select like, the 3rd item in a 20 item SELECT grouping, when it came time for me to use the variable (adding, echoing, whatever)  I'd end up with the end of the "IF stack"
Obviously, my logic and understanding of IE ELSEIF ELSE is flawed.
Ideas on how to make this "Key" from a variable's string data?
Thanks,
Rob
See below for an abridged example of what I thought would work:
Suppose the form posts "cat" for $itemname and "3" for $qty
<?
$itemname =  $_POST['specificitem'] ;
$qty =  $_POST['quantity'] ;

if ($itemname = "cat;") { $price = 2.25; }
if ($itemname = "dog;") { $price = 1.25; }
if ($itemname = "hamster;") { $price = 3.25; }
if ($itemname = "parakeet;") { $price = 7.25; }
if ($itemname = "werewolf;") { $price = 122.25; }

echo $itemname;
echo "$"$price;

?>

Should yield: cat $2.25   ????
Comment: What kind of data would sting data be? Like "Roxanne" and such?
Answer: You need == to test:
if ($itemname == "cat;") { $price = 2.25; }

However, it is common to see switch used for this type of situation:
$itemname =  $_POST['specificitem'] ;
$qty =  $_POST['quantity'] ;

switch($itemname)
{
  case "cat;":
    $price = 2.25;
    break;
  case "dog;":
    $price = 1.25;
    break;
  case "hamster;":
    $price = 3.25;
    break;
  case "parakeet;":
    $price = 7.25;
    break;
  case "werewolf;":
    $price = 122.25;
    break;
}

echo $itemname;
echo "$"$price;

Answer: I suggest you to use "table" approch for this code. Create an array representing price by item name. And get price in single line like following:
<?
$itemname =  $_POST['specificitem'] ;
$qty =  $_POST['quantity'] ;

## creating a price "table"
$item_prices = array(
    'cat;' => 2.25,
    'dog;' => 1.25,
    ## adding more is easy here
);
if (array_key_exists($itemname, $item_prices)) {
    ## get price in single line
    $price = $item_prices[$itemname];
}
else {
    ## set some default price if item is unknown
}

echo $itemname;
echo "$",$price;

?>

Later you can use $item_prices to generate options for your select tag if you need.


Nginx config issue: getting 403 Forbidden

Question: I'm trying to set up a web application using Nginx, but when trying to access it I am getting a 403 error. I've followed various different approaches to solving this including making sure that my permissions are set but to no avail.
here iss the config for the web application:
server {
    listen   80;
    server_name         localhost

    index               index.php index.html index.htm;
    root                /usr/share/nginx/html/my-app/webapp;
    port_in_redirect    off;

    # Use cached or actual file if they exists, otherwise pass request to WordPress
    location / {
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    # Deny access to hidden files
    location ~* /\.ht {
        deny            all;
        access_log      off;
        log_not_found   off;
    }

    # Pass PHP scripts on to PHP-FPM
    location ~* \.php$ {
        try_files       $uri /index.php;
        fastcgi_index   index.php;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
    }
 }

I ran chmod -R 777 my-app to give it all permissions.
yet I still get the 403 error.
Comment: What is the URL that you're trying to access?
Comment: 127.0.0.1, trying to access it on localhost
Answer: You are missing a ; on your server_name directive, which would normally be a syntax error, but in your case it translates to:
server_name localhost index index.php index.html index.htm;

Which may be a weird list of server names, but more importantly, it means you do not have an index directive. This means that you will get an HTTP 403 response code whenever you attempt to list a directory such as /.
Comment: yes, this seemed to solve the 403, no I'm on to a 404! which I may start a new question about.


GWT: What is the best way to make custom ListBox

Question: I have a question related to custom GWT widget.
I am going to make a custom ListBox which performs language selection. I tried to achieve this by extending the GWT's ListBox class and it works.
public class LanguageListBox extends ListBox {
   ....
}

However, I think from a Java point of view, we might prefer composite over inheritance. I do read some articles that suggests extending Composite rather than the widget itself.
public class LanguageListBox extends Widget {
    private final ListBox listBox;

    LanguageListBox() {
        listBox = new ListBox();
    }

    ......
}

This class does not work. I believe I failed to create bridging method that forward invocation to certain method of LanguageListBox to the wrapped ListBox. However, I have checked there are numerous of methods of ListBox, which method do I need to forward in order to make this design working?
All in all, I am not sure what is the best design in this scenario.

Shall I make my LanguageListBox to extend ListBox directly or extend Compisite and forward method invocation to the wrapped ListBox?
Are there any other better design for this?
Answer: Even though composition is generally prefered over inheritence. In this case I would definitely go with inheritence as you basically want to add new or customize existing functionality in the widget while preserving almost everything ListBox has to offer. I think that generally when dealing with GUI components, the inheritence is usual and, in most cases, the best solution.
However you should make sure, that you cannot achieve the same effect with normal ListBox without inheriting it.
As you mentioned that class will not work as there is absolutely no bridge between ListBox and LanguageListBox. It does not make much sense.
As for language selection. I think it can be achieved with normal ListBox unless you want to have some very special functionality.


Agrupar e somar dados do retorno json com jquery

Question: Possuo este Json que retorna do banco, preciso consolidar os dados que são iguais mas não tenho ideia de como fazer no jquery ou no php. Se alguem tiver alguma sugestão Agradeço!
  {
   "data":[
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"1",
         "pergunta":"a",
         "qtd":"40"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"2",
         "pergunta":"b",
         "qtd":"29"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"2",
         "pergunta":"b",
         "qtd":"11"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"3",
         "pergunta":"c",
         "qtd":"3"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"3",
         "pergunta":"c",
         "qtd":"5"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"3",
         "pergunta":"c",
         "qtd":"2"
      }
   ]
}

Comment: Consolidar de que forma? Somar os valores e deixar apenas 1 dos iguais?
Comment: isso mesmo, no caso apareceria uma vez cada pergunta com o total somado dela.
Answer: Para reduzir o array deixando apenas uma entrada para cada pergunta, distinguindo através do nr_pergunta, pode utilizar a função reduce.
Para cada elemento procura se ele existe, e caso já exista soma a quantidade. Quando não existe apenas o adiciona ao array que está a ser construido.
Implementação:

let json = `
{
 "data": [{
   "nome_pesquisa": "teste",
   "nr_pergunta": "1",
   "pergunta": "a",
   "qtd": "40"
  },
  {
   "nome_pesquisa": "teste",
   "nr_pergunta": "2",
   "pergunta": "b",
   "qtd": "29"
  },
  {
   "nome_pesquisa": "teste",
   "nr_pergunta": "2",
   "pergunta": "b",
   "qtd": "11"
  },
  {
   "nome_pesquisa": "teste",
   "nr_pergunta": "3",
   "pergunta": "c",
   "qtd": "3"
  },
  {
   "nome_pesquisa": "teste",
   "nr_pergunta": "3",
   "pergunta": "c",
   "qtd": "5"
  },
  {
   "nome_pesquisa": "teste",
   "nr_pergunta": "3",
   "pergunta": "c",
   "qtd": "2"
  }
 ]
}`;

let perguntas = JSON.parse(json).data;
//tornar a quantidade numérica para a soma funcionar como esperado
perguntas.forEach(perg => perg.qtd = Number(perg.qtd));

let perguntasAgrupadas = perguntas.reduce(function(acc, curr){
  let encontrado = false;
  for (let pergunta of acc){
    if (pergunta.nr_pergunta == curr.nr_pergunta){
      pergunta.qtd += curr.qtd;
      encontrado = true;
      break;
    }
  }

  if (!encontrado)
    acc.push(curr);

  return acc;
}, []);

console.log(perguntasAgrupadas);
Comment: Isac Muito Obrigado! Funcionou Perfeitamente! Vou ler mais sobre esta função "reduce".
Answer: Pode usar também filter após somar e apagar os itens repetidos (lembrando que o método abaixo tem compatibilidade com o IE):

var json = {
   "data":[
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"1",
         "pergunta":"a",
         "qtd":"40"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"2",
         "pergunta":"b",
         "qtd":"29"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"2",
         "pergunta":"b",
         "qtd":"11"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"3",
         "pergunta":"c",
         "qtd":"3"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"3",
         "pergunta":"c",
         "qtd":"5"
      },
      {
         "nome_pesquisa":"teste",
         "nr_pergunta":"3",
         "pergunta":"c",
         "qtd":"2"
      }
   ]
}

var temp_array = [];

$.each(json.data, function(e,v){
   var items = v.nr_pergunta+v.pergunta;

   if(temp_array.indexOf(items) == -1){
      temp_array.push(e);
      temp_array.push(items);
   }else{
      var array_pos = temp_array[temp_array.indexOf(items)-1];
      var soma = parseInt(json.data[array_pos].qtd) + parseInt(v.qtd);
      json.data[array_pos].qtd = soma.toString();
      delete json.data[e];
   }
});

json = json.data.filter(function(n){ return n });

console.log(json);

Comment: dvd , obrigado pelo auxilio , vou estudar as duas opções, tanto o filter como o reduce. Vlw!


MYOB AccountRight endpoint gives 596 Service Not Found

Question: I am trying to retrieve data from a dummy company using the AccountRight API.
I am building on this nodejs sample project.
Authentication and getting the company file from the company file work.
However, when I try to retrieve data for other endpoints such as /GeneralLedger/Account I always get a 596 Service Not Found.  My uri is:
api.myob.com/<company id>/GeneralLedger/Account
where the company id is the id I retrieve using the /accountright endpoint for the dummy company.
Any ideas?
Answer: The URL is incorrect meaning the API doesn't know you are talking to our AccountRight service.
The API is a hypermedia API and includes all the URIs you need ... however if you are constructing URI they should look like:
https://api.myob.com/AccountRight/{CompanyFile-GUID}/GeneralLedger/Account
Make sure /AccountRight/ is in the URL.
Comment: Ah, so I should just GET from https://api.myob.com/accountright and see what URI's are available?
Comment: Yes you can do that :)


How do I play these notes from "Zelda's Lullaby"?

Question: How do I play the notes shown in the below image?

Here's a link of the video if you want to see

It's on minute 02:33
Answer: Just as the tab says! Fret 8 bottom string, fret 8 3rd string, fret 7 top string, arpeggiated, from low to high.
Answer: Also, in case you can't tell he is using the second finger on the low E, the third on the G and the first on the high E.