VBA Display Collection in a message box - error

Question: I am trying to Pop-up a message something like,
"There are 3 Reports available . They are Today, Yesterday, Day before"

This is the code,
  On Error Resume Next
  For Each a In MonthYear
     arr.Add a, a
  Next

  For i = 1 To arr.Count
     Cells(i, 1) = arr(i)
  Next

MsgBox ("There are " & arr.Count & " Reports available. They are  " & arr &

But it is not working. It says sub or argument not found.
Comment: `On Error Resume Next` is a nice way to shoot yourself in the foot when attempting to debug code. Actually, it's a nice way to shoot yourself in the foot in debugged production code except when used in a _very_ controlled manner.
Comment: You have to specify which element of array you want in `& arr &`. As you want to list them all you need to have a loop that builds it.
Answer: For an array, as it appeared that the OP was using one.  Now that the OP has editted the post to show a collection this method will not work.
I will leave it for future readers for an option with arrays.
MsgBox "There are " & UBound(arr) + 1 & " Reports available. They are  " & Join(arr,",")

Comment: It skips over that part actually. The message box is not popping up.
Comment: It is declared as a collection. My bad. Extremely sorry.
Answer: This is what I came up with:
Option Explicit

Sub TestMe()

    Dim arr     As Variant
    arr = Array("Today", "Yesterday", "DayBefore")

    MsgBox ("There are " & UBound(arr) + 1 & _
            " reports available. They are " & Join(arr, ", ") & ".")

End Sub

Concerning the collection this is one way to transfer the collection to a string:
Option Explicit

Public Sub TestMe2()

    Dim reportsCol  As New Collection
    Dim i           As Long
    Dim textReport  As String

    reportsCol.Add "Today"
    reportsCol.Add "Yesterday"
    reportsCol.Add "The day before yesterday"

    For i = 1 To reportsCol.Count
        textReport = TextReport & " " & reportsCol(i) & _
            IIf(i = reportsCol.Count, ".", ",")
    Next i

    MsgBox textReport

End Sub

The IIf at the bottom decides whether to put a full stop . or a comma ,.
Comment: @Sid29 for the love of everything that's good in this world, **please** rename that variable to something meaningful, e.g. `reportColumns`. And [**drop *Systems Hungarian* notation**](https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/).
Comment: If your IT folks / programmers have tooling such as ReSharper or they're using Visual Studio, that certain boss is unfairly blocking your productivity.
Comment: Wow, what a hopeless ignorant jerk. [VBA is a perfectly fine OOP-capable COM-based language](https://stackoverflow.com/a/31861832/1188513) and FWIW it's a hosted version of VB6, running with the very same VM. And VB6 was the "funny scripting language" everyone was using to compile executables and type libraries 15 years ago. The VM runs p-code, VBA compiles to p-code, and p-code is the pre-.NET equivalent of MSIL or Java's bytecode. This loser has no clue what he's talking about.
Comment: @Mat'sMug - cheer up, it will appear in the near future :)
Comment: This will work if arr is an array. But in my case, it is a collection.
Comment: @Mat'sMug - I suppose that you mean me and not Sid?
Comment: @Mat'sMug Yes sir, will do :) It is so confusing. I started building it as an array and then just changed it to collection, that's why.
Comment: @Mat'sMug - ok, I will edit it here. But in general, once I started like this it is tough to change. My code will become inconsistent.
Comment: @Mat'sMug - now you only need to know a certain boss, who does not allow additional software used in the company and everything will come to its place.
Comment: @Mat'sMug - true, but "the programmers are programmers and I am writing on that funny scripting language that does not even compile" (these are real  words, that I have heard about 4 years ago in a German company. I always laugh when I remember it! :)
Comment: @Vityata oh FFS... he's mistaking VBA for VBScript. WTF does he think 'Debug' -> 'Compile' do?!
Comment: @Mat'sMug will definitely look into that. Thanks:-)
Comment: @Mat'sMug - he meant VBA and he meant compiling the way C# does.
Comment: @Mat'sMug - true but he had his own way of understanding computers... That's why I have separated VBA from the other languages here -
 http://vitoshacademy.com/about


Animate div off and on screen with new info

Question: I have two buttons. When button 1 is pressed a div slides on screen. When button 1 is pressed again it slides off screen. Good.
Now when button 1 is pressed the div slides on. When button 2 is pressed while the div is on screen, the div slides off. I want the second button to slide the div off and slide back on with new information.
What I have right now works fine, but I need the added step where the second button goes off screen and comes back with the new info.
How can I achieve this?

$(document).ready(function() {

  function legendButton(name) {
    var modalLeft = $('#modal').css('left');

    if (modalLeft === "-75px") {
      // Move on-screen
      $('.' + name + '').clone().appendTo('#modal');
      $('#modal').animate({
        left: "0"
      }, 'fast');
    } else if (modalLeft === "0px") {
      // Move off-screen
      $('#modal').animate({
        left: "-75px"
      }, 'fast', function() {
        $('#modal').empty();
      });
    }
  }

  $('.master-legend_faq').off('click').on('click', function() {
    legendButton('red');
  });

  $('.master-legend_video').off('click').on('click', function() {
    legendButton('blue');
  });
});
#modal {
  border: 10px solid #eee;
  padding: 10px;
  position: absolute;
  left: -75px;
  top: 120px;
  max-width: 50;
  z-index: 10;
  background: #fff;
}

    Contains FAQ's

    Contains Video

  red stuff

  blue stuff

View on JSFiddle
Answer: Here's an alternative method. It uses a CSS transition to animate a CSS transform based on a class that is toggled by jQuery.

$(function () {

  var $modals = jQuery('.modal');

  jQuery('#legend a').on('click', function (e) {

    e.preventDefault();

    var name = jQuery(this).data('modal'),
        $target = jQuery('.modal_' + name);

    $modals.not($target).removeClass('open');
    $target.toggleClass('open');

  });

});
.modal {
  position: absolute;
  border: 10px solid #eee;
  padding: 10px;
  left: 0;
  background: #fff;
  transform: translateX(-100%);
  -webkit-transition: left 1s ease-in-out;
  transition: all .5s ease-in-out;
}

.modal.open {
  transform: translateX(0);
}

Contains FAQ's

Contains Video

FAQ stuff

VIDEO stuff

Some relevant CSS3 properties are not supported in IE<=9 or Opera Mini.
Check browser compatibility:
CSS3 Transitions
CSS3 2D Transforms
Answer: I added a snippet inside the .master-legend_video click event handler, which looks at what happens when you click it. First we analyze whether or not the expected text is there, and if so we then add another animation to follow the existing one. In order to show the text, we wait for the animation to complete.
Keep in mind you can easily customize this functionality to better suit your end implementation, so do play around with it.

$(document).ready(function () {

      function legendButton(name) {
        var modalLeft = $('#modal').css('left');

        if (modalLeft === "-75px") {
          // Move on-screen
          $('.' + name + '').clone().appendTo('#modal');
          $('#modal').animate({
            left: "0"
          }, 'fast');
        } else if (modalLeft === "0px") {
          // Move off-screen
          $('#modal').animate({
            left: "-75px"
          }, 'fast', function () {
            $('#modal').empty();
          });
        }
      }

      $('.master-legend_faq').off('click').on('click', function () {
        legendButton('red');
      });

      $('.master-legend_video').off('click').on('click', function () {
        legendButton('blue');

        // Handle red to blue transition
        if ($("#modal").text().indexOf("red") > 0) {
          $("#modal").animate({
            left: "0px"
          }, {
            complete: function () {
             $(".blue").clone().appendTo('#modal');
            }
          });
        }
      });
    });
#modal {
  border: 10px solid #eee;
  padding: 10px;
  position: absolute;
  left: -75px;
  top: 200px;
  max-width: 50;
  z-index: 10;
  background: #fff;
}

      Contains FAQ's

      Contains Video

    red stuff

    blue stuff

I would like to add that there are many good things you can do to improve your current code, such as relying less on JavaScript and more on CSS. However I did work with your implementation and I hope it is as close to what you are looking for as possible. Let me know if you have any questions.
Comment: As this is more of a learning experience for me to become more comfortable with javascript, I'm curious what you mean by more CSS. Can you elaborate? Are you talking about CSS3?
Comment: @user2766423 correct CSS or CSS3 is what I mean, when using JS to do visual/animated things you need to have a rule of thumb: can it be done with CSS first? That has a lot to do with which tool is better for what you want to achieve. See the below answer and how they have used CSS transitions instead, it results in a better, simpler and more modular implementation; in short it's a suggested best practice. However for your own learning experience playing around isn't bad either, just keep in mind your best JS practices


How to view DbgPrint messages from a Windows filesystem minifilter?

Question: I am trying to run one of the minifilter samples from Microsoft provided here: https://github.com/Microsoft/Windows-driver-samples/tree/master/filesys/miniFilter/passThrough
I don't know what this minifilter is supposed to do (documentation isn't great), but for starters, if I can just see the output from a DbgPrint() statement, I'll be happy.  While running Sysinternals DebugView as admin, I did fltmc load passthrough and fltmc unload passthrough, but did not see any output from the filter.  I know that at least the function corresponding to the unload feature in the code has a DbgPrint() message:
PT_DBG_PRINT( PTDBG_TRACE_ROUTINES,
("PassThrough!PtUnload: Entered\n") );

Am I supposed to see these messages? If so, how?  If not, how can I debug minifilter development?
PS: I did define the Registry key suggested here: https://www.danclarke.com/debugview
Answer: You can do it from the debugger attached using the:
ed nt!Kd_DEFAULT_Mask 0x8

Or check this link out as you can also enable it from the registry.
Answer: Make sure you've enabled 'Capture Kernel' under the Capture drop-down menu, instead of 'Capture Global Win32' which is what the article you linked us to mentions.
As for the File-System Mini-Filter device driver sample you linked us to, there's plenty of documentation surrounding development of filter-manager drivers available over at MSDN.
If you go into driver development blind with the Microsoft samples, you can't really expect to understand how it all works with a click of a finger... It is very different to user-mode development, you'll be starting from the bottom again.
Answer: Look at PT_DBG_PRINT macros in the source code:
#define PT_DBG_PRINT( _dbgLevel, _string )          \
(FlagOn(gTraceFlags,(_dbgLevel)) ?              \
    DbgPrint _string :                          \
    ((int)0))

There is a condition that checks gTraceFlags variable. By default gTraceFlags is 0. So just set that variable to enable DbgPrint, for example:
ULONG gTraceFlags = PTDBG_TRACE_ROUTINES;


Proguard with code 1 issue

Question: I have recently seen proguard use, I am using google analytics services in my application.
In eclipse I have -- proguard-project.txt
wherein I have added below lines:
-keep class android.support.v4.** { *; }
-dontwarn android.support.v4.**
-keep public class com.google.** {*;}

In project properties I have uncommented line :-
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

I want to implement proguard in my project but struck with error code 1 with following console output:
[2013-12-03 00:49:21 - superman-v4-1] Warning: com.google.tagmanager.LRUCache$1: can't find superclass or interface android.util.LruCache
[2013-12-03 00:49:21 - superman-v4-1] Warning: com.google.tagmanager.LRUCache: can't find referenced class android.util.LruCache
[2013-12-03 00:49:21 - superman-v4-1] Warning: com.google.tagmanager.LRUCache: can't find referenced class android.util.LruCache
[2013-12-03 00:49:21 - superman-v4-1] Warning: com.google.tagmanager.LRUCache: can't find referenced class android.util.LruCache
[2013-12-03 00:49:21 - superman-v4-1] Warning: com.google.tagmanager.LRUCache: can't find referenced class android.util.LruCache
[2013-12-03 00:49:21 - superman-v4-1] Warning: com.google.tagmanager.LRUCache: can't find referenced class android.util.LruCache
[2013-12-03 00:49:21 - superman-v4-1] Warning: com.google.tagmanager.LRUCache$1: can't find referenced class android.util.LruCache
[2013-12-03 00:49:21 - superman-v4-1] Warning: com.google.tagmanager.LRUCache$1: can't find referenced class android.util.LruCache
[2013-12-03 00:49:21 - superman-v4-1] Warning: com.google.tagmanager.LRUCache$1: can't find referenced class android.util.LruCache
[2013-12-03 00:49:21 - superman-v4-1] Warning: there were 9 unresolved references to classes or interfaces.
[2013-12-03 00:49:21 - superman-v4-1]          You may need to specify additional library jars (using '-libraryjars').
[2013-12-03 00:49:21 - superman-v4-1] java.io.IOException: Please correct the above warnings first.
[2013-12-03 00:49:21 - superman-v4-1]   at proguard.Initializer.execute(Initializer.java:321)
[2013-12-03 00:49:21 - superman-v4-1]   at proguard.ProGuard.initialize(ProGuard.java:211)
[2013-12-03 00:49:21 - superman-v4-1]   at proguard.ProGuard.execute(ProGuard.java:86)
[2013-12-03 00:49:21 - superman-v4-1]   at proguard.ProGuard.main(ProGuard.java:492)

Thanks in advance.
Answer: You should build against a target SDK that contains the missing class android.util.LruCache; in this case android-12 or higher. Simply change the build target in your project.properties file or build.gradle file to that recent version.
You can still specify a different minSdkVersion and a different targetSdkVersion in your AndroidManifest.xml file.
Answer: Maybe try this config as noted in this SO question
-keep class com.google.android.gms.analytics.**
-keep class com.google.analytics.tracking.**
-dontwarn com.google.android.gms.analytics.**
-dontwarn com.google.analytics.tracking.**

Proguard with code 1 issue


How do I alter the entity type class?

Question: In Drupal 8 you can load an entity with:
$node = \Drupal::entityManager()->getStorage('node')->load(123);

This looks for the entity definitions and finds that node is defined by Drupal\node\Entity\Node - so (I guess) Drupal\node\NodeStorage will instantiate a new Drupal\node\Entity\Node instance.
What I'd like to achieve is subclassing Drupal\node\Entity\Node and being able to instantiate this subclass when it's appropriate. For example if I have a node bundle article, there would be a class:
namespace Drupal\my_module\Entity\Article;
class Article extends Drupal\node\Entity\Node {
}

And I'd call:
$node = \Drupal::entityManager()->getStorage('node_article')->load(123);

And the return would be my Article subclass.
I can achieve this by creating a new entity type and wiring it back to another existing entity definitions, for example the node-article example would be this class:
namespace Drupal\my_module\Entity;
use Drupal\node\Entity\Node;
/**
 * @ContentEntityType(
 *   id = "node_article",
 *   label = @Translation("Content"),
 *   bundle_label = @Translation("Content type"),
 *   handlers = {
 *     "storage" = "Drupal\node\NodeStorage",
 *     "storage_schema" = "Drupal\node\NodeStorageSchema",
 *     "view_builder" = "Drupal\node\NodeViewBuilder",
 *     "access" = "Drupal\node\NodeAccessControlHandler",
 *     "views_data" = "Drupal\node\NodeViewsData",
 *     "form" = {
 *       "default" = "Drupal\node\NodeForm",
 *       "delete" = "Drupal\node\Form\NodeDeleteForm",
 *       "edit" = "Drupal\node\NodeForm"
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\node\Entity\NodeRouteProvider",
 *     },
 *     "list_builder" = "Drupal\node\NodeListBuilder",
 *     "translation" = "Drupal\node\NodeTranslationHandler"
 *   },
 *   base_table = "node",
 *   data_table = "node_field_data",
 *   revision_table = "node_revision",
 *   revision_data_table = "node_field_revision",
 *   translatable = TRUE,
 *   list_cache_contexts = { "user.node_grants:view" },
 *   entity_keys = {
 *     "id" = "nid",
 *     "revision" = "vid",
 *     "bundle" = "type",
 *     "label" = "title",
 *     "langcode" = "langcode",
 *     "uuid" = "uuid",
 *     "status" = "status",
 *     "uid" = "uid",
 *   },
 *   bundle_entity_type = "node_type",
 *   field_ui_base_route = "entity.node_type.edit_form",
 *   common_reference_target = TRUE,
 *   permission_granularity = "bundle",
 *   links = {
 *     "canonical" = "/node/{node}",
 *     "delete-form" = "/node/{node}/delete",
 *     "edit-form" = "/node/{node}/edit",
 *     "version-history" = "/node/{node}/revisions",
 *     "revision" = "/node/{node}/revisions/{node_revision}/view",
 *   }
 * )
 */
class Article extends Node { }

// Results my Article sub type.
$node = \Drupal::entityManager()->getStorage('node_article')->load(123);

This works fine (as much as I can see); however, it smells. It adds a new entity type, which is not true, and might cause other troubles in the future.
How do I define a subclass for an entity bundle so that loading the entity would return an object of that class?
Comment: I'm not sure you can provide a different entity class per bundle; you can use `hook_entity_type_alter()` to make the change more cleanly, but I don't know how you'd limit that to a specific bundle
Comment: Thank you Clive - that looks a promising hook to investigate!
Answer: Create a new class in your module that extends \Drupal\node\Entity\Node.
use Drupal\node\Entity\Node as BaseNode;

class MyNode extends BaseNode {
}

Implement hook_entity_type_build().
use Drupal\Core\Entity\EntityTypeInterface;

/**
 * @param EntityTypeInterface[] $entity_types
 */
function my_module_entity_type_build(&$entity_types) {
  if (isset($entity_types['node'])) {
    $entity_types['node']->setClass('Drupal\my_module\Entity\MyNode');
  }
}

Remember to rebuild the cache.
It works fine when loading nodes via the entity type manager service and the node storage. It even works when you just use Drupal\node\Entity\Node::load($nid) thanks to the fact that this load() function it is just a static wrapper for the entity type manager service call provided by the Entity class which is extended from the Node class.
// Part of Entity class for reference
abstract class Entity implements EntityInterface {
  /**
   * Loads an entity.
   *
   * @param mixed $id
   *   The id of the entity to load.
   *
   * @return static
   *   The entity object or NULL if there is no entity with the given ID.
   */
  public static function load($id) {
    $entity_manager = \Drupal::entityManager();
    return $entity_manager->getStorage($entity_manager->getEntityTypeFromClass(get_called_class()))->load($id);
  }
}

This also works fine with the soon-to-be-removed entity_load_multiple() function, so I guess this covers all standard use cases for loading nodes.
Of course, if your module does this and another module does the same, you'll have a problem, but I guess it's not common scenario, and it makes sense only for very specific use cases.
Comment: Sorry but no :) The question was to have a different class per *bundle*. You're changing the class for all bundles of the entity type node. That's not the same.
Comment: Yeah. https://www.drupal.org/node/2570593 is one of the issues that I referenced but forgot to actually link to in my answer.
Comment: @Berdir, your right :( ... Having classes per bundle means that a entity storage for node would have to be extended too so that it's load methods could be overridden to produce those per bundle classes. Which basically is one huge headache.
Comment: I have implemented hook_entity_type_alter to set custom class. It works too.
Comment: When I attempt this method I get a 'Drupal\Component\Plugin\Exception\PluginNotFoundException: The "node" entity type does not exist.' message. I'm using the ablecore_entity_type_build function in my .module file. And I have my AbleNode.php in /src/Entity/AbleNode/ folder
Comment: Nevermind I got it. I needed to put it in Plugins/Node
Answer: From Drupal 9.3, there is support for entity bundle classes included in core.
So now you can subclass your entity bundles as much as you like without needing any contrib modules.
The core change record is extensive, but basically this:
use Drupal\mymodule\Entity\BasicPage;

function mymodule_entity_bundle_info_alter(array &$bundles): void {
  if (isset($bundles['node']['page'])) {
    $bundles['node']['page']['class'] = BasicPage::class;
  }
}

Comment: This is the right answer since 9.3.
Answer: I experienced the same issue and decided to create a module that alter the entity type class of Drupal entities via the plugin system. Currently it supports altering the Node, User and File entity classes. When altering the Node entitiy you are able to alter the type class per node bundle.
Check out the module description for an example:
https://www.drupal.org/project/entity_type_class
The module uses hook_entity_type_alter() to set a handler class on entities that you provide in your plugin annotation.
Answer: This module also gives you real bundle classes - https://github.com/amcgowanca/discoverable_entity_bundle_classes
Answer: This is an old question, but the real answer should be:
If you need different behaviour across bundles, then you should be using different entity types, not different bundles.
Custom Content Entities are 1st class citizens in D8.  In fact we estimate that it takes about 30 minutes to get a new custom content entity to the level that node is (which really just comes down to adding the Form UI to get the nice side panel, and the alias/revision fields.)  This doesn't include adding the translation pages, but that isn't that much more.
If you haven't seen it, take a look at the Drupal Console's generate:custom:entity features.

How do I alter the entity type class?


Determining constant values from 3 equations

Question: I have the following three equations:
$$\begin{align*}
k_1 + k_3 &= 0\\
k_1e^{k_2(0.1)} + k_3 &= 1\\
k_1e^{k_2(1)} + k_3 &= 100
\end{align*}$$
How do you go about solving for values $k_1$, $k_2$, and $k_3$?
Obviously $k_1$, $k_3$ are related in the fact one must be the negative of the other to make the first equation true. All that is given in lecture is "Mathematica determines the constants of these three equations to be...", it doesn't actually explain how to solve them yourself.
Thanks.
Comment: Yep, sorry about that.
Comment: Yes, the function is $f(x) = k_1e^{k_2(x)} + k_3$ where x ranges from 0 to 1.
Comment: so is the last equation written correctly?
Comment: Yes it is. Why do you think it isn't?
Comment: Because your last comment makes it look like there should be a plus sign between $k_1$ and the exponential in the last two equations.
Comment: My bad again. No plus sign.
Answer: $k_3=-k_1$.
$k_1e^{(1/10)k_2}-k_1=1$ yields $k_1={1\over e^{(1/10)k_2}-1}$
$k_1e^{k_2}-k_1=100$ yields $k_1={100\over e^{k_2}-1}$
So we have $${1\over e^{(1/10)k_2}-1}={100\over e^{k_2}-1}$$ to solve for $k_2$.
$e^{k_2}-1=100(e^{(1/10)k_2}-1)$
Let $Q=e^{(1/10)k_2}$. Then $Q^{10}-1=100Q-100$, $Q^{10}-100Q+99=0$.
One solution of this equation is $Q=1$, which leads to $k_2=0$, which we must reject --- it slipped in when we divided by $e^{k_2}-1$.
That leaves a polynomial of degree $9$. There is in general no closed form formula for the solution of such an equation. Mathematica uses numerical methods, for example, the calculus-based Newton's Method.
Comment: In the book it gives the answers as

$k_1 = 2.10999$
$k_2 = 3.87937$
$k_3 = -2.10999$

All these are said to be irrational numbers.
Comment: OK. Your point?
Comment: How were they gotten?
Comment: Presumably, by numerical methods, such as Newton's Method.


Qual seria o código para simular o inverso do tab

Question: Tenho um projeto em que eu abro um form dentro do outro, e com isso nos forms secundários o evento OnKeyDown em vez de ir para ir para os do forms secundários estão indo para o form Principal, mais se eu aperto tab na telas segundarias ele vai normal, então resolvi simular o tab.
Sei que o Código para simular keybd_event(VK_TAB, 0, 0, 0); mais como fazer para simular o inverso?
procedure TfrmAndamento.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin

  if ((key=VK_RETURN) or (key=VK_DOWN)) and not((Sender is TMemo) or (Sender is TComboBox) or (Sender is TDBComboBox) or (Sender is TDBGrid))
  then
    selectNext(ActiveControl,True,True); // <= aqui o sistema da erro pois o ActiveControl sempre vem o objeto que não era o correspondente
end;

Comment: Sinceramente não entende o por que de fechar a pergunta?
"... mas se a sua pergunta tem a ver com..."
- um problema específico de programação - OK
- um algoritmo de software
- ferramentas comuns entre programadores, quando aplicadas no desenvolvimento de software
- problemas práticos e bem definidos que dizem respeito ao desenvolvimento de software - OK
dúvidas teóricas sobre conceitos e práticas aplicadas ao desenvolvimento de software - OK
- Não é um pergunta duplicada  - OK
Não tem dizendo que tem que todos os pontos acima.
Comment: É o costume no Stack Overflow...
Answer: Você quer simular o Shift + Tab? Experimente dessa forma:
  keybd_event(VK_SHIFT, 0, 0, 0);               // pressiona o Shift
  keybd_event(VK_TAB, 0, 0, 0);                 // pressiona o Tab
  keybd_event(VK_TAB, 0, KEYEVENTF_KEYUP, 0);   // solta o Tab
  keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0); // solta o Shift

Espero que ajude
Comment: vou testar aqui. Valeu!
Comment: Velho funcionou mesmo. Muito top!! Valeu


If a sequence converges in $L^2$ and we compose every function with a non-singular function, does it still converge?

Question: Let $F\colon (0,1)\rightarrow (0,1)$ be a non-singular function with respect to the Lebesgue measure $\mu$ (so $\mu\sim\mu \circ F$). Let $\{ f_n : n \in \mathbb{N} \} \subset L^{2}([0,1])$ be a sequence of simple integrable functions and $f\in L^{2}([0,1])$ such that $f_n\to f $ in the $2$-norm. Is it correct that also $f_n\circ F\to f\circ F$ ?
If not, what are the conditions on $F$ such that this implication is correct?
Comment: By $\{f_{n}/n\in N\}$ do you mean $\{f_{n}:n\in\mathbb{N}\}$?
Comment: What does $\mu \sim \mu \circ F$ mean?
Comment: μ∼μ∘F means that for every measurable set A, $\mu (A)=0$ iff $\mu (F(A))=0$
Comment: Yes, I mean the natural numbers, I couldn't right the natural numbers symbol for some reason.
Comment: @Davide: since Arnold stated it as **iff**, I think the two are equivalent. But I am not sure that "iff" is in fact what he wants.
Answer: Here are some counterexamples. Consider the functions
$$
f_n(x)=x^{-a(n)}-x^{-b(n)},\qquad F(x)=x^2.
$$
Assume that $0<a(n)<\frac14$, $a(n)\to\frac14$, $0<b(n)<\frac14$ and $b(n)\to\frac14$. Then,
$$
\|f_n\|_2^2=\frac1{1-2a(n)}+\frac1{1-2b(n)}-\frac2{1-a(n)-b(n)}\to0,
$$
hence $f_n\to f$ in $L^2$ with $f=0$. Furthermore, $f\circ F=0$ and $f_n\circ F(x)=x^{-2a(n)}-x^{-2b(n)}$, hence
$$
\|f_n\circ F\|_2^2=\frac1{1-4a(n)}+\frac1{1-4b(n)}-\frac2{1-2a(n)-2b(n)}.
$$
Let $A(n)=1-4a(n)$ and $B(n)=1-4b(n)$, then $\|f_n\circ F\|_2^2=C(n)$ with
$$
C(n)=\frac1{A(n)}+\frac1{B(n)}-\frac4{A(n)+B(n)}=\frac{(A(n)-B(n))^2}{A(n)B(n)(A(n)+B(n))}.
$$
If $nA(n)\to\alpha$ with $\alpha>0$ and $nB(n)\to\beta$ with $\beta>0$, $\|f_n\circ F\|_2^2=\gamma n+o(n)$ with $\gamma\ne0$ as soon as $\alpha\ne\beta$, in which case $f_n\circ F$ does not converge in $L^2$ to $f\circ F=0$ since $\|f_n\circ F\|_2^2\to\infty$.
Likewise, if $n^2A(n)=1+o(1/n)$ and $n^2B(n)=1+c/n+o(1/n)$, $\|f_n\circ F\|_2^2\to c^2/2$ hence $f_n\circ F$ does not converge in $L^2$ to $f\circ F=0$ although the sequence $(f_n\circ F)$ converges pointwise to $0$ and is bounded in $L^2$.


How to get collision detection to work between rectangles?

Question: My code is not getting any errors, however it is not behaving as I expect it to.
The problem is here:
if bomb_rect.colliderect(pacman_rect)==True:
    print("hello")

The print("hello") should only execute if the two rectangles collide, however it executes every time no matter what.  I'm not sure what I've overlooked.
Edit:
Sorry for the confusion. My apologies, let me explain it again, I have two pictures imported, one is a bomb, one is Pacman. When the two pictures collide, "hello" will be printed. The source of error is not bomb_rect.colliderect(pacman_rect) rather it is where the image is set. The coordinates for the bomb is set random. and Pacman will appear at (0,0). However when I move the Pacman around, I find that even though that the bomb image is set elsewhere, there is still a invisible bomb image set at (0,0). Because when I move Pacman image further than (0,0), "hello" stops printing.
import pygame,sys,random
from pygame.locals import *
pygame.init()
blue=(0,250,0)
red=(255,0,0)
black=(0,0,0)

screen = pygame.display.set_mode((1080, 720))

bomb=pygame.image.load("bomb2.bmp")
bomb_rect = bomb.get_rect()

pacman=pygame.image.load("pacman.png")
pacman_rect = pacman.get_rect()

pygame.display.set_caption('game')
background=pygame.Surface(screen.get_size()).convert()
background.fill((255,255,255))

randBombX = random.randrange(0,screen.get_width()-200)
randBombY = random.randrange(0,screen.get_height()-200)
bomb_rect.move(randBombX ,randBombY)

dir_x = 0
dir_y = 0
clock = pygame.time.Clock()
moving=True
while moving:

    clock.tick(20)
    screen.blit(background, (0,0))

    pacman_rect.move_ip(dir_x, dir_y)
    screen.blit(pacman, pacman_rect)
    screen.blit(bomb,(randBombX ,randBombY))
    pygame.display.flip()

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            quit()
        if e.type == KEYDOWN:
            if e.key == K_ESCAPE:
                moving = False
                quit()
            if e.key == K_LEFT:
                if dir_x ==0 and dir_x >=0:
                    dir_x-=10
                if dir_x == 10:
                    dir_x-=20
                dir_y=0
            if e.key == K_RIGHT:
                if dir_x == 0 and dir_x <=0:
                    dir_x+=10
                if dir_x == -10:
                    dir_x+=20
                dir_y=0
            if e.key == K_UP:
                if dir_y ==0 and dir_y <=0:
                    dir_y -=10
                if dir_y == 10:
                    dir_y -=20
                dir_x=0
            elif e.key == K_DOWN:
                if dir_y ==0 and dir_y >=0:
                    dir_y +=10
                if dir_y == -10:
                    dir_y +=20
                dir_x=0

    if pacman_rect.left < 0 or pacman_rect.right >= screen.get_width():
        dir_x *= -1
    if pacman_rect.top < 0 or pacman_rect.bottom >= screen.get_height():
        dir_y *= -1
    if bomb_rect.colliderect(pacman_rect)==True:
        print("hello")

Comment: @MarcusMüller No, it's not [codereview.se] material.  This code does not work as intended and code that does not work as intended is explicitly off-topic on [codereview.se].  In fact, while this may or may not be a good question, it's **well** within the scope of [so].  The user's code isn't working as intended and is asking for assistance fixing it.  If this isn't on-topic for [so], I don't know what is.
Comment: codeReview material, not really stackOverflow. Try checking whether your checks work. That might be a case for unit tests.
Comment: @nhgrif Good point; Michael, please accept my apologies. However, I still think it's not clear what you're asking, because you don't explain what you've tried to do to pin down where things go wrong; if you could do that and come up with the problems you've encountered, I think you'd give us a question that is far better to answer.
Comment: @MarcusMüller I've edited his question--I think it's more clear now what is being asked.
Comment: Sorry for the confusion. My apologies, let me explain it again, I have two pictures imported, one is a bomb, one is pacman. When the two pictures collide, "hello" will be printed.  The source of error is not   bomb_rect.colliderect(pacman_rect)  rather it is where the image is set. The coordinates for the bomb is set random. and Pacman will appear at (0,0). However when I move the pacman around, I find that even though that the bomb image is set elsewhere, there is still a invisible bomb image set at (0,0). Becasue when i move pacman image further than (0,0), "hello" stops printing.
Comment: Please **edit** your question and say what you just wrote here in the question. In the meantime, I'll just delete three fourths of my answer :/.
Answer: if bomb_rect.colliderect(pacman_rect)==True:

is a bit redundant; a == True is the same as a for boolean values (if a is True, a==True is True; otherwise, it's False). But that shouldn't change the behaviour of your program.
But:
            if dir_x ==0 and dir_x >=0:
                dir_x-=10

Just happens if dir_x == 0 (maybe you're confusing and and or? Either way, one of the conditions is included in the other). You have more of these ifs in your code; I'm not quite sure what they should have been doing, but as far as I can tell, that might alter the behavior of your game from what you're expecting.
Comment: Thanks for pointing that out, It should be `or`.  I also do have a ton of if statements, i will try to fix that.
I think the problem is `bomb_rect.move(randBombX,randBombY)` here, i am not sure if the image is set randomly.


Pan Gesture making view jump away from finger on drag

Question: I'm having a problem when trying to drag a view using a pan gesture recognizer. The view is a collectionViewCell and the dragging code is working, except when the drag starts the view jumps up and to the left. My code is below.
In the collectionViewCell:
override func awakeFromNib() {
    super.awakeFromNib()
    let panRecognizer = UIPanGestureRecognizer(target:self, action:#selector(detectPan))
    self.gestureRecognizers = [panRecognizer]
}

var firstLocation = CGPoint(x: 0, y: 0)
    var lastLocation = CGPoint(x: 0, y: 0)
    @objc func detectPan(_ recognizer:UIPanGestureRecognizer) {
        switch recognizer.state {
        case .began:
            firstLocation = recognizer.translation(in: self.superview)
            lastLocation = recognizer.translation(in: self.superview)
        case .changed:
            let translation  = recognizer.translation(in: self.superview)
            self.center = CGPoint(x: lastLocation.x + translation.x, y: lastLocation.y + translation.y)
        default:
            UIView.animate(withDuration: 0.1) {
                self.center = self.firstLocation
            }
        }
    }

The first image is before the drag starts, the second is what happens when dragging up.
Comment: I believe that your .changed case shouldn't be using self.center.
Comment: @xTwisteDx What should I use instead?
Comment: Actually, just use translation instead of the last location + translation. Try that.. Sorry, don't have XCode atm so I can't test. I think what actually might be happening is you're modifying your set last location and then adding a translation. Notice the view goes up and to the left. That indicates that it's overcalculating something.
Comment: @xTwisteDx Ah! I figured it out. Your first guess was right, I should've been updating the frame.origin.y and frame.origin.x not the center. Thank you!
Answer: You're using self.center instead of using self.frame.origin.x and self.frame.origin.y then later you're setting your translation and adding it to the lastLocation.
Effectively what's happening is that your view is calculating the position changed from the center of the view, as if you were perfectly dragging from that location and then translating + lastLocation. I'm sure just by reading that you're aware of the issue.
The fix is simple.
self.frame.origin.x = translation.x
self.frame.origin.y = translation.y

The difference is the starting calculation with the translation. Origin will grab the x/y position based on where the touch event begins. Whereas the .center always goes from the center.


Macromedia Fireworks 6.0

Question: I understand this is an old technology, but I have been using it forever and own the software so I can't really change. I just installed Fireworks 6.0 on a Windows 7 box and even thought I can use the keyboard to get to my tools I can't actually CLICK any of my tools. It is the strangest thing I have ever seen. Could this be a Windows 7 issue because I've installed this product countless times on Windows XP machines and I can't ever remember this happening....HELP!
Answer: The issue with using Fireworks 6 ended up being even more bizarre than I originally thought. On my new laptop running Windows 7 I can not click to anything in my toolbox HOWEVER when I put Fireworks on my second monitor I can click everything in my toolbox. I found this out quite by accident.
Answer: I had an issue with old fireworks on windows 7 where it would not save preferences, one of the fixes was to enable compatibility mode and set it to run as administrator, you can do this by right clicking on the fireworks icon.
Hope that helps this problem too.

Macromedia Fireworks 6.0


Why Operator overloading behaves so strange

Question: Hello Friend the output of the below program is so strange. I am not getting the reason.
#include <iostream>
using namespace std;

class xyz
{
    private:
    int ab, cd;
    public:
    xyz()
    {

    }
    xyz(int i, int j)
    {
        ab = i;
        cd = j;

    }
    xyz operator+(xyz);
    void show()
    {
        cout << ab << " ....  "<< cd;
    }

};
xyz xyz :: operator +(xyz ob)
{
    xyz temp;
    temp.ab = ab + temp.ab;
    temp.cd = cd + temp.cd;
    return temp;
}

int main()
{
   // xyz xy, yz;

   xyz xy(2, 3);
   xyz yz(4, 5);
    xy = xy + yz;

    xy.show();
    return 0;
}

Comment: Did you try running it in a debugger? Or are **we** the debugger?
Comment: In addition to the solutions below I would also initialise the member variables in the default constructor:

xyz() : ab(0),cd(0) {}
Comment: @Neal:Yes I did debug the code particularly temp.ab = ab + temp.ab;
    temp.cd = cd + temp.cd; the code behaves strange
Comment: The real question is, why did it take 0.343 seconds to run?
Answer: Copy&paste error?
This
temp.ab = ab + temp.ab;
temp.cd = cd + temp.cd;

should be
temp.ab = ab + ob.ab;
temp.cd = cd + ob.cd;

Answer: In the operator+(), the xyz temp; is uninitialised and contains whatever garbage happened to be in that location.
Answer: xyz xyz :: operator +(xyz ob)

You don't use the ob object whatsoever.
Answer: The temp object was just created initialized with random values and codeis just adding to it.
xyz xyz :: operator +(xyz ob)
{
xyz temp;
temp.ab = ab + ob.ab;
temp.cd = cd + ob.cd;
return temp;
}

output:
6..8


php call matlab

Question: I am using php to build a website that can calculate some convex programming. However, when I tried to connect php and matlab, I can execute matlab and some of its command, but I cannot run any matlab functions.
I am using SSH, Windows 7, Matlab R2012a. The following are some of my observation:

I cannot execute any matlab function(function in .m file) via php, but I can run simple command such as cd, 3*3 by matlab via our php code. I also try to run matlab in UNIX using SSH. I can successfully run both matlab function and command.
One more thing is that when I cd in php calling matlab, it shows a directory (/misc/uac_std/fyp/y13/fyp_dt/public_html/) which is different from the normal directory (/uac/std/fyp/y13/fyp_dt/public_html)
In php, every time I run matlab, I have this warning message - Check directory permissions.Warning: failed to create prefere nce directory /root/.matlab/R2012a. I have searched in google for it and try to make directory manually to create .matlab/R2012a in the home directory (cd~), but it did not help.
When running matlab in both SSH and php, I found that we run different version of matlab. When I run it in SSH, the version is R2009a. When php, the version is R2012a. I do not know whether it is related to our problem or not, but it's just strange. And also, the matlab I use in my college is R2011b...

Here is my php code:
<code>if(isset($_POST['filepath'])) {

$filename  = $_POST['filepath'];
    $command="/usr/local/bin/matlab -nodisplay -nosplash -r \"test()\"";
    $output=shell_exec($command);
    print "$output\n";
}
</code>
Can someone help me?
Answer: You could create an input file for Matlab. Basically the same technique as http://www.danpearce.co.uk/php_and_matlab, but use PHP to write the input file and then parse the output file from Matlab.
Comment: I followed http://www.danpearce.co.uk/php_and_matlab at the beginning. But exec() in php even cannot invoke matlab. Therefore I use shell_exec() to run matlab and some simple command like cd, disp(),etc, but i can't run any function in matlab (.m file). i think it relate to the warning message: Check directory permissions.Warning: failed to create prefere nce directory /root/.matlab/R2012a, some permission problem. Beacuse I can run matlab function via SSH without this warning message.

php call matlab


Making a upper bound for the integral of integrable functions

Question: I am proving something about uniform integrable families of functions and I need to prove something that seems easy but I stucked, it says:
Let be $(X,S,\mu)$ a measurable space, $g$ integrable and $\epsilon>0$ so exists $\delta>0$ s.t. If $E\in S$ with $\mu(E)<\delta$ then $\int_{E}|g|d\mu<\epsilon.$
Answer: You're trying to prove that the measure induced by $|g|$ is absolutely continuous.
Given $\epsilon >0$, there is some simple function $\phi = \sum_{i=1}^n a_i \chi_{A_i}$ such that $0\leq \phi\leq g$ and $\int \phi \geq \int g - \frac{\epsilon}2$
Note that
$$\begin{align}
\int_{E} g &= \int_E (g-\phi) + \int_E\phi\\
&\leq \int (g-\phi) + \sum_{i=1}^n a_i \mu(E\cap A_i)\\
&\leq \frac{\epsilon}2 + n\cdot \max  a_i \cdot \mu(E)
\end{align}$$
Therefore $\delta = \frac{\epsilon}{2n\max a_i}$ fits the bill.
Comment: Thank you, yes I am attempting to make bounds for a family of integrales where the domain of integrations is variable.
Comment: Good luck in your endeavors


jquery if statement and .each, if statement runs unexpectedly

Question: I'm having an issue where an if statement triggers unexpectedly. I'm creating a transition between two images on click. After the transition ends I add a class to the body so some content appears and disappears. I want to reverse the transition by adding a class to the body, then moving the image back into place.
However, when I run the following code (I've omitted the code that defines the offsets). The first transition works fine – running the code in the first if statement then adding class 'expand' to the body. But on the next click to transition back, the class 'expand' is removed from the body, the transition on the images is run, but then 'expand' is added back to the body (the first if statement gets run after the transitions happen).
How would I prevent the initial if statement from executing, and adding 'expand' back to the body, on the second click/transition?
Thanks for your help!
$('.picture-item').click(function(){

if (!$('body').hasClass('expand')) {
  var length = $('.match').length;

  $('.match').each(function(i) {
    // get the data value for the equivalent pictures
    var pictureMatch = $(this).data('image');

    $(this).find('.picture-item-background').css({ '-webkit-transform':'translate('+offsetLeft+'px, '+offsetTop+'px) scale('+offsetScale+')'});
    if(length == i+1){
      $('.match').find('.picture-item-background').on('transitionend webkitTransitionEnd oTransitionEnd', function () {
          $('body').addClass('expand');
      });
    }
    i++;

  });
}

if ($('body').hasClass('expand')) {
  $('body').removeClass('expand');
  $('#minimized').on('transitionend webkitTransitionEnd oTransitionEnd', function () {
    $('.picture-item-background').css({'-webkit-transform':'translate(0px,0px) scale(1)'});
  });
}

return false;
event.stopPropagation();

});

Comment: I don't know that the `if` statement is your problem.  You've bound an event handler that you're not removing.  It's going to run each time the event completes successfully.  It's likely that when you complete the transition back the event fires and the class is added.
Comment: You could try jQuery's `.one` method instead of `.on`.  The event handler fires at most one time and the removes itself.  [jQuery .one](http://api.jquery.com/one/)
Comment: @asafreedman That sounds like what's happening! Could you explain a bit how I'd go about removing it?
Comment: I've done a couple things which have resolved the issue, but it's still unclear to me exactly why it did. I separated the click event into 2 click events, in hopes I wouldn't erroneously trigger the first `if` statement. This still triggered adding the class "expand" back to the body. I then removed the redundant checks for `transitionend` (`webkitTransitionEnd oTransitionEnd`) and this seems to have fixed the issue.
Comment: I'm glad you solved it but I don't there there was too much wrong with what you had.  There are a few different ways you could probably do what you want.  I'd still look into checking out jQuery's `.one` method, though.
Comment: @asafreedman thanks for your help. I tried using `.one` and still ran into the same issue until i removed  `webkitTransitionEnd oTransitionEnd`. Perhaps I was implementing it wrong. I'm going to keep trying the feedback I get until I can get a better understanding of what exactly is happening.
Answer: At a quick glance, it look like you simply need an else in your code:
$('.picture-item').click(function(){

  if (!$('body').hasClass('expand')) {
    // your code
  } else {   // get rid of if ($('body').hasClass('expand')) {
   // the rest of your code
  }
  return false;
  event.stopPropagation();
});

That way only one section of the code will fire on each click. As of now, if it doesn't have the class you run the first section of code which adds the class.  The next section of the code will always fire because you have already added the class.
Comment: thanks for the feedback. are you saying if both `if` statements return false it will ignore the conditions of the `if` statement and run the first one it comes across?
Comment: The first thing you do is check if the body doesn't have a class of `expand`.  Then you do a whole bunch of stuff.  Then you check if it does have `expand`.  The second `if` seems to be the same as just using an `else` there instead.  Not sure if that is clearer or not....
Comment: i think that is clearer. however, if my second `if` statement is the same as an `else` statement, i don't think it would solve the issue? currently it seems that the code in both if statements are getting executed regardless of the body's class. wouldn't changing it to an `else` statement just have the same result? sorry if i'm misunderstanding...
Comment: If I understand your code correctly, the `body` will always come out of your top loop with a class of `expand`.  Eventually, as you loop through the `.match` elements, one of these elements will meet all of your internal criteria.  When it does it adds the `expand` class.  Your second `if` statement will then always pass and run the second set of code.  By replacing the second `if` statement with an `else` either top set of code will run or the bottom set but not both.  I created a [fiddle] (http://jsfiddle.net/j90vj66y/1/).  It won't work because there is no HTML but you can see the code.


Executar jQuery em onclick de botão

Question: Como chamar o jQuery direto no onclick do botão?, por exemplo:
<input type="button" id="btnteste" onclick="$("#IDdoTextBox").spectrum("set", $("IDdoCampo").val());" />

E não funciona, não retorna erro nem nada. Aliás, no próprio Visual Studio já fica em vermelho como código errado.
A maneira abaixo funciona, porém como falei não quero, visto que vai ser criado tudo dinamicamente em ASP.NET

Executar jQuery em onclick de botão


basis for the splitting field of $x^3 - 3$ over the rationals

Question: Let $F$ be the splitting field of $x^3 - 3$ over the rationals. Find a basis for $F$ as a vector space over $\mathbb{Q},$ and prove your answer is correct.
I think that the roots of the polynomial $x^3 - 3$ are $\sqrt[3]{3}, \sqrt[3]{3}(-1 + i\sqrt{3})/2,$ and $\sqrt[3]{3}(-1 - i\sqrt{3})/2.$ From here I would know that $F = \mathbb{Q}(\sqrt[3]{3}, \sqrt{-3}).$ Would that mean that the basis of $F$ is $\{1, \sqrt[3]{3}, \sqrt{-3}\}?$
Are any of these ideas correct and how far away am I from a proof?
Answer: It is a basis as a vector space, not a set of generators as a ring. This means you are allowed only to add them and multiply them with a rational number when making linear combinations: not multiply them with each other.
Actually, what can be proven is that the basis has $6$ elements, and you can take as a basis: $1, \sqrt[3]{3}, \sqrt[3]{9}, \sqrt{-3}, \sqrt{-3}\sqrt[3]{3}, \sqrt{-3}\sqrt[3]{9}$. You need to prove that the splitting field is generated by those elements, and that they are linearly independent.
The first statement is easy, and basically comes from the fact that product of any two elements from the above (purported) basis is a linear combination of elements of the same set.
As for linear independence, if $\alpha+\beta\sqrt[3]{3}+\gamma\sqrt[3]{9}+\delta\sqrt{-3}+\epsilon\sqrt{-3}\sqrt[3]{3}+\zeta\sqrt{-3}\sqrt[3]{9}=0$, $\alpha,\beta,\ldots,\zeta\in\mathbb Q$, then by making the real and the imaginary parts equal to $0$ you have:
$$\alpha+\beta\sqrt[3]{3}+\gamma\sqrt[3]{9}=0$$
and
$$\delta+\epsilon\sqrt[3]{3}+\zeta\sqrt[3]{9}=0$$
Now, the first equality implies $\alpha=\beta=\gamma=0$ because $x^3-3$ is the minimal polynomial of $\sqrt[3]{3}$ over $\mathbb Q$ (it is irreducible by Eisenstein criterion for $p=3$), so no polynomial $\alpha+\beta x+\gamma x^2$ would have a zero in $\sqrt[3]{3}$, unless $\alpha=\beta=\gamma=0$. Similarly, $\delta=\epsilon=\zeta=0$.
Answer: Nop. That splitting field has dimension $\;6\;$ over the rationals, not $\;3\;$ . Take
$$\zeta:=e^{2\pi i/3}=\frac12\left(-1+\sqrt3\,i\right)$$
then the roots of the cubic polynomial are $\;\sqrt[3]3,\,\sqrt[3]3\,\zeta\,,\,\,\sqrt[3]3\,\zeta^2\;$ , and the splitting field of $\;x^3-3\in\Bbb Q[x]\;$ is $\;\Bbb Q(\sqrt[3]3,\,\zeta)\;$ , with dimension
$$[\Bbb Q(\sqrt[3]3,\,\zeta):\Bbb Q]=[\Bbb Q(\sqrt[3]3)(\zeta):\Bbb Q(\sqrt[3]3)]\cdot[\Bbb Q(\sqrt[3]3):\Bbb Q]=2\cdot3=6$$
since $\;x^2+x+1\;$ is the minimal polynomial of $\;\zeta\;$ over $\;\Bbb Q(\sqrt[3]3)\;$ . (Check all this!)


Diophantine equation $x^2+101^2y^2=2z^2$

Question: I tried find solutions in integers to the equation
$$x^2+101^2y^2=2z^2$$
and I believe there doesn't exist one, but I keep missing how to prove it. I tried Looking square residue and  similar, but haven't managed to find the proof. Any tip will help.
Comment: There is a solution. You can use this formula.  https://math.stackexchange.com/questions/1513733/solving-a-diophantine-equation-of-the-form-x2-ay2-byz-cz2-with-the-co/1514030#1514030
Answer: Notice that $101$ is a prime.
There are two cases:
$1)$ If $101\nmid z$, then $x^2\equiv 2z^2\pmod{101}$, $(x\cdot z^{-1})^2\equiv 2\pmod{101}$ (modulo multiplicative inverse).
But $101$ is a prime of the form $8k+5$, so this congruence/equivalence has no solutions by Quadratic Reciprocity.
$2)$ If $101\mid z$, then $101\mid x^2$, by Euclid's lemma $101\mid x$.
Let $x=101a$, $z=101b$, $a,b\in\mathbb Z$.
$a^2+y^2=2b^2$. This equation has infinitely many different integer solutions. This equation is in this Math.SE question with answers.


Does 'aggregate and compress CSS files' actually use gzip?

Question: Under performance settings in my D7 site, I have "Aggregate and compress CSS files" enabled.
When I run YSlow, I get this:

Grade F on Compress components with gzip. There are 4 plain text
  components that should be sent compressed:

/files/css/css_CKoWqiBj9gVXhPuDSnNphuEB0b0J2To76x0pX0EGqn4.css
/files/css/css_5lmdLBQE3741385dmh2zZ_gO_fPyq-62r9KkuUzfIH0.css
/files/css/css_UIg6lj2uEi5H1zubqecd1x6N7_ejFWRiwKYJ_qrEmOQ.css
/files/css/css_oYatxLY13v2flmA_6hUfSrbPmK_x8KS-tOsczLXYqqo.css

This suggests that the aggregated CSS files aren't being gzipped by Drupal?
Answer: There is a difference.  You are seeing aggregated (ie, concatenated) and minified CSS when you tick that option on the performance page.
That YSlow report is talking about the webserver sending the results compressed responses the wire.  I honestly can't remember if there is a Drupal option for output compression as I always use mod_deflate rules to do this.
Typically, I add the rules directly to the Apache config for my whole server (so I don't have to worry about core updates nuking my .htaccess file).  Lately, I have been using the rules from HTML5 Boilerplate:
<IfModule mod_deflate.c>
  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # HTML, TXT, CSS, JavaScript, JSON, XML, HTC:
  <IfModule filter_module>
    FilterDeclare   COMPRESS
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/html
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/css
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/plain
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $text/x-component
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/javascript
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/json
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/xhtml+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/rss+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/atom+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/vnd.ms-fontobject
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/svg+xml
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $image/x-icon
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $application/x-font-ttf
    FilterProvider  COMPRESS  DEFLATE resp=Content-Type $font/opentype
    FilterChain     COMPRESS
    FilterProtocol  COMPRESS  DEFLATE change=yes;byteranges=no
  </IfModule>

  <IfModule !mod_filter.c>
    # Legacy versions of Apache
    AddOutputFilterByType DEFLATE text/html text/plain text/css application/json
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE text/xml application/xml text/x-component
    AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml
    AddOutputFilterByType DEFLATE image/x-icon image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype
  </IfModule>
</IfModule>

Note that this works on MIME type, and not file extensions, so more respones from Drupal will get compressed.
Answer: As MPD says the options in the performance screen only concatenated and minify the files.
To also Gzip you should turn it on in your Apache config or .htaccess
<IfModule mod_deflate.c>
  <FilesMatch ".(js|css|html|php|txt)$">
    SetOutputFilter DEFLATE
  </FilesMatch>
</IfModule>

Answer: Just came across this while looking for something else. I too wondered if the gzip versions of my css files were being served. I posted my findings on this here:
https://drupal.org/node/2162911
Hopefully it'll help anybody coming across this (and people can comment on its accuracy or otherwise).


Changing ipv6 netmask and gateway on running interface

Question: I am trying to change the netmask and gateway of a running ipv6 interface.
On ipv4, I can simply do something like:
ifconfig eth0 netmask 255.255.255.0 gateway 18.104.22.168

How would I do this with ipv6?
I have tried several ways without any success:
ifconfig eth0 inet6 netmask 112 gateway xxxx:xxxx:xxxx:xxxx::

How does the correct syntax look like?
Answer: ifconfig(8) (provided by net-tools) has been obsoleted by ip(8) (in iproute or iproute2).
Some reasons to stop using ifconfig have been nicely summarized here.
For you use case, and according the ip-address(8) manpage, setting the netmask in CIDR notation would be:
ip addr change xxxx:xxxx:xxxx:xxxx::/112 dev eth0

And the ip-route(8) manpage describes how to set the default gateway:
ip -6 route add default via xxxx:xxxx:xxxx:xxxx:: dev eth1

Comment: your line only ADDS an IP to an interface. It does not change the ip that has already been set. I wanted to just change the netmask of the existing IP.
Comment: You are right, I have corrected the command.


Conditional probability in a Pakistani cricket tournament

Question: As a part of an assignment, I am facing a problem in following question (pretty long one)
In a national-level cricket tournament, 3 teams from 3
different cities Lahore, Islamabad and Karachi participated. Team
Lahore is the defending champion (i.e., they were the winners of
the previous year's tournament). The policies of the tournament
stated that teams of Islamabad and Karachi (other than the
defending champion) would play a match (Round-1) consisting of 2
games. The statistics tell us that Islamabad will beat Karachi with
probability 0.7. If none of the teams win both the matches in
Round-1, then Lahore would be declared as the winners again. If
any of the team wins both the matches in Round-1 than it would
compete with team Lahore in another match (Round-2) of 2 games
and would have to defeat Lahore in both the games to win the title
of championship. If Lahore wins the 1st game of Round-2, the 2nd game would not be played and
the tournament would conclude. We also know that Lahore will win from Islamabad with
probability 0.5 and from Karachi with probability 0.6. Now, considering that all the matches are
independent and end with a win/lose result (i.e., no match is a draw):
a. Find the probability that Round-2 will be required
b. Find the probability that Islamabad will win Round-1
c. What is the probability that Lahore will remain the champions for this year as well
d. Given that Round-2 is played, what is the conditional probability that:
i. Islamabad survives the Round-1
ii. Lahore remains the champion
e. Given that Round-2 is played with just one game, find the probability that Islamabad was
the winner of Round-1
I have been been able to solve (I think) parts a, b, c and i of part d but I have no clue on how to attempt ii part of d and part e. I am posting my solution in the question because I think they are all related and I also think that If I did earlier parts correctly, remaining parts would have been done without trouble. Let me post my solution without further discussion.
Proposed Solution:
Let's first define the required events
Ii = {Islamabad wins from Karachi in ith game}  P(Ii) = 0.7
Ki = {Karachi wins from Islamabad in ith game}  P(Ki) = P(Iic) = 0.3
Li = {Lahore wins from Islamabad} P(Li) = 0.5   P(Lic) = 0.5
Lk = {Lahore wins from Karachi} P(Lk) = 0.6 P(Lkc) = 0.4
R2 = {Round 2 is required or played}        P(R2) = ?
IR1 = {Islamabad wins/survives round 1} P(IR1) = ?
KR1 = {Karachi wins/survives round 1}   P(KR1) = ?
Lc = {Lahore remains the champion this year}    P(Lc) = ?
O = {Round 2 is played with just one game}
P(IR1| R2) = ?
P(Lc | R2) = ?
P(IR1| O) = ?
a) Find the probability that Round 2 is required? P(R2) = ?
We know that round 2 is only required when either Islamabad wins both matches or Karachi wins both matches. We can write this as following
P(R2) = P(I1). P(I2) + P(K1). P(K2)
= (0.7) (0.7) + (0.3) (0.3)
P(R2)   =  0.49 + .09 = 0.58
b) Find the probability that Islamabad wins Round 1? P(IR1) = ?
We know that Islamabad wins/survives round 1 if and only if it wins both matches from Karachi and its probability can be modeled as
P(IR1) = P(I1). P(I2)
P(IR1) = (0.7). (0.7) = 0.49
c) What is the probability that Lahore remain the champions of this year as well? P(Lc) = ?
Lahore can remain the champion if round 2 is not played OR Islamabad wins Round1 and loses from Lahore in first match OR Islamabad wins Round 1 and wins from Lahore in first game and loses from Lahore in second game OR Karachi wins Round 1 and loses from Lahore in game 1 OR Karachi wins Round 1 and wins from Lahore in 1st game and loses from Lahore in 2nd game. This statement can be modeled in the form of following equation
P(Lc) = P(R2c) + P(IR1). P(Li) + P(IR1). P(Lic). P(Li) + P(KR1). P(Lk) + P(KR1). P(Lkc). P(Lk)
=   (0.42) + (0.49). (0.5) + (0.49). (0.5). (0.5) + (0.09).(0.6) + (0.09). (0.4) . (0.6)
=  0.42 + 0.245 + 0.1225 + 0.054 + 0.0216
P(Lc) =  0.8631
d) Given that the Round 2 is played, what is the conditional probability that
i- Islamabad survives the Round 1   P(IR1| R2) = ?
ii - Lahore Remains the Champion  P(Lc| R2) = ?
i)
We know that by Baye's rule we can write
P(IR1| R2) = P(R2 | IR1) . P(IR1) / P(R2)
We also know that if Islamabad wins round 1, round 2 has to be played i.e
P(R2| R1) = 1, So
P(IR1| R¬2) = (1) . (0.49) / 0.58 = 0.8448
ii)
P(Lc| R2) = P(R2| Lc) P(Lc) / P(R2)
In the above equation, we have P(Lc) = 0.8631 and P(R2) = 0.58 but we don't know the value of P(R2| Lc) and  I have no idea how to approach this problem
e) Given that Round 2 is played with just one game, find the probability that Islamabad was the winner of Round 1? P(IR1 | O) = ?
P(IR1| O) = P(O | IR1) P(IR1) / P(O)
I have no idea how to approach this problem either.
Any help is highly appreciated
Answer: OK, let's tidy up all the words…

Islamabad beats Karachi with probability 0.7
Lahore beats Islamabad with probability 0.5
Lahore beats Karachi with probability 0.6
In round 1, if neither Islamabad nor Karachi win both games, Lahore remains champion
In round 2, the winner of round 1 must win both games to become champion, else Lahore remains champion (the tournament stops early if Lahore wins the first game)

…and construct a probability fen (tree) out of it.
<code>      (L)
       ^
    2*.7*.3     /-.4*.4-> (K)
       |        |
----R1-+-.3*.3->+--else-> (L)
       |   K    R2
       \-.7*.7->+-.5*.5-> (I)
           I    |
                \--else-> (L)
</code>
Each + represents a branching point, with I, K and L standing for Islamabad, Karachi and Lahore respectively. Letters in brackets denote winners and expressions on each arrow denote the probability of that arrow being followed from the branch point it starts from.
The solutions for parts (a), (b), (c) and (d)(i) are correct. Here are the solutions for the remaining parts.

(d)(ii) If round 2 is played, what is the probability that Lahore remains champion?

There are exactly two ways Lahore can remain champion if the tournament proceeds to round 2:

If Islamabad progresses (0.49) but doesn't win the two games required ($1-0.5^2=0.75$)
If Karachi progresses (0.09) but doesn't win the two games required ($1-0.4^2=0.84$)

Hence the answer to this part is $0.49\times0.75+0.09\times0.84=0.4431$.

(e) If round 2 is played, but only for one game, what is the probability that Islamabad won round 1?

Again, there are exactly two ways for this to happen:

Islamabad wins round 1 (0.49), then loses the next game (0.5)
Karachi wins round 1 (0.09), then loses the next game (0.6)

From the start of round 1, the probability of the first case happening is $0.49\times0.5=0.245$, while that of the second is $0.09\times0.6=0.054$. Now think of these probabilities as shares in a reduced event space where round 2 is played for only one game; the share of the first case, where Islamabad wins, is $\frac{0.245}{0.245+0.054}=0.8194$ (to 4 decimal places) of the total. This is the answer to part (e).
Comment: Thanks a lot @Parchey Taxel. it makes perfect sense. Can we somehow model the above equations in form of Baye's rule. I am basically confused where to use Baye's rule, LOTP and Tree structure?
Comment: Some people use trees to visualise branching probabilities, and I favour them quite a lot (really, it's up to personal preference). The law of total probability (which I used) can naturally be seen in such a tree, and is therefore suited for events that happen in sequence (like the cricket tournament here). The Bayes/Price theorem is better suited for events that can happen in parallel, like rates of cancer in people over 65.
Comment: Thanks man! can yo have a look at following question of mine http://math.stackexchange.com/questions/1929285/a-troublesome-counting-problem


How to print a one2many field values in qweb report in Odoo?

Question: I am trying to print a one2many field values one by one separated by comma,

Attendees:

How can i achieve this and also wanted to print values separated by comma?
Answer: Try this code :
<t t-foreach='o.matp' t-as='value'>
      <t t-esc="value.empname"/>,
</t>

Comment:
Comment: Thank you very much Jainik patel
Comment: Jainik , table outer borders are not visible ? any idea on that ?
Comment:  how to give substitue value to display on the qweb , suppose i want to display '-' if o.nxt_mt does not have a value ?
Answer: You can define a function in your parser of qweb report and call that function from report, which returns a comma separated list of values to your report.
Comment: Hardik Patadia, yes i agree, Thank you very much


How to prove statement about sum

Question: We have such sum: $$\sum_{n=1}^{\infty}\frac{(-1)^{(n+1)}}{n^p}, 0<p<1$$
How to prove that sum is between 1/2 and 1?
Comment: construct a function f (p) this is a continuous monotone function bounded by it's end points
Answer: Let $ \quad f(x) = 1/x^{p} \quad \colon \{ x \ge 1 \,, \space 0 \lt p \lt 1 \} \space\Rightarrow\space 1/x \lt 1/x^{p} \lt 1  $
 $ \Rightarrow \quad f^{\prime}(x) = -p/x^{p+1} \lt 0 \space\Rightarrow\space f^{\prime\prime}(x) = p(p+1)/x^{p+2} \gt 0 \space\Rightarrow\space f(x) \space $ is convex
$$
\begin{align}
& \\
& \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^{p}} = 1 + \sum_{n=2}^{\infty} \frac{(-1)^{n+1}}{n^{p}} = 1 + \sum_{n=1}^{\infty} \frac{(-1)^{n+2}}{(n+1)^{p}} = 1 - \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{(n+1)^{p}} \Rightarrow \\
& \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{(n+1)^{p}} = 1 - \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^{p}} \Rightarrow \small \sum_{n=1}^{\infty} \left[ \frac{1}{(2n)^{p}} - \frac{1}{(2n+1)^{p}} \right] = 1 - \sum_{n=1}^{\infty} \left[ \frac{1}{(2n-1)^{p}} - \frac{1}{(2n)^{p}} \right] \\
\end{align}
$$
$$
\begin{align}
& \\
& \because \space 2n \lt 2n+1 \Rightarrow \frac{1}{2n} \gt \frac{1}{2n+1} \Rightarrow \frac{1}{(2n)^{p}} \gt \frac{1}{(2n+1)^{p}} \Rightarrow \frac{1}{(2n)^{p}} - \frac{1}{(2n+1)^{p}} \gt 0 \Rightarrow \\
& \sum_{n=1}^{\infty} \left[ \frac{1}{(2n)^{p}} - \frac{1}{(2n+1)^{p}} \right] = \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{(n+1)^{p}} = 1 - \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^{p}} \gt 0 \Rightarrow \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^{p}} \color{red}{\lt 1} \\
\end{align}
$$
$$
\begin{align}
& \\
& \because \space f(x) \space \text{convex} \space\Rightarrow\space f(x) \space \text{midpoint convex} \space\Rightarrow\space \small f \left( \frac{x_{1} + x_{2}}{2} \right) \le \frac{f(x_{1}) + f(x_{2})}{2} \\
& \text{Let} \space \small x_{1} = 2n - 1 \,, \space x_{2} = 2n + 1 \normalsize \Rightarrow \small f \left( \frac{2n - 1 + 2n + 1}{2} \right) = f(2n) \le \frac{f(2n - 1) + f(2n + 1)}{2} \normalsize \Rightarrow \\
& \frac{1}{(2n-1)^{p}} + \frac{1}{(2n+1)^{p}} \ge \frac{2}{(2n)^{p}} \quad\Rightarrow\quad \frac{1}{(2n-1)^{p}} - \frac{1}{(2n)^{p}} \ge \frac{1}{(2n)^{p}} - \frac{1}{(2n+1)^{p}} \space\space\Rightarrow \\
& \sum_{n=1}^{\infty} \left[ \small \frac{1}{(2n-1)^{p}} - \frac{1}{(2n)^{p}} \normalsize \right] \ge \sum_{n=1}^{\infty} \left[ \small \frac{1}{(2n)^{p}} - \frac{1}{(2n+1)^{p}} \normalsize \right] \Rightarrow \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^{p}} \ge 1 - \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^{p}} \Rightarrow \\
& 2 \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^{p}} \ge 1 \Rightarrow \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n^{p}} \color{red}{\ge 1/2} \\
\end{align}
$$

How to prove statement about sum


Calculating difference between max and min date for the specific value in pandas

Question: I have the dataframe with max and min date and the value('price') - the values can be grouped by third column (let's say 'category'). How can the difference between price between max and min date be calculated using Pandas for each of the categories? Do I need groupby for that or it can be achieved using index?

So that it will be 783.44 for category A and 5.08 for category B
Thanks!
Comment: Please put your sample dataframe as text, not an image, and add expected output
Comment: provided it so I hope it is clearer now
Answer: Use:
<code>print (df)
        date    price category
0 2018-06-03  7632.09        a
1 2018-06-03   123.29        a
2 2018-04-05  6848.65        a
3 2018-04-05   118.21        a

df2 = (df.groupby(['category', 'date'])['price']
         .agg(['max','min'])
         .add_prefix('_')
         .eval('_max - _min')
         .reset_index(name='diff'))
print (df2)
  category       date     diff
0        a 2018-04-05  6730.44
1        a 2018-06-03  7508.80
</code>
Comment: I think you can also add the first version with sort_values() and 'last'-'first' it is also very clear :)


Error Handling in Python3 (os.system)

Question: In Python, I am calling sub files from main python file.
In all sub python files, I have included try and except block.
In main file, I need the sub files to be executed in the order I have mentioned below.
Is there a way to stop executing os.system("python SubFile2.py") statement, if any error is caught in os.system("python SubFile1.py") statement?
And also I need to get the error details in the main python file.
This is the code snippet of main file:
import os
import sys

print("start here")
try:
    print('inside try')
    os.system("python SubFile1.py")
    os.system("python SubFile2.py")
    os.system("python SubFile4.py")
except:
    print("Unexpected error:")
    print(sys.exc_info()[0])
    print(sys.exc_info()[1])
    print(sys.exc_info()[2])
finally:
    print('finally ended')

Thanks in advance
Comment: do you want your main process to be exited as well when an error encounters in x subfile?
Comment: yes main process should be exited
Comment: Ok, Please check my answer then. You should consider using `subprocess` though.
Answer: You should consider using [subprocess][1] It's not recommended to use os.system if you want to catch the exception and end another process, Because os.system() indicates a failure through the exit code of the method. For more detail you should consider reading this answer: Python try block does not catch os.system exceptions
For your workaround, you can try this code which works, however I have used subprocess.
import os
import sys
import subprocess

print("start here")

files = ["first.py", "second.py"]
count=0
for file in files:

    try:

        cmd = subprocess.Popen(["python", file],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        output, error = cmd.communicate()

        if(error):
            print(error)
            sys.exit()
    except OSError as e:
        print("inside exception", e)
        sys.exit()
    count+=1

Error Handling in Python3 (os.system)


Time series seasonality test

Question: What are the most simple seasonality tests for time series?
Being more specific, I want to test if in specific time series the seasonal component is meaningful.
What are the recommended packages in Python/ R?
Comment: `darts` package in Python has a `check_seasonality` function: https://unit8co.github.io/darts/generated_api/darts.utils.statistics.html
Answer: Before you test for seasonality you should reflect which type of seasonality you have. Note that there are many different types of seasonality:

Additive vs. Multiplicative seasonality
Single vs. Multiple seasonalities
Seasonality with even vs. uneven number of periods. Each year has twelve months, but 52,1429 weeks.
Trend vs. Seasonality: A seasonality pattern always appears in the same period, but a trend may appear a little bit later or earlier and not exactly each 5 years. One example for a trend are business cycles.

One of the most common methods to detect seasonality is to decompose the time series into several components.
In R you can do this with the decompose() command from the preinstalled stats package or with the stl() command from the forecast package.
The following code is taken from A little book of R for time series
births <- scan("http://robjhyndman.com/tsdldata/data/nybirths.dat")
birthstimeseries <- ts(births, frequency = 12, start = c(1946,1))
birthstimeseriescomponents <- decompose(birthstimeseries)
plot(birthstimeseriescomponents)

You can check the single components with

birthstimeseriescomponents$seasonal
birthstimeseriescomponents$random
birthstimeseriescomponents$trend

An other method is to include seasonal dummies and to check whether they have significant p-values when you compute the regression. If the single months have siginificant coefficients your monthly time series is seasonal.

An other method to detect seasonality is either to plot the data itself or to plot the ACF (autocorrelation function). In our case you can easily notice, that there is seasonality.

And last, but not least there are some "formal" hypothesis tests in order to detect seasonality such as the Student T-Test and the Wilcoxon Signed Rank Test.
Comment: I am ... AUTOBOX automatically searches for both stochastic i.e ARIMA structure and deterministic structure (fixed effects like day-of-the-week , month-of-the-year, day-of-the-month,quarter-of-the-year etc) while dealing with complications like step/level shifts,local time trends,pulses,changes in both parameters and error variance over time. There is an R version . It is an outgrowth of my PHD dissertation to automate time series model identification in both univariate and multivariate settings.
Comment: in my case, I don't know by myself (additive vs multiplicative , Single vs. Multiple seasonalities
Seasonality with even vs. uneven number of periods), I have a lot of time series and would like to have a approch generich as much as possible.

For begining I would like to start with **additive, single seasonality, even + not even.** @Ferdi
Comment: maybe you should think about your data: is it daily, weekly, monthly or quarterly data? are there any shocks or irregularities? what do you observe, when you visualise it?
Comment: some of the time series have weekly, daily, hourly. And some other doesn't have at all.
For the first step I want to detect if the seasonal component meaning full at all.
For your second example it has Lag 3 and 12. But somehow by eye I don't find any seasonality at lag 3. Is it better to look on **pacf** instead?
If I look on ACF or PACF how I distinguish AR(p) model (which is not seasonal) versus a seasonal model?@Ferdi
Comment: I am not aware of any algorithm you can blindly run on any kind of time-series to test for seasonality
Comment: I wonder if FFT / STFT could be good to discover the seasonality behaviour?
Comment: Coming back to the OP's question, specifically to "I want to test if in specific time series the seasonal component is meaningful", if there is seasonality, but it really does not make up much of the data when you see the series decomposed, could it be ignored and left out of a particular model? That is, is it meaningful enough or can we ignore it and go with a less complex model that does not take into account seasonality?
Answer: In R you have the seastests package that includes several seasonality tests and the function isSeasonal() that conveniently combines several seasonality tests to indicate whether your time series is seasonal.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: My thoughts are to check the amplitude of the:

ACF autocorrelation function
PACF partial autocorrelation function
Fourier Coefficients

(Fourier Coefficients are related to ACF via Wiener-Khinchin theorem.)

Time series seasonality test


C# Mysql Insert Data not work

Question: I am Nubie in C#, I Try to learn CRUD. Select data Succes but I cant Save data to mysql.
my table
mahasiswa

   ID| namae | jurusan | email
  _____________________________
  1 |  Bill  | IT      | email@example.com
  2 | Tony   | IT      | firstname.lastname@example.com

ID is set to auto increment in Mysql
and this my script for btn save
 void btnsave_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtid.Text != "" && txtnama.Text != "" && txtjurusan.Text != "" && txtemail.Text != "")
                {
                    query = string.Format("INSERT INTO mahasiswa values ('{1}','{2}','{3}');", txtnama.Text, txtjurusan.Text, txtemail.Text);

                    koneksi.Open();
                    perintah = new MySqlCommand(query, koneksi);
                    adapter = new MySqlDataAdapter(perintah);
                    int res = perintah.ExecuteNonQuery();
                    koneksi.Close();

                    if (res == 1)
                    {
                        MessageBox.Show("Input Data Sukses...");
                    }
                    else
                    {
                        MessageBox.Show("Input Data Gagal... ");
                    }

                }
                else
                {
                    MessageBox.Show("Data tidak lengkap");
                }
            }
            catch(Exception ex)
            {
                  MessageBox.Show(ex.ToString());
            }
        }

That Script can run, but after input data and click save buttonm the program stop.
Can anybody help me.
Im very Appreciated your answer
Thanks
form load
 void Form1_Load(object sender, EventArgs e)
        {
            try
            {

                koneksi.Open();
                query = string.Format("SELECT * FROM mahasiswa");
                perintah = new MySqlCommand(query, koneksi);
                adapter = new MySqlDataAdapter(perintah);
                perintah.ExecuteNonQuery();
                ds.Clear();
                adapter.Fill(ds);
                koneksi.Close();
                dgv1.DataSource = ds.Tables[0];
                dgv1.Columns[0].Width = 50;
                dgv1.Columns[0].HeaderText = "ID";
                dgv1.Columns[1].Width = 120;
                dgv1.Columns[1].HeaderText = "Nama Mahasiswa";
                dgv1.Columns[2].Width = 120;
                dgv1.Columns[2].HeaderText = "Jurusan";
                dgv1.Columns[3].Width = 120;
                dgv1.Columns[3].HeaderText = "Email";
                //txtid.clear();
                txtnama.Clear();
                txtjurusan.Clear();
                txtemail.Clear();
                btnedit.Enabled = false;
                btndelete.Enabled = false;
                btnsave.Enabled = true;
                btnsearch.Enabled = true;

            }
            catch (Exception ex) {

                MessageBox.Show(ex.ToString());
            }
        }

Comment: try to change your sql string like "INSERT INTO mahasiswa values ('{0}','{1}','{2}');"
Answer: Also if your learning CRUD it would be helpful if you made the necessary stored procedures within SQL aswell as attempting it this way.
Just create a CREATE, INSERT, UPDATE, DELETE procedure. Then in your code for an insert example you have this:
public bool Add(string example)
    {
        try
        {

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("[Proc name]", con);
                cmd.CommandType = CommandType.StoredProcedure;
                if (con.State == ConnectionState.Closed)
                    con.Open();
                cmd.Parameters.AddWithValue("@Example", example);

                cmd.ExecuteNonQuery();
                return true;
            }
        }

This allows you to view what happens and to ensure your procedures are working correctly. This way allows you to catch exceptions easier, and also validate your inputs easier.
Comment: Thanks For Your Advice, but I am still nubie, its hard to me to create the procedure specially in VS 2010. Usually I code with PHP and create Function on new file.
Comment: From my example it would be better to create the proc in SQL, using an INSERT statement and then this code in my example would be the only code you need to add the values into your SQL table.
Answer: try this
"INSERT INTO mahasiswa (name,jurusan,mail) values ('{1}','{2}','{3}')", txtnama.Text, txtjurusan.Text, txtemail.Text)";

as your query will instruct mysql to look for 4 values whereas you are passing only 3 values.
Comment: what is the rror you are geting
Comment: i Just modified my query  can you try with the new query
Comment: hi @satya work, but i Modify like this "INSERT INTO mahasiswa (nama,jurusan,email) values ('{0}','{1}','{2}');", txtnama.Text, txtjurusan.Text, txtemail.Text, it work but I still not understand why it work. and the datagrid not update in real time.
Comment: it workeds becaused you numbered the parameters correctly this time. About datagrid need to re-check, and where is the code for datagrid?
Answer: Do not use string concatenation to build sql command text, use always a parameterized query
query = "INSERT INTO mahasiswa VALUES (@p1,@p2,@p3);";
using(MySqlConnection koneksi = new MySqlConnection(connectionString))
using(MySqlCommand perintah = new MySqlCommand(query, koneksi))
{
     koneksi.Open();
     perintah.Parameters.AddWithValue("@p1", txtnama.Text);
     perintah.Parameters.AddWithValue("@p2", txtjurusan.Text);
     perintah.Parameters.AddWithValue("@p3", txtemail.Text);
     int res = perintah.ExecuteNonQuery();
     if (res == 1)
         MessageBox.Show("Input Data Sukses...");
     else
         MessageBox.Show("Input Data Gagal... ");
}

If you use string concatenation your code will be open to sql injection where a malicious user could wreak havoc with your database (Look at this funny example)
Also your format statement is totally wrong, I doubt that your code reaches the point where the database command is executed because you list the arguments for string.Format from the index 1 to index 3 and you supply 3 arguments, but the index should start from zero and end at two. So you should get an exception on that line.
Another point to keep note is the using statement. As you can see, in my code the using statement will ensure the proper closing and disposing of the connection and command objects. The connection is particularly important to dispose properly because a failure here could break your program later.

C# Mysql Insert Data not work


How can a "standard Elastic IP" become the External IP for a VPC?

Question: In AWS, I have an IP address I must keep.  (end users are manually typing it in for DNS service)
I need to move the DNS server from a standard instance to a VPC base instance. I understand that I can't directly assign the IP to my VPC, but I want to understand techniques in which I can otherwise do it.
For example, is the only option to set up a classic host with 2 NICs, one is my "external" IP, and one is my internal, and then have some kind of port forwarding happen?
What have I done
I've experimented with the VPC wizard and it appears that the "public and private subnets" option deploy an instance of a NAT-ing firewall, that resides on a virtual host.  What kind of software is this, and can I deploy it manually in an existing configuration?
Is there an alternative way to deploy port-forwarding as described?
Answer: You can now move the EIP from standard to vpc scope. Check out http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#migrating-eip
Answer: EC2 EIPs, whether in EC2 Classic or in a VPC, operate through a 1:1 NAT. That is, the IP address never actually gets assigned directly to your host. Rather, traffic to/from the associated instance goes through the EC2 NAT infrastructure.
Sadly, EIPs are not portable between EC2 Classic and VPC, so you're out of luck if you were hoping to be able to somehow move this IP into a VPC.
With regards to NAT hosts in a VPC, that is only necessary if you have hosts in the VPC that 1) do not have an EIP assigned and 2) need access to resources outside your VPC. If you assign EIPs to your instances that need access to outside resources, AWS handles the NAT for you. However, if you have instances that do not have EIPs associated, and those instances need outside access, then you'll need to roll your own NAT server or use one of Amazon's pre-configured NAT AMIs. These are nothing special - just a linux server with NAT enabled via iptables and ip forwarding enabled in the kernel.
Comment: You could, in the short term. Or some sort of IPSec tunnel between the two. By doing that, though, you're doubling your chances of downtime, not to mention the complexities of managing such a system.
Comment: So if the EIP lives on classic, and another EIP lives on VPC... I could use IPTables to accommodate the forwarding?
Answer: It is now possible to migrate an EIP from the standard scope to the VPC scope but you first need to disassociate your Elastic IP from your instance (so you will see a short amount of downtime).
You can then move the Elastic IP to the VPC scope:

It can take a few minutes to transition over unfortunately and it may look like it has disappeared for a moment (details here). Once it has moved over, you can then allocate it to your instance in VPC.


Git Post-receive hook get modified files/foldes

Question: I'm writing a post-receive hook to update some servers.
My git repo has a folder for each server. My objective is get all folders (servers) that has modified to ran some scripts on only those servers.
Here is an example of my working tree:
├── host1
│   ├── examplefile.json
│   └── configfile.cfg
├── host2
│   └── file1.txt
├── host3
│   └── binfile.rpm

It's possible to write something like that on post-receive?
UPDATE 1:
My post-receive so far execute a script on another server witch has a copy of this repo, this server than fetch, reset and execute a script to update those files on every host.
Comment: So you want to execute code based on what server receives an update from git? If so, yes, that is possible.
Comment: hello @blcook223, no, that's not the point. Read my update, now it's more clear haha
Answer: What i've just figured out it's much more simpler to ran a diff on the server that post-receive execute:
My post-receive it's just a command over ssh:
#!/usr/bin/env bash
ssh root@controller-host -C /root/sync.sh

Sync script on controller host:
cd /root/mytest/myrepo
git fetch --all
git diff --name-only origin/master
git reset --hard origin/master
git diff --name-only origin/master

OUTPUT:
Fetching origin
host1/file1
host2/file1
host3/file1
host4/file1
HEAD is now at 8e57e51 startei

Now it's possible to parse the diff output an syncronize only host1,host2,host3 and host4.
If someone find a better way please share.


Is it possible to crop an Element using Elm's std library? If not, is there a 3rd party lib for this?

Question: I often run across a situation where I've constructed an Element or Form and wish to crop the view down to a given area (i.e. for scrolling within a smaller rectangle) though I haven't been able to find any methods for this within their respective modules.
Is it possible to do this using Elm's std library? If not, are there any 3rd-party libraries capable of doing this?
Otherwise, perhaps there is a better way of achieving this?
Any help or suggestions appreciated!
Comment: So you want a small box with scrollbars with content in it that could be larger than the box?
Comment: @Apanatshka yes, this would be one example of where it would be useful. Another use-case example might be creating a movable 2D "camera" style view of a small area of the larger content.
Answer: No scollbars (using the std library)
I can't find a way to crop but have scrollbars with the current Graphics.Element. What is possible is to crop without having scrollbars, either through a container that's smaller than it's contents or by resizing an element with size. I think the container way is more robust, as resizing an image will actually warp the image.
Here's an example:
import Graphics.Element exposing (..)
import Text

string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est."

main : Element
main =
  let element =
    leftAligned (Text.fromString string)
    |> container 400 300 topLeft
  in container 205 200 topLeft element

Scrollbars (via "3rd party" library)
If you want scrollbars, you'll probably need at least a little bit of html from elm-html. Note that the author of the library is also the author of Elm, so it's not quite 3rd party :P . You can keep it minimal by using conversions to html and from html and wrapping it in a div with style attributes that define the smaller size and the right overflow property. As long as that div has a known size, it should be easy to convert back to an Element.


How to compute the initial matrix from result

Question: By multiplying the below matrix element wise, we can find the answer as $A.B = C$
$$
\begin{bmatrix}
2 \\
3 \\
\end{bmatrix}.
\begin{bmatrix}
2 & 1 \\
3 & 4 \\
\end{bmatrix}
=
\begin{bmatrix}
    7 \\
    18 \\
    \end{bmatrix}
$$
Is there any way to to find B (2x2 matrix) if we know C and A?
Comment: The multiplication on the LHS is not defined: did you mean to have the 2x2 matrix on the left multiplying the 2x1 vector?
Comment: In general, we can't. Take $A=C=0$. Then any $B$ is possible.
Answer: There is a way, but you won't get a unique matrix $B$. Namely, if:
$$B=\left[\begin{matrix}a&b\\c&d\end{matrix}\right]$$
then your equation for $B$ looks like this:
$$\left[\begin{matrix}a&b\\c&d\end{matrix}\right]\left[\begin{matrix}2\\3\end{matrix}\right]=\left[\begin{matrix}7\\18\end{matrix}\right]$$
which is equivalent to the following system of equations:
$$\begin{array}{rcl}2a+3b&=&7\\2c+3d&=&18\end{array}$$
which doesn't have a unique solution. For example, you can freely choose $a$ and $c$, and set $b=\frac{1}{3}(7-2a)$ and $d=\frac{1}{3}(18-2c)$, so:
$$B=\left[\begin{matrix}a&\frac{1}{3}(7-2a)\\c&\frac{1}{3}(18-2c)\end{matrix}\right]=\left[\begin{matrix}0&7/3\\0&6\end{matrix}\right]+a\left[\begin{matrix}1&-2/3\\0&0\end{matrix}\right]+c\left[\begin{matrix}0&0\\1&-2/3\end{matrix}\right]$$
for any numbers $a,c$.


The security database on the server does not have a computer account for this workstation trust relationship

Question: I have a Server 2008 machine called OTTO
I recently, by mistake, booted up an old machine, also called OTTO (the hardware was unstable, so the new one was set up to take it's place)
I shut down the old machine, turned it off, and recycled it (it won't ever be back on)
Now, whenever i try to log in to the real OTTO with the domain account (mydomain\Administrator) i get the following error:

The security database on the server does not have a computer account for this workstation

What can I do to fix this?
It doesn't appear in active directory any more
I've added it, but I'm guessing this had no effect, due to a different SID
I can log in as the local administrator however
Answer: The easiest fix is to place "OTTO" back into a "Workgroup" and re-join the domain. (Be sure you have a good local Administrator credential on OTTO when you're doing this...)  I'm unsure how just booting the old machine caused this issue, but disjoining and rejoining the domain will resolve the problem.


Como criar uma keystore no prompt do windows?

Question: Eu quero assinar o apk do meu aplicativo que já está pronto faz 1 mês, mas não consigo de nenhuma forma criar essa tal 'keystore'. Já tentei online, no Android Studio(zzz) e estou tentando no prompt de comando a 2 semanas. Já tentei seguir alguns tutoriais para isso mas pedem para instalar o java e depois um JDK e abrir o prompt como administrador e mesmo assim não funciona de nenhuma forma.

Se alguém puder me ajudar eu agradeço bastante.
Answer: tens que adicionar o keyTool como variavel de ambiente!
Comment: Mais precisamente, tem que adicionar o caminho onde está o aplicativo `keytool.exe` à variável de ambiente `PATH`. Ele fica na subpasta `bin` da pasta da JRE ou JDK (não lembro agora). Exemplos aqui: http://stackoverflow.com/questions/6211919/errorkeytool-is-not-recognized-as-an-internal-or-external-command-operable-p
Comment: Como que eu faço isso?
Comment: Não acredito que deu certo * o * Muito obrigado!
Answer: Veja esse vídeo, nele tem um passo a passo para publicar um app https://www.youtube.com/watch?v=Rj1w9atPpHk


Prevent continue Typing in TextBox When a Char is Entered

Question: I have a textbox which user should type a price in it.
I need to prevent continue typing if price starts with 0.
For example user can not type "000" or "00009".
I tried this on KeyPress, but nothing!
if (txt.Text.StartsWith("0"))
       return; Or e.Handeled = true;

Comment: Refusing to allow any typing when the price starts with 0 seems like a poor user experience - notably, they may want to type a backspace to *remove* the character if they entered it in error. A softer approach that highlights the text box and refuses to submit the entire form, whilst allowing edits/corrections would usually be preferred.
Comment: Yes User can backspace and delete, but if it starts with 0 it can not type another char.
Comment: Should it be `e.Handeled = true`? [Reference](http://stackoverflow.com/a/2591284/1050927), and you may need to check user input `numeric` instead of control character (backspace, delete...)
Answer: try this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    //only allow digit and (.) and backspace
    if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '\b' && e.KeyChar != '.')
    {
        e.Handled = true;
    }

    var txt = sender as TextBox;

    //only allow one dot
    if (txt.Text.Contains('.') && e.KeyChar == (int)'.')
    {
        e.Handled = true;
    }

    //if 0, only allow 0.xxxx
    if (txt.Text.StartsWith("0")
        && !txt.Text.StartsWith("0.")
        && e.KeyChar != '\b'
        && e.KeyChar != (int)'.')
    {
        e.Handled = true;
    }
}

Comment: instead of `e.KeyChar != '\b'` it is better to use `!char.IsControl(e.KeyChar)`
Answer: You could use the TextChanged-event for this.
private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (this.textBox1.Text == "0") this.textBox1.Text = "";
}

This will only work, if the TextBox is empty on startup.
Comment: I do not want to empty the text box after entering 0 at start. I just want to prevent continue typing in this situation.
Comment: You can still use text changed
Answer: I solved it Myself:
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
    if (txtPrice.Text.StartsWith("0") && !char.IsControl(e.KeyChar))
    {
        e.Handled = true;
        return;
    }
}


Como faço para exibir uma mensagem se registro encontrado e se não encontrado?

Question: Tenho a seguinte rotina em php:
or die ("Não foi possível realizar a consulta ao banco de dados");
while($rowfoto2 = mysql_fetch_array($ridfoto2))
   {

Como faço para exibir uma mensagem se registro encontrado e se não encontrado?
Muito Obrigado!
Comment: Veja o número de linhas retornadas, se for zero, `echo 'registro não encontrado';`
Answer: Basicamente é isso:
or die ("Não foi possível realizar a consulta ao banco de dados");
if( mysql_num_rows($ridfoto2) == 0 ) {
    echo 'Não veio nada';
} else {
 while($rowfoto2 = mysql_fetch_array($ridfoto2))
    {

É o que o @rray disse nos comments.
Importante, já que você está desenvolvendo um código novo, usar as funções mysqli no lugar das funções mysql, que já estão obsoletas e vão parar de funcionar nas próximas versões do PHP.
Aqui tem uma resposta do @rray que orienta essa troca: https://pt.stackoverflow.com/a/32822/70
Answer: Um pouco mais otimizado mas o que o Bacco respondeu resolve o teu problema.

or die ("Não foi possível realizar a consulta ao banco de dados");
if (mysqli_num_rows($ridfoto2) > 0) {
    while($row = mysqli_fetch_array($ridfoto2)) {
     //Instruções
    }
} else {
    echo "0 results";
}

Comment: Resumindo os comments que eu deixei anteriormente: seu código está correto, só não concordo que seja uma otimização do meu, apenas uma reordenação. Entendo que se a mensagem vem no `if` ou no `else` depende apenas da necessidade e/ou conveniência que o autor pretende.