Objective C to Swift header file with multiple targets

Question: I'm successfully calling my Swift classes from Objective C (for target 'MyApp') via the import statement:
#import "MyApp-Swift.h"

I've now created a new target called "MyAppLite"
When I compile the new target, I get errors because "MyApp-Swift.h" is required by the code, but the compiler is creating "MyAppLite-Swift.h"
So, I need to create a conditional Swift/ObjC header #import for the target I'm compiling against.
How can this be done, or is there a better way?
Answer: It is also possible to set the Product Module Name setting in Build Settings to be the same across your modules (I set it to $(PROJECT_NAME)), so that the <project>-Swift.h file that is generated has the same name across all modules. This eliminates the need for adding/checking preprocessor macros.
Comment: I"m not sure, but my feeling is that messing with the `Product Module Name` will affect something later on, probably when submitting to the App Store ;)... changing the `Objective-C Generated Interface Header Name` as described in the other answer has no implications.
Comment: @Yar Just saw your comment. That was my feeling initially but the app has been in the App Store for a while and it hasn't been an issue. But if I was using the latest version of Xcode, I'd use Mike Fay's solution tbh. This answer was made before `SWIFT_MODULE_NAME` was available.
Comment: When you create your first Swift-file in your project, xcode will ask you to add the bridging header to the project. In my case it only added the needed config to the _first_ build target. So I also needed to fix the other build targets by configuring the `Objective-C Bridging Header`
Comment: I found that this caused issues in the build process, and that when switching between them, I needed to clean the build folder. I believe that because they all share the same project name, they all build to the same folder.
Comment: God bless you! Using same module name across all my targets save me from crappy issue with custom swift class in mixed Swift/ObjC project which happens only in release build!!! Thanks a lot!
Comment: @boraseoksoon This answer is a little dated. I'd go with the answer by Mike Fay for recent XCode versions
Comment: This is not really the correct answer, I would go with the second most upvoted answer
Answer: The best way I've found to address this issue is in your Xcode shared project settings. You can search for the following setting:
Objective-C Generated Interface Header Name*
If you set that value to a common header name, such as "MyProject-Swift.h", it will be applied to each of your targets and you can safely use the import declaration in any of your Objective-C files. This allows you to continue using unique product module names for each target, if needed.
I've tested this in Xcode Version 6.4 (6E35b).
*Note: This will appear under your Swift compiler settings, which are only visible if you have Swift source files added to your project. Additionally, if a target doesn't have any Swift source associated with it, the Swift compiler options will not be visible for that target's build settings.
Good luck!
Comment: This is the best solution IMO.
Comment: The original value of this is `$(SWIFT_MODULE_NAME)-Swift.h`... so while this answer is awesome, I'd *love* to know how to adjust the `SWIFT_MODULE_NAME` for the module.
Comment: While I'm here, I'd recommend using some obvious name to reduce confusion, e.g., `MidiDesignerAllTargets-Swift.h` Thanks for this great answer, it's a *great* find.
Comment: This is the best solution if you are using Xcode 7+.
Comment: It is definitely still available in Version 8.3.3 (8E3004b).
Comment: @AntonTropashko You will need to select show/filter `All` and not `Basic` to see it.
Answer: Previous answers have some problems if you decide to rename your targets or project, or use SWIFT_MODULE_NAME as intended.
The most universal solution is to change SWIFT_OBJC_INTERFACE_HEADER_NAME ("Objective-C Generated Interface Header Name") under Project's, not Targets, Build Settings, to:

$(PROJECT_NAME)-Swift.h — one per project;
$(SWIFT_MODULE_NAME)-Swift.h — one per module (default value).
Comment: the cleanest of all solutions.Xcode 8.3.3, Swift 3, make sure the common/shared swift files belong to each target, all works after this.
Comment: How to handle "$(PROJECT_NAME)-Swift.h file not found" error like warnings?
Comment: This should be accepted Answer as it shows some more details though @C0D3LIC1OU5 's answer was good enought
Comment: This is what I'm looking for. Thank you for your answer.
Answer: Well, the only way I can fix is to...
#ifdef IS_LITE
#import "MyApp_Lite-Swift.h"
#else
#import "MyApp-Swift.h"
#endif

Note that if there's any 'illegal' chars in my Product Module Name, they need to be replaced with underscores.
Hope that helps!
Comment: This worked for me, as the accepted answer caused build issues when switching between targets.
Comment: what's IS_LITE?
Answer: I put the appropriate #import <project>-Swift.h statement in a prefix header file (<project>-Prefix.pch) defined/added for each build (target/scheme).
Comment: This has the advantage of making it more convenient to use Swift classes in Objective-C, and more consistency between the Swift experience, where headers do not need to be explicitly imported, and the Objective-C experience.
Answer:
pickture will tell you all

second targets name xxx and xxx-ih

select first target tap build setting -> find Objective-C Bridging Header set xxx-bridging-Header.h and Objective-C Generated Interface Header Name set xxx-Swift.h

select second target and same step 2
Answer: The only working way is the following :
1- from first target (which has a working bridging) Build Setting select Objective C Bridging Header
2- Copy Objective C Bridging Header
3- open the other target Build Setting
4- Paste it
5- change the header file to your new header file (i.e target B.h)
(now you have this option for two target)


How to check an array against a regex with jQuery?

Question: I have a bit of jQuery which I'm using to identify spam submissions in a form by using a regex to check for blacklisted keywords in the user input. It works great, but it's only able to check one field. I would like it to check the input of all fields which I've added a class to.
This is what I have that's working:
jQuery(function($) {
 var user_input = $(":input[name=input_4]");
 user_input.change(function() {
     var spam_check = user_input.val().search(/\b(marketing|penis enhancement|dating)\b/i);
     if (spam_check !== -1) {
         alert("This is spam");
     }
 });
});

And this is the version I've modified but I'm having issues with:
jQuery(function($) {
 var user_input = $(".spam-check");
 user_input.change(function() {
     var spam_check = user_input.val().search(/\b(marketing|penis enhancement|dating)\b/i);
     if (spam_check !== -1) {
         alert("This is spam");
     }
 });
});

I've been trying to somehow return all the values of the array as a single string, but I'm at a loss...
Comment: $() selector returns collection. val() method returns value of first element. use $(this) selector for current element.
Answer: You need to use $(this) instead
jQuery(function($) {
  var user_input = $(".spam-check");
  user_input.change(function() {
    var spam_check = $(this).val().search(/\b(marketing|penis enhancement|dating)\b/i);
    if (spam_check !== -1) {
      alert("This is spam");
    }
  });
});

Here's the code a bit improved
$(function() {
  const user_input = $(".spam-check");
  user_input.on('change', e => $(e.currentTarget).val().search(/\b(marketing|penis enhancement|dating)\b/i) !== -1 ?  alert("This is spam") : '');
});

Comment: Thanks so much!
I have a follow up question though because it's not working for me still...

I just realized the class I was going to use for the input fields isn't being applied to the input fields directly but instead to on of its parents...
If I was to change `const user_input = $(".spam-check");` to `const user_input = $(".spam-check > input");` should that work?
Alternatively, all these input fields have a name that starts with "input_", so I would think I could do `const user_input = $(":input[name^="input_"]");`, but I can't get it working with either of these selectors...
Comment: @MitchMcQuinn `If I was to change const user_input = $(".spam-check"); to const user_input = $(".spam-check > input"); should that work?` -- YES, `so I would think I could do const user_input = $(":input[name^="input_"]")` -- Should work
Comment: Strange, it's still not working when I try to use either of those selectors with either the modified or improved versions you posted above...
Comment: Ooh! Nevermind, I got it! I was using a double quote where it should have been single ♂

Thanks again for your help! You're a real life saver ♂


Help understanding notation around generalized inverses of distribution functions

Question: I am trying to understand this excerpt from Beran (1984) - an old paper on the statistics of the bootstrap:

I don't understand how it can ever be the case that $c_{n, L} < c_{n, U}$. Isn't it the case that, by definition $c_{n, L} \geq c_{n, U}$, since distribution functions are always non-decreasing? In fact, I don't understand how we can ever have $c_{n, L} \neq c_{n, U}$. But if $c_{n, L} = c_{n, U}$ always, then this write-up seems strange.
As I see it, both of these things are equivalent to the "generalized inverse" commonly used for distribution functions, which is usually defined similarly to $c_{n, L}$ here (i.e. $F^{-1}(1-\alpha) = c_{n,L}(\alpha)$).
Answer: A distribution function (aka cumulative distribution function, probability distribution function, cdf) is always non-decreasing but can be constant on intervals.  Such as, the cdf for a Bernoulli random variable, for which, say, $$F(x)=P(X\le x)=\begin{cases} 0&\text{if }x<0\\1-p&\text{if }0\le x<1\\1&\text{if }x\ge1.\end{cases}$$
Apply Beran's recipe in the case that $\alpha=p$ and you will see that the two $c_n$ numbers differ.
The underlying random variable need not be discrete.  Such as a Bernoulli rv plus an independent uniform on the range $[0,1/2]$; the resulting sum is supported on $[0,1/2]\cup[1,3/2]$, and if $\alpha$ corresponds to the probability of $[0,1/2]$, the two $c_n$ numbers will again differ.
If the graph of $F$ has horizontal segments on which $F$ is constant, the inverse of $F$ will have jump discontinuities.  The two $c_n$ numbers are the left- and right hand limits of $F^{-1}(1-\alpha)$.


parsing the value in between two XML tags

Question: I know this one has been asked before, however I can't seem to find a suitable solution, so I 'll state the problem:
I have a string of characters that is similar to an XML file. It's not an XML string, but it has opening and closing tags. All the information resides in one single line, for example:
<user>username</username>random data;some more random data<another tag>data</anothertag>randomdata;<mydata>myinfo</mydata>some more random data....

etc...
I am trying to read ONLY what's in between <mydata></mydata>. Any way to just parse this?
thanks, code is appreciated.
Comment: So the input string is not valid XML?
Comment: Yeah, was going to say, why not just make it valid XML, then you have parsers & encoders at your fingertips.
Comment: no, as I mentioned, it's NOT an XML string.
Comment: @Shawn D. Because I am not in charge of that string. I just get it and need to parse it. I can't force my customer to create a valid XML string when they don't need to. Besides, bringing a full XML parser just to parse one single tag is a huge overkill. thanks though.
Answer: I would just use strstr():
char * get_value(const char *input)
{
  const char *start, *end;

  if((start = strstr(input, "<mydata>")) != NULL)
  {
    start += strlen("<mydata>");
    if((end = strstr(start, "</mydata>")) != NULL)
    {
      char *out = malloc(end - start + 1);
      if(out != NULL)
      {
        memcpy(out, start, (end - start));
        out[end - start] = '\0';
        return out;
      }
    }
  }
  return NULL;
}

Note that the above is untested, written directly into the SO edit box. So, it's almost guaranteed to contain at least one off-by-one error.
Comment: @Jessica: `memcpy()` isn't affected by carriage returns.
Comment: thanks. the code only returns the 1st 12 characters of the string. I can't figure out why.
Comment: hmmm... sometimes the string passed onto input contains a carriage return even though it is part of the same buffer (string). However I see how this affects strstr() into returning only the 1st 12 characters...
Comment: it has to do with the memcpy. I just added a for loop and copy each char of start into out until i < end - start and it works.
Comment: @Jessica: You found a bug, the second argument to memcpy() was incorrect. It's fixed now.


DirectX versus OpenGL Game Development

Question: I have a few questions regarding what graphics platforms are utilized when making professional games (like WoW, starcraft2, diablo 3.. etc).
First, would WoW look different if rendered in OpenGL, rather than Direct X? Would performance be significantly different if rendered in OpenGL?
Second, What is the main process when creating a game, specifically in terms of using a model created in Maya, or 3DS Max in the video game? Does one create the model, then export the model to readable OpenGL/DirectX code, with all of the shader programs exported, and all vertices and triangles created in code, and finally utilize the code in a C++/c program?
OVerall, I'm curious on how video game designer/programmers export actual 3DS MAX/Maya models into their code
Answer:
First, would WoW look different if rendered in OpenGL, rather than Direct X?

It is rendered in OpenGL (well, it can be with a setting). And no, it doesn't look different in D3D rendering. (note: DirectX is more than just Direct3D.)

Would performance be significantly different if rendered in OpenGL?

Unlikely. There are some things that OpenGL implementations can be faster at, but WoW doesn't use any of them.

Does one create the model, then export the model to readable OpenGL/DirectX code

Neither OpenGL nor Direct3D has a model format. Even .x files are deprecated at this point; those were part of the D3DX library, which was just a Microsoft-written layer on top of D3D.
Second, you don't export them into "code". You export them into files, which you then read in your game. Well, generally, you process those files into more digestible formats for you game, as exporters tend to optimize meshes differently from what you might want in your game.
So it's export to file -> process to final file -> read in game.
Comment: @Jim Hubbard - no the external file contains the shape of the character (the vertex mesh) and the texture (surface image). They are drawn by the artistic half of the company (the ones with more tattoos  and better dress sense) and then incorporated into the game engine by the programmers. The character is then adjusted and moved by the game engine during play.
Comment: So say you had an animation that your model did to run your model whenever the user pressed w on his/her keyboard.. This animation would be in a separate file, which would be called, and the file itself changes the vertex coordinates accordingly?
Answer:
First, would WoW look different if rendered in OpenGL, rather than Direct X? Would performance be significantly different if rendered in OpenGL?

OpenGL and Direct3D follow similar principles: A stream of vertices goes in, gets transformed (either fixed function or by a vertex shader), after transformation the vertices are grouped into primitives (points, lines, triangles) and the primitives rasterized, i.e. for each pixel the primitive covers some calculation (again either fixed function or by a freely programmable fragment shader) is performed that determines the so called "fragment" color. Finally the fragment it tested for visibility and blended into the picture-in-drawing-progress.
Later versions of OpenGL and DirectX added geometry and tesselation stages, but those are just details.
In all other aspects the ways they work are so similar, that there's virtually no difference between rendering results, except the rounding errors introduced on the vertex positions by the different clip space mappings.

Second, What is the main process when creating a game, specifically in terms of using a model created in Maya, or 3DS Max in the video game? Does one create the model, then export the model to readable OpenGL/DirectX code, with all of the shader programs exported, and all vertices and triangles created in code, and finally utilize the code in a C++/c program?

No! The model and its auxiliary data are stored separately from the code. While it most certainly is possible to store geometry in code, this is a rather bad idea and should not be done. I explained the basic idea, how a model is loaded in How to Import models from 3D software, like Maya into OpenGL?

OVerall, I'm curious on how video game designer/programmers export actual 3DS MAX/Maya models into their code

They don't. They export their models into a file format optimized for efficient loading by a 3D engine, and then the engine loads the models and auxiliary data from files. This is not some kind of black voodoo magic. The whole process is not very different from loading an image from a file and displaying it or some music playing it to the speakers. To animate a 3D model, the model contains additional control information (armatures, bones, etc.) which allow to deform it based on a rather small number of parameters (arm rotation, looking direction, etc.) Then those parameters are varied.
Answer: You're asking a large question, but to at least the "second" part of it-- nontrivial models are created in software packages as you describe, but they're then usually exported into data files that basically represent lists of geometry. Those files are then read in by the game's resource loader, and put into vertex arrays or buffer objects or etc. This way the data is independent from the code.
Hardcoded geometry is usually used for small, fixed things, and for tutorial projects. :)
Answer: Your first question is really not answerable - both graphics libraries give me access to the underlying graphics hardware through an API.  How the game looks depends largely on how that API is used.  If I set the backbuffer to red in OpenGL, it will look the same as if I set the backbuffer to red in DirectX.  If I do the same lighting calculations in OpenGL that I do in DirectX, I will see the same results, and so on.  Any differences that result are likely a result of the APIs not being identical so the programmers work around it.
Models from a 3D modeling program (such as Maya or 3DsMax) are not 'coded', they are exported into a format that the game can understand.  These can be XML based formats such as Collada, text based formats such as OBJ, or even proprietary binary formats.  What is important is that the data from the modelling program is made available to the game in a format which it can read in and convert into an internal representation of the geometry.  Pretty much every game engine handles geometry in a slightly different fashion.
Technically, I could just save the following file:
V1  0.0, 0.5, 0.5
V2 -0.5,-0.5, 0.5
V3  0.5, 0.5, 0.5

M1 V1, V2, V3

As long as the game understood that this file contained three vertices (V1, V2, V3) and one mesh (M1) consisting of those three vertices, and knew how to read it in to a format that we could then render, we would be in business and could draw this triangle to the scene as a mesh.  Incidentally, this format is not far from the OBJ format.
Most exporters are much more complicated than this, and most engines support a more complicated geometric representation to account for all the extra data that these (powerful) modeling tools can provide for us.
Answer: This is a very big question that is hard to answer briefly.
About directX and Opengl, they are not very different in terms of functionality and performance (maybe).
DirectX is always one step ahead of Opengl. For example, it first supported the hardware tessellation feature, and then after a while, this feature appeared in Opengl. But this is not a big deal, because when you develop a game, you will have to support a range of machines, including those low performance machines. So you may not be able to use the new features until it becomes very common.
Yes, game developers use Maya, and 3Ds max kind of software to create the models of a game, and normally they output the model to a model file. this file is read in by the game engine of the game.
I don't suggest you to start with opengl or directx, I think it is better to use a game (or graphics) engine instead. For example, ogre 3D. http://www.ogre3d.org/
because it supports both directx and opengl, and it also has ready made 3Ds max, Maya exporter, which makes loading models easily.

DirectX versus OpenGL Game Development


Issue filling selection box with PHP from database

Question: Basically, I have 1 selection box at the top of my page, called cups. There are 8 teams assigned to each cup. Upon selecting a cup and hitting submit I want all of the teams associated in that cup to fill 8 selection boxes elsewhere on the page allowing the user to choose which team plays the other.
I've attempted many things, and I have got to the point where I can echo the teams, they simply aren't being echoed into the selection boxes in a different div on the same page
<input type="submit" name="submit" value="Generate" class="submit">
<?php
if (isset($_POST['submit'])) { //checking if submit button was clicked

    include_once 'action/dbcon.php';

    $cname = $_POST['cupname'];

    if (empty($cname)) {
        header("Location: ../table.php?field=empty"); //return them if fields are empty
        exit();
    } else {
        $sql = "SELECT * FROM teams WHERE cup_name='$cname'";
        $show_teams = mysqli_query($conn, $sql);

        if (!$show_teams) {
            echo "Could not load teams! " . "(" . mysqli_error($conn) . ")";
        }
        while ($team = mysqli_fetch_assoc($show_teams)) {
            echo $team["team_name"];
        }
    }
    echo "dank";
}
?>
</form>

        <form class="seed-form">
            <select name="team" required>
            <option></option>
            </select>
            <select name="team" required>
            <option></option>
            </select>

So, I'm echoing the right results, just not as options in the selection boxes where I want them
Comment: **Warning:** You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php) and should really use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](http://php.net/manual/en/pdo.prepared-statements.php) or by [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Never trust any kind of input, especially that which comes from the client side. Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/).
Answer: most easy might be to echo them where they should appear:
<select name="team" required>
<?php while ($team = mysqli_fetch_assoc($show_teams)) { ?>
    <option value="<?php echo $team["team_id"]; ?>"><?php echo $team["team_name"]; ?></option>
<?php } ?>
</select>

Comment: This is what i was trying to incorperate, however, im confused as to where the already written PHP code before the while statemnt is placed. Could you possibly provide an example? Thanks
Comment: @BradArcher haven't I already provided a nice, minimal example? just move that loop... or fetch all records and then loop twice. the only thing confusing here is you not having provided the fields of the record-set & no expected output... nor option values to be selected. Ordinary, one would probably use a template engine for this kind of output.
Comment: i apologise i didnt understand, that parts working now. Quick question, do you know a method of removing them from the select box once a user has selected that specific entry?
Comment: By the way this code only works for one selection, when the same line of code is used in another it doesnt load any results
Answer: You can handle this with jQuery - In my example I simply cut and pasted from one of my cms scripts.
The form below is included in a larger form so the the form tag and submot are not in the example.
The form:
<?php
    echo '
';
        # page-type
        echo '
';
            $getPgType = $db->prepare('SELECT page_type_id, page_type FROM page_types WHERE page_type_id >= 1 order by page_type asc');
            $getPgType->execute();
            echo 'Page Type
';
            echo '<select id="" name="page_type" class="expand">';
                echo '<option value=""'; if($page_type == ''){echo 'selected';} echo '>Select Page Type</option>';
                while($row = $getPgType->fetch(PDO::FETCH_ASSOC)){
                    $id = $row['page_type_id']; $pagetype = $row['page_type'];
                    echo '<option value="'.$pagetype.'"'; if($page_type == $pagetype){echo 'selected';} echo '>'.ucwords($pagetype) .'</option>';
                }
            echo '</select>';
        echo '
';

        # classification_type
        echo '
';
            echo 'Classification Type
';
            echo '<select id="classificationType" name="classification_type" class="expand">';
                echo '<option value=""'; if($classification_type == ''){echo 'selected';} echo '>Select Classification Type</option>';
                echo '<option value="classification"'; if($classification_type == 'classification'){echo 'selected';} echo '>Classification</option>';
                echo '<option value="category"'; if($classification_type == 'category'){echo 'selected';} echo '>Category</option>';
                echo '<option value="content"'; if($classification_type == 'content'){echo 'selected';} echo '>Content</option>';
            echo '</select>';
        echo '
';

        # classification
        echo '
';
            $selstmt = $db->prepare('SELECT classification_id, classification FROM classifications WHERE classification_id >= 1');
            $selstmt->execute();
            echo 'Classification
';
            echo '<select id="getAssignedCats" name="classification" class="expand">';
                echo '<option value=""'; if($classification == ''){echo 'selected';} echo '>Select Classification</option>';
                while($row = $selstmt->fetch(PDO::FETCH_ASSOC)){
                    $classification_id = $row['classification_id']; $classN = $row['classification'];
                    echo '<option value="'.$classification_id.'"'; if($classification == $classification_id){echo 'selected';}
                    echo '>'.ucwords(str_replace('-',' ',$classN)).'</option>';
                }
            echo '</select>';
        echo '
';

        # category
        echo '

';
    echo '
';
?>

Notice the

... this is where the jQuery renders the desired selection box.
The jQuery
/* PARSE GET ASSIGNED CATEGORIES
======================================================================================== */
    $("#getAssignedCats").change(function(){
        var type = $("#classificationType").val();
        if(type != 'classification'){
            var class_id = $(this).val();
            var url = 'parse/get-assigned-categories.php';
            var postit = $.post( url, {class_id:class_id});
            postit.done(function( data ) {$('#categoryHTML').html(data);});
        }
    });

When the selection box #getAssignedCats is changed by the user the jquery collects the value and posts it to the parse.php file.
Parse PHP
<?php
    $level = '../../../';
    include($level.'core/ini/start.php');

    $class_id = $_POST['class_id'];

    if($class_id != 888888){

        $selCat = $db->prepare('SELECT cat_id, category FROM categories WHERE classification = :THEID ORDER BY category asc');
        $selCat->bindValue(':THEID',$class_id,PDO::PARAM_INT); $selCat->execute(); $cat_ct = $selCat->rowCount();
        echo 'Category';
        echo '<select name="category" class="expand">';
            echo '<option value=""'; if($category == ''){echo 'selected';} echo '>Select Parent category</option>';
            if($cat_ct <= 0){
                echo '<option value="777777"'; if($category == '777777'){echo 'selected';} echo ' class="blue">This is a Category Page</option>';}
            elseif($cat_ct >= 1){
                while($row = $selCat->fetch(PDO::FETCH_ASSOC)){
                    $cat_id = $row['cat_id'];
                    $category = $row['category'];
                    echo '<option value="'.$cat_id.'"'; if($category == $cat_id){echo 'selected';}
                    echo '>'.ucwords(str_replace('-',' ',$category)).'</option>';
                }
            }
        echo '</select>';
    }
?>

Hope this helps.


PHPUnit: Getting equalTo assertion to ignore property

Question: I have the following PHPUnit testcase:
    $mailer = $this->getMockBuilder(MailerInterface::class)->getMock();
    $simpleMailer = new SimpleMailer($mailer);

    $message = (new Message())
        ->setTo($user)
        ->setFrom($from)
        ->setSubject($subject)
        ->setTemplate(SimpleMailer::TEMPLATE)
        ->setContext(['message' => $body]);

    if ($bcc) { $message->addBcc($bcc); }

    $mailer
        ->expects($this->once())
        ->method('send')
        ->with($this->equalTo($message));

    $simpleMailer->sendMessage($user, $subject, $body, $from, $bcc);

This was working fine until the Message class was changed. The Message class now sets a unique ID on construction, meaning that equalTo now returns false with the following difference:
 MailerBundle\Document\Message Object (
-    'id' => '5a372f3c-a8a9-4e1e-913f-d756244c8e52'
+    'id' => '11176427-7d74-4a3c-8708-0026ae666f8b'
     'type' => null
     'user' => Tests\TestUser Object (...)
     'toName' => ''
     'toAddress' => null
     'domain' => null
     'fromName' => null
     'fromAddress' => 'email@example.com'
     'bccAddresses' => Array (...)
     'subject' => 'subject'
     'textBody' => null
     'htmlBody' => null
     'template' => 'MailerBundle:MailTemplates:...l.twig'
     'context' => Array (...)
)

Is there any way that I can exclude certain properties from the equality check?
Comment: Maybe you can override the `id` for the test!?
Comment: The id is a private property with a public getter method. Exposing the setter only for the tests doesn't sound like a good idea to me. I'd like to find a solution without changing code outside the tests.
Comment: If you have php7 you can do it with an anonym class like `new class extends Message { public function _construct(){ /*override here*/}}`, no need to override the original. And btw you can `mock` the getter, maybe that helps
Comment: Yes, I could influence the `Message` I construct in the tests. But not the message constructed in `simpleMailer->sendMessage`
Answer: If your Message class has getters, you can use a callback in with function to match only properties you care about. Something similar to
$mailer
    ->expects($this->once())
    ->method('send')
    ->with($this->callback(function(Message $message) use ($user, $from, $subject, $body) {
            return $message->getTo() == $user
                && $message->getFrom() == $from
                && $message->getSubject() == $subject
                && $message->getTemplate() == SimpleMailer::TEMPLATE
                && $message->getContext()['message'] == $body
        }));

Comment: Thank you! This seems to be the most straight forward way to solve the problem.
Comment: Having to add every new property to the test is just a useless waste of time.
Answer: I just wrote something similar, and was curious if I just reinvented the wheel (I pretty much did). However, I thought would share my result here in case it helps anyone, since it matches your use case like mine.
My goal was to compare two objects and assert equality between properties, with the ability to ignore specified keys. I'm using this with the current PHPunit (Feb 2020).
private function assertEqualWithIgnore($expected, $actual, $ignoreKeys = [], $currentKey = null): void
    {
        if (is_object($expected)) {
            foreach ($expected as $key => $value) {
                $this->assertEqualWithIgnore($expected->$key, $actual->$key, $ignoreKeys, $key);
            }
        } elseif (is_array($expected)) {
            foreach ($expected as $key => $value) {
                $this->assertEqualWithIgnore($expected[$key], $actual[$key], $ignoreKeys, $key);
            }
        } elseif ($currentKey !== null && !in_array($currentKey, $ignoreKeys)) {
            $this->assertEquals($expected, $actual);
        }
    }

Answer: Inspired by Brian's answer, here is an helper that trim the unwanted ids before making an equality check. This way the behavior remains very close to phpunit's assertEquals.
You get the equality checks on all properties at once instead of one at the time. You can also more easily spot where the check is failing.
private function assertEqualsButIgnore($expected, $actual, $ignoreKeys = []): void
{
    $copyExpected = $expected;
    $this->recursiveUnset($copyExpected, $ignoreKeys);

    $copyActual = $actual;
    $this->recursiveUnset($copyActual, $ignoreKeys);

    $this->assertEquals($copyExpected, $copyActual);
}

private function recursiveUnset(&$objOrArray, $unwanted_key): void
{
    foreach($unwanted_key as $key) {
        if(is_array($objOrArray)) {
            unset($objOrArray[$key]);
        } else {
            unset($objOrArray->$key);
        }
    }
    foreach ($objOrArray as &$value) {
        if (is_array($value) || is_object(($value))) {
            $this->recursiveUnset($value, $unwanted_key);
        }
    }
}

Answer: Another solution using a custom comparator as suggested by Sebastian in https://github.com/sebastianbergmann/phpunit/issues/4034
My use case is to assert objects for equality after the test subject has been unserialize(serialize()): A custom __serialize() ignores some properties when doing that, so a custom comparator is used to ignore these.
final class FooTest extends TestCase
{
    public function setUp(): void
    {
        parent::setUp();
        // Register custom comparator to compare IncludeTree with its unserialize(serialize())
        // representation since we don't serialize all properties. Custom comparators are
        // unregistered after test by phpunit runBare() automatically.
        $this->registerComparator(new UnserializedIncludeTreeObjectComparator());
    }

    /**
     * @test
     */
    public function foo(): void
    {
        $includeTree = [...]
        self::assertEquals($includeTree, unserialize(serialize($includeTree)));
    }
}

With this comparator class:
final class UnserializedIncludeTreeObjectComparator extends ObjectComparator
{
    protected function toArray($object): array
    {
        $arrayRepresentation = parent::toArray($object);
        if ($object instanceof IncludeInterface) {
            // This property is not serialized and falls back to default
            // value on unserialize(). We ignore it for equality comparison.
            unset($arrayRepresentation['name']);
        }
        return $arrayRepresentation;
    }
}

Comment: That actually looks like the most natural solution. Thank you.
Answer: Why not just...
$exporter = SebastianBergmann\Exporter\Exporter();

$expectedObjectAsArray = $exporter->toArray($expectedObject);
$actualObjectAsArray = $exporter->toArray($actualObjectAsArray);

unset($expectedObjectAsArray['unwantedProperty']);
unset($actualObjectAsArray['unwantedProperty']);

$this->assertEquals($expectedObjectAsArray, $actualObjectAsArray);

PhpUnit already compares objects as arrays:
// vendor/sebastian/comparator/src/ObjectComparator.php:77
parent::assertEquals(
    $this->toArray($expected),
    $this->toArray($actual),
    $delta,
    $canonicalize,
    $ignoreCase,
    $processed
);

My proposed solution is therefore just as performant as comparing via PhpUnit.
Answer: Do you have to make sure it's the equal object? If not I would recommend using a matcher, e.g.
->with($this->isInstanceOf(Message::class))

You could also combine multiple checks using e.g. logicalAnd()
Here is a good resource of available matchers: http://archive.gregk.me/2011/phpunit-with-method-argument-matchers/


I need to provision 30TB for a server.  Does this process have anything to do with Logical Memory?

Question: I'm currently buying a server that NEEDS 30TB of storage, 15TB of which is logical and 15TB is physical.  However the towers only allow 8 2TB 3.5 inch HDD's, which gets me to 16TB. How do I get another box of HDD's without needing another processor? Or does the 16TB fit the 15 logical and 15 physical requirement? I'm having a hard time understanding this.
Comment: Your question doesn't make sense in the first place. There's no such thing as Logical Storage. You can have logical disks, which is storage that maps to physical storage (abstracted commonly by a HBA controller)...
Comment: I hate to point this out, but when you say "another processor" I fear that you mean "another chassis" or "another computer". Which, if that's the case, means you're already in over your head. This site is here so people can learn, but maybe you just need to hire someone qualified to help you right now.
Comment: Just keep daisy chaining 2TB firewire hard drives together and let your OS software RAID them together! (sarcasm).
Answer: I think you're confusing a couple things here.  Logical memory refers to how Windows allocates memory space.  Paging (also known as virtual memory) refers to how Windows will swap memory to disk in order to continue to do calculations in RAM.  And then you have your actual disks and storage.
Like Chris states in his comment, logical disks refers to having many disks in a RAID that is presented as one drive to the system.  So you could have 15 disks presented as one "drive" for data.
I'm not sure that the MD3000 that ST8 posted will work for you because even though it has 15 bays, it's divided into two managed partitions that as far as I remember can't be bridged.  They're handled on two different RAID controllers.  EDIT On further reflection, I could be remembering the MD1000.  In either case, you need to be sure you can present one contiguous 30TB drive to whichever OS you're using.
Some links to keep you entertained regarding logical memory and paging.
Comparison of 32-bit and 64-bit memory architecture for 64-bit editions of Windows XP and Windows Server 2003
Windows Memory Management (pdf)
Virtual Memory in Windows XP
Essentially you'll need to find some kind of external storage, whether DAS or NAS and attach it to your server.  As I don't know the requirements of your application, I can't really help you with that.  You may want to get a consultant or talk with the sales reps or whomever you have that can support this on site.
Answer:
However the towers only allow 8 2TB 3.5 inch HDD's

Then dont get towers. I am always surprised how people try to fit something large into equipment totally not made for this.
Go rack.
SuperMicro has nice cages for storage computers and JBOD - JBOD has more drives but no place for a motherboard, slave them by SAS chaining. This is up to 80 (!) 2.5" drives in 4he, loaded front and back. Stoage Pod (look it up on google) fits 60 3.5" drives into 4 HE.
it is not that hard to find equipment that totally outsizes your meager requirements. just use google properly. It will not e a rack of te mill tower, though.
THAT SAID - I know of a maxi tower there you can fit 6 2.5" cabinets each with 8 discs. That is 48tb raw capacity ;)
Answer: I'd suggest getting a server with a minimal hard drives to support the OS and attaching a raid array to it. An MD3000 for example
Comment: Can you help me understand what that means? So I should get a processor box with the minimum # of HDD's and then get RAID Boxes full of HDD's that are connected via SCSI cables?
Comment: Yes, exactly. "15TB of which is logical and 15TB is physical" - no. You can separate 30Tb into logical drives, but it will still be physical storage somewhere. If your tower doesn't have room you will need a different enclosure. This is why I suggested something like an MD3000.


Rewriting squareroot function in the form (a-b)(a+b)?

Question:
I have this function and I'm trying to write a program to compute it as n approaches 100. The problem is it overflows once it reaches around 50. The hint to solving this question is to rewrite the part inside the parentheses (sqrt(1+2^-n*Xn) - 1) to (a-b)(a+b), but I'm having trouble thinking of how to do that.
Comment: Multiply top and bottom by $\sqrt{1+2^{-n}x_n}+1$. On top we get something nice.
Comment: In the language C#, the max value that could be stored in an integer is $9,223,372,036,854,775,807$, that is 2 to the power 63. As a result, you need to re-write the expression with much reduced powers of 2, somehow...
Comment: What is $x_0$? It would help to spare us the calculations.
Answer: Well, $(a+b)(a-b)$ is $a^2 - b^2$, so perhaps you treat the two terms as $a^2$ and $b^2$ to get:
$$x_{n+1} = 2^{n+1}((1+2^{-n}x_n)^{1/4} + 1)((1+2^{-n}x_n)^{1/4} - 1)$$
Maybe this helps?
Answer: Try something like this, assume $x>0$:
$$\sqrt x-1= (x^{1/4})^2-1=(x^{1/4} -1)(x^{1/4}+1). $$
But I am not sure that it will be easier now.


Kubernetes: Expose multiple services internally & externally

Question: Am using AKS for my cluster
Scenario:
We have multiple API's (say svc1, svc2 & svc3 accessible on port 101, 102, 103).
These API links need to be exposed to client and are also used internally in application.
Question:
I want to expose this to both external & internal load balancer on same ports.
Also when i access the service internally, i want them to be accessible by service name (Example: svc1:101)
Answer: Well, I was able to fix the issue without using NodePort/ClusterIP.
Solution is pretty simple but seems its not documented.
Only thing we have to do is have multiple tags where 1 tag is same as of external load balancer and other tag you have same matching service.
This will map your replicaset to both service & external loadbalancer.
Detailed answer available on - https://www.linkedin.com/pulse/exposing-multiple-portsservices-same-load-balancer-sunil-agarwal
Comment: Great article that you posted. Saved my day. Reduced from 4 public ips to 1
Answer: In Kubernetes:

if you want to expose something internally only, you should use ClusterIP service type
if you want to expose both internally & externally, use LoadBalancer (or NodePort) service type.

Please check Kubernetes: Service Types for more details.
Comment: I know this. My requirement is i want both
Comment: if i use node port, for each service i will get different public IP. I want one common IP for all services (port will be different). At the same time, I want all services to be accessible internally.


Data set for forecasting

Question: I am looking for a data set which can be used for ARIMA or any forecasting models. The data should be such that, over a period of time the range of inputs change i.e. the band of input data changes significantly. This should lead to incorrect forecasting. I should see the error in forecasting and should retrain the model. I do not want to simulate and i am looking for some real world example.
Comment: Like the AirPassenger data in Box and Jenkins? Please note that this sort of question ... "*Where can I find data that fits these criteria*" doesn't seem to fall under the scope of CV as defined in the [faq](http://stats.stackexchange.com/faq#questions).
Comment: You can find here http://www.matteodefelice.name/research/resources/ electricity demand, ambient temperature and occupancy of a building inside my research centre. I've used such data for a paper about forecasting comparing neural networks with ARIMA models.
Answer: Dr. Rob Hyndman has provided a Time Series Data Library here.

Data set for forecasting


Is there a helper to display a comma separator if the value exists?

Question: I have the following helper:
def results(grade, percent, date)
  "#{grade} #{percent} , #{date}"
end

Basically I want my output to look like:
10 %, 12/12/2012

The above helper works fine if grade, percent and date exist.
However, there are other scenarios that needs to be handled. For example, if grade and percent are both empty, then I would get the following output:
,12/12/2012

If the date is empty then:
10 % ,

I could do a bunch of if/else statements and handle the above case, but I wondered if there is a smarter way to handle this?
In the above scenarios, I dont want the comma to be displayed.
Comment: In other scenarios, you show how they are currently handled, but you do not show how you want them to be handled.
Comment: Why are you passing percent as a parameter. Its always suppose to be '%'. Am I right..?
Comment: actually percernt would be replaced with units. it can be anything
Comment: What do you mean by `value`, `unit` and `date`? You only  have `grade`, `percent`, and `date`.
Answer: The first that came up in my head was to split it into an array. For the first part i would use lstripto remove whitespaces before and after and then join with date.
def results(amount, unit, date)
  ["#{amount} #{unit}".lstrip , date].reject(&:blank?).join(', ')
end


Serializing abstract class over WCF with subclasses in different assemblies

Question: We are using C# and .NET 4 to build an WCF-enabled application. We have a "parent" assembly that implements:
[DataContract]
public abstract class A
{
  //...
}

Then, other "child" assemblies implement subclasses of A, like this:
[DataContract]
public class B : A
{
  //...
}

In another assembly we have some methods that we are trying to encapsulate as WCF services. Some of these methods have a return type of A.
Evidently, child assemblies need to include a reference to the parent assembly in order for derived classes to inherit from class A. The problem arises when WCF seems to demand that we add KnownType attributes to class A to list all its potential subclasses; this would need that the parent assembly where A resides had references to the child assemblies, which would create circular dependencies.
Is there any other way around this? Does WCF really need to know the types of all the potential concrete classes of an abstract class that is being used as a return type? Thank you.
EDIT. We have tried the approach based on KnownTypeAttribute.MethodName, as suggested by some comments. This would allow us to dynamically load the assemblies where the subclasses reside and return the subclasses to WCF on demand. It works when class A is used as a return type, but it doesn't work when it is used as a method parameter; we keep obtaining a "type not expected" WCF error. We'll keep trying approaches.
Comment: You may look at the last answer here: http://stackoverflow.com/questions/2329464/wcf-probem-with-serializing-inherited-types
Comment: @Kangkan: Thank you, sounds interesting.
Comment: I found this http://stackoverflow.com/questions/4140920/how-to-serialize-a-derived-type-as-its-base-type-with-wcf also interesting. This should help you. I have not tried, but seems it works.
Comment: Update here once you follow one of these and get the result.
Answer: You can set the known types when you construct the Serializer which might get you around this issue
http://msdn.microsoft.com/en-us/library/aa344259.aspx
Comment: We are not constructing a DataContractSerializer by hand. Also, and as far as I can see from the link you provide, we would still need to provide a list of known types, so we would still have the circular dependency problem.
Comment: Ah yeah, sorry I did see that you are using WCF. You might have to put the different classes into the same assembly then, im not sure if there is a way around it? It will be interesting to see if Kangkan`s answer works


Show that a certain set is an open set in C[a,b]

Question: I need to show that the set
$$
R_n = \bigg\{f\in C[a,b]: \forall x\in [a, b]\exists h>0 \bigg(\bigg|\frac{f(x+h)-f(x)}{h}\bigg| > n\bigg)\bigg\}
$$
is an open set on the metric space $(C[a,b], d)$, where $C[a,b]$ are all continuous real functions on closed interval $[a,b]$, and the metric $d$ is  $$d(f,g) = \max_{a\le x \le b}|f(x)-g(x)|$$
I tried to solve this problem for hours but couldn't make it... The solution simply says that it can be shown by using the definition of $R_n$ and the compactness of $[a,b]$. I tried to estimate
$$
\bigg|\frac{g(x+h)-g(x)}{h}\bigg| > \bigg|\frac{f(x+h)-f(x)}{h}\bigg| - \bigg|\frac{g(x+h)-f(x+h)}{h}\bigg| - \bigg|\frac{g(x)-f(x)}{h}\bigg|
$$
For a certain $f\in R_n$ , if I traverse all $x\in [a,b]$ I get the corresponding $h=h(x)$ and $K(x) = |(f(x+h)-f(x))/h|$, if I can somehow show that $\sup K(x) > n$ and $\inf h(x) > 0$, I can use the inequality above to construct a valid $\epsilon$, so that the open ball $B(f, \epsilon)$ is contained in $R_n$. However I failed to show this.
Can anyone help solve this problem? Thanks in advance!
Comment: If x=b, wouldn't x+h be out of the function's domain?
Comment: @billy9797 sorry, it should be [a, b-1/n]
Answer: (There is a minor problem in the definition of $R_n$.
You need to choose something like $C[a, c]$ with $c > b$ as ambient space, for otherwise the definition of $R_n$ is not well posed.)
Let $f\in R_n$.
Since $f$ is continuous, the condition in the definition of $R_n$ can be rewritten as:
$$
\forall x\in [a,b]\ \exists h(x) > 0, \ \exists \delta(x) > 0, \exists \epsilon(x) > 0:
\quad
\left|\frac{f(y+h(x))-f(y)}{h(x)}\right| > n + \epsilon(x)\quad
\forall y \in B_{\delta(x)} (x).
$$
Since $[a,b]$ is compact, you can find $x_1, \ldots x_m\in [a,b]$ such that
$$
[a,b] \subset \bigcup_{i=1}^m B_{\delta_i}(x_i),
\qquad \delta_i := \delta(x_i).
$$
Choosing
$$
\epsilon := \min_{i=1,\ldots,m} \epsilon(x_i)
$$
you have that every $g\in C[a,b]$ with $\|g-f\|_\infty < \epsilon$
belongs to $R_n$.
Comment: Thank you very much! I came across the idea that such a $B_\delta(x)$ exists for any $x$ but didn't think about constructing a open cover.


How to get HTTP status answer from GuzzleHttp response by php Laravel?

Question: I develop at php Laravel.
I receiving GuzzleHttp response from Mailgun as Object and can't to get from it the status.
the Object is:
O:8:"stdClass":2:{s:18:"http_response_body";O:8:"stdClass":2:{s:6:"member";O:8:"stdClass":4:{s:7:"address";s:24:"email@example.com";s:4:"name";s:10:"not filled";s:10:"subscribed";b:1;s:4:"vars";O:8:"stdClass":0:{}}s:7:"message";s:36:"Mailing list member has been created";}s:18:"http_response_code";i:200;}

I need just last data pair:
"http_response_code";i:200;
to get it into variable, like:
$http_response_code = 200;
or even just its value.
To get string as I cited above I use
$result_ser = serialize($result);
but yet can't to extract value of variable.
Also I tried this:
$this->resultString .= \GuzzleHttp\json_decode($result_ser, true);
and get error.
Please, explain me , How to get/extract value I needed?
Comment: Can you post your request code?
Answer: To take the response status code you can use the function getStatusCode :
$response = $client->request();

$statusCode = $response->getStatusCode();

while to take the body of response you  can use :
$contents = $response->getBody()->getContents();

Comment: This is a good answer, it can be improved by adding a bit more detail about these functions, perhaps links to the documentation of where these functions should be used. It'll help others when they find this question know why this code works rather than it just works! Thanks and welcome to StackOverflow!
Comment: thank you , sorry i forget to include the link of of guzzlehttp docs http://docs.guzzlephp.org/en/stable/ where you can read throug for a more detailed information
Answer: let's consider your request is something like
 $response = $client->get("https://example.com");
 if ( $object_res->getStatusCode() == 200 ) { // here you are checking your http status code
 }

$object_res->getStatusCode() is the method to get http status code.
refer docs, there is simple example in this page.
Comment: Thanks for ry to help!
Comment: @Vlad is it what you want or I have not got the question correctly?
Comment: Thanks for try to help!
My code is:
`$mgClient = new Mailgun(config('mail.encryption'));
$listAddress = config('mail.listName') . config('mail.listAddressMark') . config('mail.listDomain');
        try {
            $result = '';
            $result = $mgClient->post("lists/$listAddress/members", [
                'address' => $request->email,
................
            ]);
        } catch (Exception $e) { `
As you see, it's POST request.
Are you mean that I can get status code from my $result variable? Like
`$result->getStatusCode()` ?
I'll try right now
Comment: I get error

`Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method stdClass::getStatusCode()`

Should I to 'use' some class or package for correct work of it?
Comment: I suggest that response I get is not an Guzzle but Mailgun object.
Maybe I should to ask the Mailgun support about their response.
Comment: @Vlad yes, you are correct. we need to check mailgun doc instead of guzzle doc.
Comment: @Vlad check this https://stackoverflow.com/questions/38005563 may be this answer will give you some idea.
Answer: I found that 'mailgun/mailgun' package uses its own HTTP client which also uses 'RestClient' and these classes are return stdObject.
In that Object there is property 'http_response_code' containing HTTP response code like 200, 400, 401 etc.
This property accessible by standard way $object->property and it's a solution of my query in this case.
For anybody who will read this question and answers I should to explain one thing that I not cleared in question.
I made request to the Mailgun API for subscribing member to mailing list. The API returns stdObject, not JSON or XML data.
But also there is one more strange thing - stdObject returned when request is successful only. If request fails you'll get just Exception thrown with message and without code. This forced me, if fail, to parse message body instead of get and resolve error code.
Answer: $responseObj->getStatusCode();


Using Composition and Implementation in State Design Pattern

Question: I read this link enter link description here,
to learn State Desing Patern.
interface class:
public interface State {
    void doAction();
}

onState class:
public class TVStartState implements State {

    @Override
    public void doAction() {
        System.out.println("TV is turned ON");
    }
}

offState:
public class TVStopState implements State {

    @Override
    public void doAction() {
        System.out.println("TV is turned OFF");
    }

}

TvContext Class:
public class TVContext implements State {

    private State tvState;

    public void setState(State state) {
        this.tvState=state;
    }

    public State getState() {
        return this.tvState;
    }

    @Override
    public void doAction() {
        this.tvState.doAction();
    }

}

test Class :
public static void main(String[] args) {
    TVContext context = new TVContext();
    State tvStartState = new TVStartState();
    State tvStopState = new TVStopState();

    context.setState(tvStartState);
    context.doAction();

    context.setState(tvStopState);
    context.doAction();

}

Now I have two questions :
1- why TVContext Class implements State and has Composition toghether  ?
is a bug in OO ?
because for example  Cat inherits from Animal class and has_a animal together (in this case).
2-If The final programmer in this TestClass pass context to   context.setState() instead of tvStartState or tvStopState , Program successfully compiles but error in run_time.

For the second question in State Design Pattern,  instead of inheritance, same name method can be used. but int Decoration Design Pattern not.
Comment: Please, no images containing text. If you have an error stack trace, copy and paste it into your question and format using the `{}` button.
Comment: what is the error `Program successfully compiles but error in run_time.`? can you post it here?
Answer:
Why TVContext class implements State and has composition together?

The example is incorrect, TVContext should not implement interface State. From the UML diagram for State Design Pattern we can see that class Context only
compose an attribute that implements interface State.

If the final programmer in this TestClass pass context to context.setState() instead tvStartState or tvStopState , program successfully compiles but errors in run_time.

The reason it compiles is because context is implementing interface State, but it fails in run-time with a java.lang.StackOverflowError because function context.setState() is recursively invoking itself with no exit condition. Removing the interface State from TVContext class fix this issue.
In Decorator Design Pattern the intent is to add new behavior to the Component class. That is why inheritance is used to add new methods to the Component.
In State Design Pattern the intent is to change the behavior of the Context class. For example if we implement it using inheritance with an abstract class instead of the interface the operation on the concrete state classes need to override the operation defined in the abstract class. That is why an interface makes more sense in this case.
Comment: good answer. *"In State Design Pattern the intent is to change the behavior of the Context class"* if its internal state was changed


Why won't my class that returns a list iterate?

Question: Here is my code, I use it to open an excel sheet and then return each row as a list of strings (where each cell is a string). The class returns one list that is filled with as many lists as there are rows in the file. So 50 rows will return 50 lists.
from xlrd import open_workbook

class ExcelReadLines(object):

    def __init__(self,path_to_file):
        '''Accepts the Excel File'''
        self.path_to_file = path_to_file
        self.__work__()

    def __work__(self):
        self.full_file_as_read_lines = []
        self.book = open_workbook(self.path_to_file)
        self.sheet = self.book.sheet_by_index(0)

        for row_index in range(self.sheet.nrows):
            single_read_lines = []
            for col_index in range(self.sheet.ncols):
                cell_value_as_string = str(self.sheet.cell(row_index,col_index).value)
                cell_value_stripped = cell_value_as_string.strip('u')
                single_read_lines.append(cell_value_stripped)
            self.full_file_as_read_lines.append(single_read_lines)

        return self.full_file_as_read_lines

But when I run:
for x in ExcelReader('excel_sheet'): print x

I get the error message:
class is not iterable

Answer: In order for a class to be iterable, it needs to have an __iter__ method.
Consider:
class Foo(object):
    def __init__(self,lst):
        self.lst = lst
    def __iter__(self):
        return iter(self.lst)

example:
>>> class Foo(object):
...     def __init__(self,lst):
...         self.lst = lst
...     def __iter__(self):
...         return iter(self.lst)
...
>>> Foo([1,2,3])
<__main__.Foo object at 0xe9890>
>>> for x in Foo([1,2,3]): print x
...
1
2
3

Your example seems like it would be a good bit better as a generator -- I don't really understand what the need is for a class here:
def excel_reader(path_to_file):
    book = open_workbook(path_to_file)
    sheet = book.sheet_by_index(0)

    for row_index in range(sheet.nrows):
        single_read_lines = []
        for col_index in range(sheet.ncols):
            cell_value_as_string = str(self.sheet.cell(row_index,col_index).value)
            cell_value_stripped = cell_value_as_string.strip('u')
            single_read_lines.append(cell_value_stripped)
        yield single_read_lines

Comment: I've look around and that seems to be the consensus. But I can't understand how to use it to return a list of lists.
Answer: You should look into implementing Python's special iterator methods.
Also, note that you shouldn't name a method __work__ since it uses magic method syntax but isn't actually a real magic method.
Answer: You have a few problems here.

Your code doesn't return anything.  You call __work__ but don't return the value.
Even if it did, that wouldn't help, because returning something from __init__ doesn't make the object be that thing.
You don't want your object to be a list anyway, you just want to iterate over it.

See this question for a simple example of how to write an iterator in Python.
In addition, you shouldn't use double-underscore-sandwich names like __work__ in your code.  That sort of name is by convention reserved for Python-internal use.
Comment: @user1367204 -- To return a value from a function, you need the `return` statement.  And, python doesn't respect values `return`ed from `__init__`.
Comment: I don't understand your first point. I believe that it does return a value. init call the work method, and the work method returns a list.

Also, I would like a list of lists, this way I can sort each list according to an algorithm and put each list into either one bucket or another.
Answer: Unless I'm mistaken, what you're really after is
def first_sheet(fname):
    wb = xlrd.open_workbook(fname)
    ws = wb.sheet_by_index(0)
    for i in xrange(ws.nrows):
        yield ws.row_values(i) # maybe strip 'u''s - but that looks a bit sus... (probably something to do with your `str`)

list_of_rows = list(first_sheet('somefile.xls'))

Then do any transposition using zip if needs be...


Simplification of case-based logistic regression cost function

Question: In Andrew Ng's Coursera Machine Learning class, the cost function for logistic regression is defined as:
$$\begin{align*}
J(\theta) &= \dfrac{1}{m} \sum_{i=1}^m \mathrm{Cost}(h_\theta(x^{(i)}),y^{(i)}) \\[2ex]
\mathrm{Cost}(h_\theta(x),y) &=
  \begin{cases}
    -\log(1-h_\theta(x)) \; & \text{if y = 0} \\
    -\log(h_\theta(x)) \; & \text{if y = 1} \\
  \end{cases}
\end{align*}$$
It is said that this simplifies to:
$$\require{cancel}
J(\theta) = - \frac{1}{m} \displaystyle \sum_{i=1}^m \left[y^{(i)}\log \big(h_\theta (x^{(i)})\big) + (1 - y^{(i)})\log \big(1 - h_\theta(x^{(i)})\big)\right] \\[6pt]$$
How is this simpler? Why are the cases multiplied by $y^{(i)}$ and $1-y^{(i)}$ respectively?
Comment: Re: "Why are the cases multiplied by y(i) and 1−y(i) respectively?" -- what does the expression inside the sum work out to when $y(i)=1$? What about when $y(i)=0$? ... it's not hard to work out.
Answer: The single case formula is simpler in the sense that it can be written on one line.
The implementation may still be more efficient using branching based on the value of $y^{(i)}$ to avoid unnecessary calculation.
$y^{(i)} \in \{0,1\}$, so $y^{(i)}$ and $1-y^{(i)}$ will  evaluate to either $0$ or $1$.
Multiplying a case by $0$ cancels it, and multiplying by $1$ keeps it.
Given:
$$\require{cancel}
J(\theta) = - \frac{1}{m} \displaystyle \sum_{i=1}^m \left[y^{(i)}\log \big(h_\theta (x^{(i)})\big) + (1 - y^{(i)})\log \big(1 - h_\theta(x^{(i)})\big)\right] \\[6pt]$$
$$J(\theta) =
  \begin{cases}
  \displaystyle - \frac{1}{m} \sum_{i=1}^m \left[\cancel{0 \cdot \log (h_\theta (x^{(i)}))} + \cancel{(1 - 0)}\log (1 - h_\theta(x^{(i)}))\right] \quad \text{if $y=0$}\\
  \displaystyle - \frac{1}{m} \sum_{i=1}^m \left[y^{(i)}\log (h_\theta (x^{(i)})) + \cancel{(1-1) \log (1 - h_\theta(x^{(i)}))}\right] \quad \text{if $y=1$}\\
  \end{cases}$$
Which is the same as the original case-defined definition (moving the negation before the $1 \over m$).


how to prove finitely many? which route is easier?

Question: I want to prove that: If $N$ is finitely generated semi-simple $R-$module, then $N$ is a sum of finitely many simple submodules.
I know that if $N$ is a finitely generated $R-$module, then that the following three conditions are equivalent(I have seen its proof before).

$N$ is a sum of simple modules.

$N$ is a direct sum of simple modules.

Given any submodule $M \subset N,$ there exists a unique submodule $M' \subset N$ such that $N = M \oplus M'.$

And any module satisfying these conditions is called a semi-simple module.
Then, to prove my first statement above, I know that I can adjust my proofs either for $2 \implies 1$ in the statement above or for $3 \implies 1.$ I prefer to prove my first statement to prove that: $N$ is a direct sum of simple modules implies $N$ is a sum of finitely many simple modules.
Here is my trial:
Assume that $N$ is a direct sum of simple modules, then, by definition of direct sum, $N$ is a sum of simple modules. But then how can I prove that it is a finite sum? could anyone help me in proving this please?
EDIT:
Maybe proving that every sequence of submodules of $N$ is stationary is a better way of proving my first statement but in that case I also do not see the proof of finitely many.
Any help is appreciated!
EDIT:
Since $N$ is semi-simple by assumption, then $N$ is a direct sum of (possibly infinitely many) simple modules. This infinitely many sum can come from either one of those two cases:
$(1)$ $N$ is infinitely generated i.e. generated by an infinite set. But this case is excluded because by assumption our $N$ is finitely generated.
$(2)$ at least one of the generators of $N$ is infinitely generated, which is not our case because each of the generators is simple i.e., it has only two submodules.
Is that reasoning correct or there is a more succinct proof?
Answer: A direct sum of infinitely many nonzero (right) modules is not finitely generated.
Indeed, if you're given a family of nonzero module $M_\lambda$, for $\lambda\in\Lambda$, and $x_1,\dots,x_n$ are elements of the direct sum thereof, there exists a finite set $F\subseteq\Lambda$ such that
$$
x_1R+x_2R+\dots+x_nR\subseteq \bigoplus_{\lambda\in F}M_\lambda
$$
and this finite direct sum is a proper submodule of the whole direct sum.
Comment: @MathFear Where's the problem? No matter what modules you take the direct sum of, if there are infinitely many of them the direct sum isn't finitely generated. Therefore, *If* a direct sum is finitely generated, it has only finitely many (nonzero) summands. And each of them has to be finitely generated, of course, but simple modules are.
Comment: @MathFear You know that your module is a direct sum of simple modules; since it is finitely generated by assumption, the number of those simple modules has to be finite, as my argument shows.
Comment: Sorry I did not get your idea of the proof I am seeking. Or are you correcting a wrong idea I stated in my question?
Comment: but maybe one of them is infinitely generated? but this is not the case as each of them are simple ..... is that correct?


Arrange Array in C# Issue

Question: I've an array sequence 20,40,60,10,30,50. I want to sort this sequence into the following order 60,40,50,20,30,10 in C#.
Any Help? Thanks in advance☺
Comment: People need to note that the desired output is NOT in descending order. Its a test question which he is not giving all the requirements for.
Comment: Have you tried anything?
Comment: Possible duplicate of [How can I make my Quick Sort Algorithm sort the arrays in both Ascending and Descending order?](http://stackoverflow.com/questions/43803531/how-can-i-make-my-quick-sort-algorithm-sort-the-arrays-in-both-ascending-and-des)
Answer: Very Simple if you have an Array
int[] arr = { 1, 2, 3, 5, 9, 0, 2, 10 };
    arr.OrderBy(a => a);
     arr.Reverse();
in case of list
List<int> abc = new List<int> { 1, 2, 3, 5, 9, 0, 2, 10 };
   abc.Sort();
   abc.Reverse();
Answer: Just use OrderByDescending of LINQ:
var list = new[] {20, 40, 60, 10, 30, 50};
var newList = list.OrderByDescending(x => x);
Console.WriteLine(string.Join(",", newList)); //60,50,40,30,20,10

Answer: You can try this
int[] array = new int[] { 20, 40, 60, 10, 30, 50 };
    Array.Sort<int>(array,
                    new Comparison<int>((element1, element2) => element1.CompareTo(element2)));

to reverse sort
element2.CompareTo(element1)

Comment: @AmitMishra can you provide exact rules for the sorting of the array?
Comment: @AmitMishra How is it working? the output is entirely different from what you have posted: "**into the following order 60,40,50,20,30,10**"
Comment: can you explain in briefly
Comment: MSDN Link :https://msdn.microsoft.com/en-us/library/aw9s5t8f(v=vs.110).aspx
Comment: Sir can you provide me a answer using an example?

Arrange Array in C# Issue


Standard Deviation - Practice Exam Question Error?

Question: I'm taking an online practice exam to prepare for a real test.  This question appeared and I believe I'm answering it correctly but the online practice exam scoring engine keeps telling me I'm wrong, but I'm pretty sure I'm right.  Here's the question:

Use the following information to determine your answers: The typical amount of sleep per night that adults get has a bell-shaped distribution with a mean of 7.5 hours and a standard deviation of 1.3 hours.
About 68% of adults typically sleep between a minimum of ___ hours a night and a maximum of ____ hours a night.
Please enter your answer in the following format and round to the first decimal place: (min_value, max_value)

My answer is $(6.2,8.8)$ but I keep getting it wrong.  Can someone help me understand what I'm doing wrong, or if the auto-corrector is wrong?
Thank you.
Comment: Please add the self study tag.
Comment: @PeterFlom added tag as recommended. Thx.
Comment: it probably asks for a symmetric interval around the mean and I think you're correct considering the simplicity of the context. Try entering decimals with commas (and dots) as well.
Comment: @gunes  thanks for the insight.  On other questions on this same practice exam I've used the same "." and also answered with or without the parenthesis with no luck.  Maybe they have the expected answer entered on the back end, that's my best guess now.
Answer: Comment: As @gunes comments, you have correctly found an interval that satisfies the 68% condition stated in the question---and is also symmetrical about the mean $\mu = 7.5.$  A sensible  choice on your part. In R:
diff(pnorm(c(6.2,8.8), 7.5, 1.3))
[1] 0.6826895

But there are very many other intervals that satisfy the 68% criterion. For example, $(0, 8.1).$
diff(pnorm(c(0,8.1), 7.5, 1.3))
[1] 0.6777938

Perhaps yet another publisher's automated quiz program written by someone who knows very little statistics or probability. Maybe they're a CS guru, a randomly chosen high school basketball coach who sometimes teaches math, or a writer for their advertising materials.
Comment: Fine people all. Just maybe not the best people to be writing statistics quiz software.
Comment: Maligned basketball coaches, advertising writers and CS gurus deserve their advocates too.


Redmine Digest version 2.2.2.stable

Question: I have installed https://github.com/drewkeller/redmine_digest plugin but for the life of me cant set up a cron to run it daily .
Can anyone help a poor boy out ?
root@ip-10-202-39-172:/home/bitnami/apps/redmine/htdocs/bin# rake redmine:send_digest start=1 days=1 project=myproject Rails.env="productio" --trace
(in /opt/bitnami/apps/redmine/htdocs)
** Invoke redmine:send_digest (first_time)
** Execute redmine:send_digest
rake aborted!
string not matched
/opt/bitnami/apps/redmine/htdocs/plugins/redmine_digest/lib/tasks/digest.rake:47:in `[]='
/opt/bitnami/apps/redmine/htdocs/plugins/redmine_digest/lib/tasks/digest.rake:47:in `block (2 levels) in <top (required)>'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `call'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `block in execute'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `each'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `execute'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/opt/bitnami/ruby/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:144:in `invoke'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:116:in `invoke_task'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block (2 levels) in top_level'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `each'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block in top_level'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:88:in `top_level'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:66:in `block in run'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/bin/rake:33:in `<top (required)>'
/opt/bitnami/ruby/bin/rake:23:in `load'
/opt/bitnami/ruby/bin/rake:23:in `'
Tasks: TOP => redmine:send_digest
root@ip-10-202-39-172:/home/bitnami/apps/redmine/htdocs/bin#

root@ip-10-202-39-172:/home/bitnami/apps/redmine/htdocs/bin# rake redmine:send_digest start=1 days=1 project=SSO Rails.env="productio" --trace
(in /opt/bitnami/apps/redmine/htdocs)
** Invoke redmine:send_digest (first_time)
** Execute redmine:send_digest
rake aborted!
string not matched
/opt/bitnami/apps/redmine/htdocs/plugins/redmine_digest/lib/tasks/digest.rake:47:in `[]='
/opt/bitnami/apps/redmine/htdocs/plugins/redmine_digest/lib/tasks/digest.rake:47:in `block (2 levels) in <top (required)>'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `call'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:205:in `block in execute'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `each'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:200:in `execute'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/opt/bitnami/ruby/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/task.rb:144:in `invoke'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:116:in `invoke_task'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block (2 levels) in top_level'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `each'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:94:in `block in top_level'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:88:in `top_level'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:66:in `block in run'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:133:in `standard_exception_handling'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/lib/rake/application.rb:63:in `run'
/opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/rake-0.9.2.2/bin/rake:33:in `<top (required)>'
/opt/bitnami/ruby/bin/rake:23:in `load'
/opt/bitnami/ruby/bin/rake:23:in `'
Tasks: TOP => redmine:send_digest
root@ip-10-202-39-172:/home/bitnami/apps/redmine/htdocs/bin#

Redmine 2.2.2.stable
Default administrator account changed
Attachments directory writable
Plugin assets directory writable
RMagick available (optional)
Environment:
  Redmine version                          2.2.2.stable
  Ruby version                             1.9.3 (x86_64-linux)
  Rails version                            3.2.11
  Environment                              production
  Database adapter                         Mysql2
Redmine plugins:
  openid_fix                               0.1.0
  redmine_digest                           0.2.0
  redmine_googlesss                        0.0.2

Answer: Some other people have reported issues with line 47 in the rake.digest file. You could try the same workaround: https://github.com/drewkeller/redmine_digest/issues/29
Also see https://github.com/drewkeller/redmine_digest/issues/36. Looks like you crossposted your question.

Redmine Digest version 2.2.2.stable


Como Fazer uma máscara para campos no HTML com JavaScript puro?

Question: Estava desenvolvendo um projeto simples, e precisei utilizar máscaras em um determinado formulário. Optei, naquele momento, pelo uso do JQuery com a biblioteca JQuery Mask Plugin.
$(document).ready(function(){
  $('.dinheiro').mask('000.000.000,00', {reverse: true});
});

Mas o JQuery está entrando em conflito com o Angular ao manipular o DOM, então tive que remover o JQuery das dependências.
De que forma posso fazer uma implementação de uma máscara com JavaScript puro?
Comment: Além da implementação nativa, uma alternativa seria o [ngx-mask](https://www.npmjs.com/package/ngx-mask)
Comment: Aqui: https://pt.stackoverflow.com/questions/241620/formatar-valor-em-dinheiro-enquanto-digita-com-javascript-puro
Comment: @renanzin deu certo, mas ainda quero saber o que acontece "por baixo dos panos" em uma máscara
Comment: obs: Esse mask é muito ruim, fora que ele não funciona muito bem pra celular...
Comment: para evitar conflitos, use: `jQuery.noConflict();`
Answer: Usei o regex que estava numa resposta aqui, no link o usuário que respondeu também explica a expressão regular.

function validaCampo(c) {
      let valor = c.value;

      if(/([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/.test(valor)) {
        c.style.backgroundColor = "green";
         } else {
        c.style.backgroundColor = "red";
      }
}
* {
  margin: 0;
  box-sizing: border-box;
}

.validable-field {
  display: block;
  width: 180px;
  margin: auto;
  margin-top: 5%;
}
<input class="validable-field" type="text" onBlur="validaCampo(this)" placeholder="Exemplo: 000.000.000-00">

<input class="validable-field" type="text" onBlur="validaCampo(this)" placeholder="Click para dar onBlur">


Drupal Custom Search Results Per Content Type

Question: So I have a View that is a list of all content on my site. I have an exposed form in a block that is "Search Terms". I have a custom template for my view to customize the results page. I have a couple of content types including "Products" and "Locations".
I'd like the Products to be displayed in a grid format with their corresponding product images and the Locations to be displayed in a list with a corresponding map. What would be the best way for me to accomplish this?
Comment: From the way you have framed the question it sounds like both types of content can appear on the page at once, which makes the question unanswerable. So presumably your exposed form also includes a content type selection?
Comment: Why does having both content types on a single page make this question unanswerable? This scenario exists in 99% of all Drupal sites as it is the base template of all site searches. Check out https://drupal.org/search/site/captcha?f[0]=ss_meta_type%3Amodule. Couldn't this page be customized?
Comment: As I understood it you want both on the same page? You can't normally have a grid and a list in a single result set.
Comment: Or rather, you can, but it tends to look a mess.
Comment: OK, I think I see what you are asking for now.
Answer: Here's a sketch of an answer: in a views template for the result set you will have access to the original results in $view->result. If the view is set up for fields output, and includes all the fields required including content type, you can iterate through it 3 times, each time ignoring entries that have the content type you don't want for that case.
It's quite hard to come up with clean-looking code because of the way that views names the field data, but if you don't mind that, you can use the dpm() function of the Devel module to inspect it then code accordingly.


Can a tuner help to tune my violin in perfect fifths?

Question: I have always used a tuner to tune my violin, but have noticed that the strings are not in perfect fifths (I'm a complete beginner, and I understand perfect fifths to mean that if I play E using my 4th finger on the A string, it will be the same pitch as an open E string). I have always assumed that this is just because of my wonky hearing (I used to be unable to tell the difference between a flat and a sharp), until I came across this post, where in the last paragraph the poster said "but it will probably not tune your instrument with perfect fifths".
Is the poster claim true?
Comment: There's a discrepancy of 2 cents between the twelve-tone equal tempered fifth and a just perfect fifth. This is a very small difference, even for most educated ears. I'd say that your fingering position is most likely the problem, i.e. you're placing your fourth finger on the wrong spot of the keyboard.
Comment: If you're going to try to tune to a perfect fifth, best to do so with the upper string open or on second harmonic and the lower string playing the 3rd harmonic (finger on the string but not pressed down).
Answer: The answers here are mostly wrong, confusing "perfect fifth" with "tuner fifth".  Special string tuners may or may not tune in perfect fifths: no idea.  However, a "straightforward" tuner will display correct pitches according to an equal tempered scale.  And equal tempered fifth is 2 cent short of a perfect fifth.  In order to be able to play double stops without beatings, a violin is tuned to concert pitch on A, and then to perfect fifths from there.  That means that its E string is 2 cents sharp over an equally tempered E, its D string is 2 cents flat, and its G string is 4 cents flat as compared with instruments like a piano.
Fingering with a precision of 2 cents is not realistic: violin players tend to autocorrect their play as well as using vibrato which breaks up the regularity of any beatings, rendering them inobtrusive.
Things to take away from this are: when you are using an equally-tempered tuner, you might want to have your tuning errors lean very slightly to be "too wide" in order to err in the direction of perfect fifths, and when you are tuning by listening for perfect fifths, it is better to stop when the fifths are slightly too small rather than slightly too large, as you will then match with equally tempered instruments better.
With fingering, you won't be able to check for 2 cents of difference: if your fingers can find any sort of grooves or dents they recognize, the fingerboard is due for honing.  Any such irregularities will interfere with proper intonation, vibrato, position shifting and so on.
Answer: Using your tuner, get an open string spot-on in tune. Then finger where you think the fifth is on that string. Chances are, your finger is going to be slightly out, as will be shown on the tuner, if it's a chromatic one. Even an open string tuner should show exactly what note you're fingering.Tuning the open strings to each other is the best way, listening to the 'hard' sounding 5th interval.
Comment: Maybe it's just a personal thing, but I find the sound of a perfect fifth is hard, unharmonious, and lacking anything that I hear in a third or sixth, for example.There's already the same note sounding as a harmonic of the 'root' note, so a p5 doesn't seem to add much in the way of pleasant harmony: thus, hard/harsh - to me.
Comment: What's a "hard" sounding 5th interval?
Answer: If the open string is the first note in the scale, the fifth is the note played by the fourth finger, which is the same note as the next open string up. A perfect fifth is where the ratio of the frequency of the sound waves of the notes is 3:2, and is something you can learn to hear. To hear what the fifth sounds like, play first the A string, then immediately play the E. If you are skilled enough, play both at once.
Inexpensive electric tuners do not have the precision to tune a violin to the exact 3:2 ratio, so players who need that much precision learn to tune by ear. If you've only recently learned to tell the difference between sharps and flats, you may not yet be skilled enough at listening to do that yet.  Get a teacher or an very good player to show you what it sounds like. If you can't tell the difference between close and perfect yet, don't worry about it, and keep tuning to the tuner. Listening is just as much of a skill as playing. Tuning by ear took me about a year to learn to do as well as a cheap tuner, and I still can't beat a high quality tuner.
If you are a beginner, just tune to the electronic tuner. It is definitely close enough for everyday use, especially once you learn to hear what a fifth on the violin should sound like and can finish off your tuning by ear.
The problem with checking your tuning by playing a fingered note is that it is impossible to place your finger precisely enough. You can tune the instrument with the most precise tuner in the world, and it won't solve the problem of misplaced fingers. When things sound off when you play the open E + the fourth finger on the A string, then your finger is probably off by some fraction of a millimeter (or more). What makes it so noticeable is that you are playing the same note on two strings, so any tiny discrepancy is obvious. This is why tuning is always done to open strings on the violin.
Comment: You say that inexpensive tuners don't have the precision to tune a violin to exact 3:2 ratio, but you leave out that the real issue is that tuners usually tune to the equal tempered scale (which most chromatic instruments do employ). On this scale, the 5ths are slightly altered from the 3:2 ratio!
Answer: For years I have used the Korg LCA-120 which customizes the notes so you can adjust for harmonic tuning of the E, A, D, & G.  (E adjusted 2 cents higher, A at 440 Hz, D adjusted 2 cents lower, and G adjusted 4 cents lower.) It also has a focus tune which, if turned on, focuses the total range of +-50 cents to a total range of +-10 cents once you get within 10 cents of the correct note. (BTW the way, the difference between a chromatic and harmonic perfect fifth is 1.95 cents).
THE PROBLEM IS THAT THE LCA-120 is now obsolete, but you can still find them on the market. I have not been able to find a substitute brand that does as good a job.
Having tuned with the LCA-120 for years, I can not say enough about how it has improved my playing.  When I buckled down to superior intonation it was a God send.
The reason is the modern strings are very stable, especially the D'dario Zyex strings which once broken in will stay in tune within a cent, sometimes for days. (ironically it is then the steel E string that is the least stable.)
The main benefit is that if you tune this carefully every time you practice, your fingers can be trained more consistently because you can depend on the same placement on the strings for a particular note over the years.
Those that are willing to listen carefully to one's playing will find a way into really excellent intonation.  The more careful you listen for the nuances the better your intonation will become habituated to precision.  I have been taught by a student of Itzhak Perlman to know every half step and whole step of every piece and strictly apply the knowledge to calculate how to get to every finger placement and every shift, and then vigilantly and consciously focus and refine the correctness and relaxation of each all of the time during practice, and move this into mind/body connection (which is the exact opposite of stage fright which is a blockage between mind and body) by using the trick of being "all ears" to the notes you are about to play.  When you do this right, you will find your body will quickly learn to place your fingers correctly before the next note is played.
BTW really good intonation will not be heard as really good intonation, it will be heard as a beautiful sound.
5/2023
I've moved on, the best solution for tuning in perfect fifths is the StroboClip HD and the StroboPlus HD from Peterson tuners.  Both have many "sweeteners" that cover 60 to 200 different scale adjustments and also you can customize your own which can be downloaded by USB.  Of course, these include non-tempered perfect fifths in the violin and other stringed instrument timings if you want.


Erro ao carregar a library database do Codeiginiter

Question: Estou com o seguinte erro no codeginiter:

A PHP Error was encountered Severity: Error
Message: Call to undefined function mysqli_init()
Filename: mysqli/mysqli_driver.php
Line Number: 135
Backtrace:

Já fui até o php.ini e retirei os comentários do extension=php_mysql.dll , extension=php_mysqli.dll e o coloquei o caminho no extension_dir = "C:/php/ext", alguém que já passou por isso sabe a solução?
Obs: estou tentado hospedar no Apache porque no php cli funciona normalmente
Comment: Se você tiver utilizando WampServer, XAMPP etc. Provavelmente estás alterando o `php.ini` incorreto. Crie um arquivo PHP e executo o código `<?php phpinfo();`. Lá mostrará o arquivo "correto".
Comment: @ValdeirPsr mas em que parte do phpinfo() sei que o apache está unsado?
Comment: basta pesquisar (Ctrl + F) por `php.ini`. O valor fica em `Loaded Configuration File`
Comment: @ValdeirPsr então achei o caminho porém ele aponta para o C:\Window mas lá não tem nenhum php.ini
Comment: Você utiliza algum software como WampServer ou XAMPP?
Comment: @ValdeirPsr então cara consegui resolver lá no httpd.conf na última linha eu coloquei o PhpIniDir + o caminho em que estava instalado o php junto com o php.ini. Mas vlw pela ajuda.
Comment: Responda à sua própria questão. Não deixe aberta. Atrapalha.
Answer: No httpd.conf na última linha eu coloquei o PhpIniDir + o caminho em que estava instalado o php.ini


Left hand thumb position for ukulele

Question: Some people:

place the thumb behind the neck (more freedom for fingers)

some let the neck fall deep between the thumb and index finger, and the thumb is visible above the fretboard

Which position is right for what situation? Can it be changed when playing? And is this possible without a strap?
Answer: Each player's physiology is different - length of fingers/thumb, flexibility, etc. There may, or may not, be a 'standard' way to position, but basically, it's going to be down to individuality, and each player will find his own best method, which will change as the chord shapes change, or when playing only one or two strings. Or when seated or standing.Or how high or low one has the uke. It's pretty well much the same syndrome with guitar playing - there are no right or wrong ways - as long as the product sounds good - just because I put my hand in a particular way doesn't mean my students must do the likewise. Whatever works best for the individual is probably the best answer!
Answer: Here is the answer I got from Peter Forrest:

People tend to play often with the thumb protruding when playing open
  chords like F, C, G when playing near the nut.  I do it myself.  It
  all depends on the next chord that you will be playing and will moving
  that thumb make more effort for one's changes.  When playing up the
  fretboard, the thumb should be behind on full chords.  If you standing
  up while playing, it works better with the thumb behind. You need to
  try to use the thumb behind the fretboard as much as possible.  You
  have to on barred chords.  Look up my video Paris in the '20s.  I
  cannot play the verse without having the thumb behind... but voila.. I
  put the thumb up while playing Fm (near the nut) and I slide up the
  strings.  So, it depends on the chord changes.
Answer: The thumb will tend to be in slightly different places for different chords.  The ideal for me is thumb on the back but the angle of the thumb can change if, for example you are playing an 'inside out' chord like E7 (unless you are using fingers 2,3, and 4). Also, people with different shaped hands might find other ways...  as long as it works for you I guess?

I like to use a strap, to save me having to hold the uke with my left hand, but some prop it on their knee, or use the right elbow to cuddle the uke. (sorry to left handers).

Left hand thumb position for ukulele


Largest eigenvector as the rank-1 approximation

Question: Consider a square real symmetric matrix $A$. The singular value decomposition (SVD) is given as
$A = U\Sigma U^T$,
and it can also be found by minimizing $|A-U\Sigma U^T|$ where $|.|$ is the $l$2 norm, $U$ is constrained to be orthonormal and $\Sigma$ is diagonal, or simply $A=UU^T$ if $U$ is orthogonal.
Now since $A$ is square, real and symmetric, is the SVD the same as the eigenvalue decomposition? I think so.
Now suppose I want to find the rank=1 approximation to A. I can take the first row of $U$ (corresponding to the largest element of $\Sigma$). This is the eigenvector with the largest (absolute) eigenvalue.
Is this the same as minimizing $| A - U_1 U_1^{T} |$ where $U_1$ is a $N$x$1$ row vector?
So is it true that the first eignevector $U_1$ is the solution to
$\arg\min_{U_1} |A-U_1 U_1^{T}|$
Can I simply state this result as a known result in my work?
Answer: In general, the SVD decomposition of a matrix $A$ is $A = U \Sigma V^T$ where $\Sigma$ is diagonal with non-negative entries (the singular values), the columns of $U$ are the eigenvectors of $A^T A$ and the columns of $V$ are the eigenvectors of $A A^T$. If $A$ is symmetric and positive semidefinite (so all the eigenvalues of $A$ are non-negative), then the SVD decomposition of $A$ coincide with the eigenvalue decomposition. If $A$ is symmetric but not necessarily positive semidefinite, the eigenvalue decomposition of $A$ is not the same as the SVD decomposition but quite close:
If you take a basis $(u_1, \ldots ,u_n)$ of eigenvectors of $A$ with $Av_i = \lambda_i v_i$ such that $|\lambda_1| \geq \ldots \geq |\lambda_n|$ then the SVD decomposition of $A$ can be constructed by choosing $U = (u_1 | \ldots | u_n)$ and $V = (\pm u_1 | \ldots | \pm u_n)$ (where you choose $-u_i$ if $\lambda_i < 0$ and $+u_i$ otherwise).
Finally, the matrix $\lambda_1 u_i u_i^T$ is indeed the best rank one approximation of $A$ in the sense that
$$ \lambda_1 u_1 u_1^T = \arg \min_{u,v} |A - uv^T| $$
where $| \cdot |$ is the Frobenius norm. You can read about this (and see the proof) here. It is well-known and you can find many sources if you need to refer to the result.
Comment: Thank you! You mean $u_1 = \arg \min_{u}|A-uu^T|$, right?
Comment: No - A general rank one matrix is of the form $uv^T$ (for which each row is of the form $u_i \cdot v^T$) and not $uu^T$.
Comment: The theorem you are looking for is known as the Eckart-Young theorem (1936) and it says that the truncated SVD is the best low rank approximation for the Frobenius norm. The same truncated SVD is also the best low rank approximation for the spectral norm as well.