Closed mapping theorem

Question: I have been trying to prove the following:
Assume that $X$,$Y$ are two normed spaces. Let $T$ be a closed mapping
$T: X \to Y$ show that the image $A$ of a compact subset $C$ in $X$ is closed.
Show that the inverse image $B$ of a compact subset $K$ of $Y$ is closed in $X$.
I think that I have succeeded with the first part of the problem by usigneret that the graph of $T$ on $C$ is closed and thus $A$ must also be closed.
The second part is harder: then I want to assume that $T$ is either invertible or bounded, but I can't show that it is.
Comment: compact subsets in a Hausdorff space are closed, so everything follows by this observation.
Answer: For the first problem: If $C$ is compact in $X$ then is closed and thus $T(C)$ is closed in $Y$.
For the second problem:Because $T$ is closed map,we have that $T^{-1}$ is continuous and continuous image of a compact set is compact and hence $T^{-1}(K)$ is compact and thus closed in $X$.
Comment: @user108875 ,check my proof please.thank you

Closed mapping theorem


{} no retorno do require()

Question: Eu estou criando um módulo, mas quando vou utilizar ele, recebo um objeto vazio no require()
Códigos abaixo:
dev/index.js

module.exports = () => {
  'use strict';

  const names = require('./names.js'),
  findSuperman = require('./find.js');

  if ( findSuperman(names()) )
    console.log('O superman está dentro de names');
  else
    console.log('O superman não está aqui');

}

dev/names.js

module.exports = () => ['Barry Allen', 'Hal Jordan', 'Kara Kent', 'Diana Prince', 'Ray Palmer', 'Oliver Queen', 'Bruce Wayne', 'Wally West', 'John Jones', 'Kyle Rayner', 'Arthur Curry', 'Clark Kent'];

dev/find.js

module.exports = (values) => {
  'use strict';
  let foundSuperman = false;

  values.forEach(name => {
    if (name === 'Clark Kent')
      foundSuperman = true;
  });

  return foundSuperman;
}

Daí, ao executar o browserify
browserify dev/index.js -o out.js

out.js

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = (values) => {
  'use strict';
  let foundSuperman = false;

  values.forEach(name => {
    if (name === 'Clark Kent')
      foundSuperman = true;
  });

  return foundSuperman;
}

},{}],2:[function(require,module,exports){
module.exports = () => {
  'use strict';

  const names = require('./names.js'),
  findSuperman = require('./find.js');

  if ( findSuperman(names()) )
    console.log('O superman está dentro de names');
  else
    console.log('O superman não está aqui');

}

},{"./find.js":1,"./names.js":3}],3:[function(require,module,exports){
module.exports = () => ['Barry Allen', 'Hal Jordan', 'Kara Kent', 'Diana Prince', 'Ray Palmer', 'Oliver Queen', 'Bruce Wayne', 'Wally West', 'John Jones', 'Kyle Rayner', 'Arthur Curry', 'Clark Kent'];

},{}]},{},[2]);

Até aí, tudo bem :)
Porém...
Tento fazer um teste e não rola :/

'use strict';

const oi = require('./out.js');
console.log(oi);

// O retorno é: {}
Comment: Porque tens a variável `findSuperman = require('./find.js');` não declarada? Já testaste a colocar essas duas linhas (requires) fora da função que estás a exportar? ou seja, no inicio do ficheiro `dev/index.js`? Esse tipo de erro do Browserify acontece-me quando há erros de _lint_ / sintaxe no código.
Comment: 1- Está declarada como const em `dev/index.js`. 2- Fiz o que você falou. Mas ocorreu-me de receber `{}` de novo :/
Answer: Bom dia!
Acredito que você está aprendendo ES6 e Browserify, certo? Acho que eu entendi as suas dúvidas, então vamos lá:
Os arquivos dev/names.js e dev/find.js retornam funções utilizando a notação arrow-function. O arquivo dev/index.js também retorna uma função, porém ela nunca é executada! Tente alterar esse arquivo para somente
  const names = require('./names.js'),
        findSuperman = require('./find.js');

  if ( findSuperman(names()) )
    alert('O superman está dentro de names');
  else
    alert('O superman não está aqui');

Execute o comando browserify dev/index.js -o out.js no terminal e adicione o script gerado a um arquivo HTML e abra no navegador. Após fazer isso, você perceberá que um alert foi exibido com a mensagem "O superman está dentro de names".
Sobre o Browserify, seu objetivo é escrever código JS usando módulos do NodeJS (CommonJS) e depois fazê-lo rodar no navegador.
Comment: Perdão por não ter visualizado antes, estive um pouco ausente. Enfim, achei estranho porque não tive o resultado esperado mesmo com IIFE. Porém da sua maneira funcionou perfeitamente. Obrigado!

{} no retorno do require()


Running feeds in order

Question: I just ran into a situation where I need to run three imports, one after another using the same file providing successful import. Does anyone know how to do this? I looked briefly at Feeds rules but I don't think that will work unless I'm missing something?
Thanks
Answer: I would recommend using a small custom module to add your own queue:
http://api.drupal.org/api/drupal/modules!system!system.queue.inc/group/queue/7
Then use your callback to run each item through feeds.

Running feeds in order


Stylesheet not loading in Mozilla Firefox

Question: I'm stumped. Working on a site that isn't loading properly in FireFox. It loads great in Chrome and even IE, but for some reason the stylesheet isn't loading in FireFox.
The site: http://gregsonaccounting.com
I'm using html5 code and have used the basic resets and such from html5 Boiler Plate. Not sure if the problem is in my html or CSS.
Any insight is extremely helpful.
Many thanks.
Comment: http://validator.w3.org/check?verbose=1&uri=http%3A%2F%2Fgregsonaccounting.com%2F often helps.
Answer: Your problem comes from style.css which begins by @charset "IBM437"
Replace it with @charset "UTF-8"; and it will be better !
It seams this charset IBM437 is auto added by SASS:
CSS pseudo element ▼ becomes gibberish in IE
Comment: Any idea of how to keep SASS from adding IBM437? When I recompile my stylesheet now from SASS it still reverts to the problematic IBM437. Perhaps there's a way to tell it to use UTF-8 in the Config.rb file?
Comment: It seems if the source file is both UTF-8 and if @charset "UTF-8"; is the very first line then sass gets it right.
Answer: A stylesheet should be defined in the format;
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">

You may also include media attribute, that they specify how a document is to be presented on different media: on the screen, on paper, with a speech synthesizer, with a braille device, etc.
In your page, it is;
<link rel="stylesheet" href="stylesheets/style.css" rel="stylesheet" />//Here is the problem
<link rel="stylesheet" href="nivo-slider/nivo-slider.css" type="text/css" media="screen" />
<link rel="stylesheet" href="nivo-slider/themes/default/default.css" type="text/css" media="screen" />

So that line may be modified like;
<link rel="stylesheet" href="stylesheets/style.css" type="text/css" media="screen" />

Answer: Try changing:
<link rel="stylesheet" href="stylesheets/style.css" rel="stylesheet" />

to
<link rel="stylesheet" href="stylesheets/style.css" type="text/css" />

Comment: since HTML5 it is not anymore necessary to specify `type="text/css"`
Answer: My CSS code worked well on Chrome, but it kept crashing on IE and Firefox. Then i found out the problem was in a badly preprocessed CSS.
Just copy paste your CSS to http://csslint.net/ and if you get any error, just fix it and you are good :)
Worth trying!
Answer: insert this inside your html documents. I am not writing in code just giving u the key words so you know and can put it in.
link rel="stylesheet" type="text/css" href="stylesheet.css"
it works so make sure you have this correctly or else your html document will not load with your stylesheet. best of luck to you and keep working brah.


When a row is checked, the whole row turns black

Question: When using checkbox in bootstrap-table every row that is selected turns black, how can I manage the colors or a I missing a library or something
bootstrap-table checked
I tried a CSS attribute change but nothing happened
Comment: Without you posting the CSS code, we cannot help you
Answer: Since you did not share the CSS file, I am using an example of "selected" class for your td element. Do override the background color of your row like this:
<code>.selected tr{
   background-color:white !important;
 }
</code>


Show all users except profile being viewed (views, panel node)

Question: I've got a view of type "users".  I have it filtered to a certain "role".  There are only 12 ppl in this role (it is for a calendar, and someone is sponsored each month).  When viewing a users profile I want to show a list of the other 11 below that user.  I currently have it listing all 12, I cant figure out a filter to exclude the current profile being viewed.
I have to be missing something easy
Answer: the last checkbox on the settings of the contextual filter - exclude :) (under more)
Comment: HA! -- wooooooooow.  Thanks, Sorry to waste your time. I swear I looked at that screen 9,000 times.


Unable to install breakpoint - Wildfly remote debugging / Eclipse

Question: I am suddenly getting an error while trying to remote debug a Wildfly (9.0.1) WAR web application using Eclipse.
Unable to install breakpoint in com.yadayada.rest.PageService$Proxy$_$$_WeldClientProxy due to missing line number attributes.  Modify compiler options to generate line number attributes.

I have ensured the "Add variable attributes", "Add line number", "Add source file name" options are all checked in Eclipse properties.  (Note based on several other similar StackOverflow posts, I have unchecked these, applied the changes, rebuilt the application, left eclipse, come back in, re-checked them, rebuild).
I exploded my WAR and did a javap -l on a class file (specifically the one I am trying to debug) and this showed me a a LineNumberTable and LocalVariableTable for all my methods, so I feel like the line numbers are being included.
I seem to be able to debug okay, but I am confused by the error.
My process to do the debugging:
1. I have a break point set in my code.
2. I have Wildfly started with the debug option (sh standalone.sh --debug)
3. I have a Remote Java Application defined in Eclipse and start debugging by clicking DEBUG on the debug configuration.

Some information that may be helpfulL
1. MacOS 10.14.15; Wildfly 9.0.1; Eclipse Photon 4.8.0 build 20180619-1200; Maven 3.3.3
2. To build my WAR, I am using:  mvn clean package -Dmaven.test.skip=true

Answer: How did you do 'Add line number attribute' for Eclipse in MacOS? I cannot find the way to do it.
Comment: Eclipse --> Preferences --> Java --> Compiler --> Classfile Generation.  It's the first several check box options.


Trig 101: Calculate coords of point P such that it is distance n from line AB and distance m from line BC

Question: I've been in software engineering nearly 25 years and my trigonometry and maths skills are very rusty.  We have a requirement to drill a hole in the corner of a sheet of material, where the corner isn't a right angle and the hole must be 30mm from the top edge and 50mm from the side edge.  This was fairly easy to solve when the line AB is vertical because I could make assumptions about similar triangles and solve in two lines of trig, but the calculation where both lines are not aligned with the axes is stumping me.  I've a feeling it's going to involve simultaneous equations.  I've searched but this site tends to the pure math side of things and I'm not sure the terminology to use.
I hope someone whose skills are up to date can take pity on me and bash this out in a minute or two :)

We know the coordinates of the points A, B and C, the distances m and n are constants (50 and 30), and we know point P must be n perpendicularly from AB and m perpendicularly from BC.
Edit: in the real world point A is actually the origin 0,0 because the coordinate space of each piece of material starts at its bottom left corner.  This would probably simplify the calculation, but for purity we could continue to assume A is an arbitrary 2d point.
How would we calculate point P?
Answer:
I hope someone whose skills are up to date can take pity on me and
bash this out in a minute or two :)

It takes 1-2 minutes to "bash out", 20 minutes to write out in Latex. Hope it is helpful :-).
Given  $A=(0,0),{B=(x_b,y_b)},C=(x_c,y_c),$
$\vec{BA}=(-x_b,-y_b), \tag 1$
$\vec{BC}=(x_c-x_b,y_c-y_b), \tag 2 $
$|\vec{BA}|=\sqrt{x_b^2+y_b^2}=a,\tag 3$
$|\vec{BC}|=\sqrt{(x_c-x_b)^2+(y_c-y_b)^2}=c,\tag 4$
$\boxed{{\cos \angle B=\frac{\vec {BA}•\vec{BC}}{|\vec{BA}||\vec {BC}|}=\frac{(-x_b,-y_b)(x_c-x_b,y_c-y_b)}{ac}=\color{red}{k},\sin \angle B=\sqrt{1-k^2}}}\tag 5$
We can get $\angle B$ with inverse trig function now:
$\boxed{\angle \color{red}{B} =\arccos k} \tag {5a}$
From difference formula of sine function:
$\sin( \angle B - \theta)=\sin\angle B\cos\theta-\cos\angle B\sin\theta=\sqrt{1-k^2}\cos\angle \theta-k\sin\theta$
$BP=\frac{n}{ \sin \angle \theta}\\=\frac{m}{sin( \angle B -\angle \theta)} \tag {5b}$
$=\frac{m}{\sqrt{1-k^2}\cos\theta-k\sin \theta}\tag {5c}\\$
cross-product (5b) and (5c)
$n\sqrt{1-k^2}\cos\angle \theta-nk\sin\theta={m\sin \angle \theta}$
$n\sqrt{1-k^2}\cos\angle \theta={(m+nk)\sin \angle \theta},\\\cot \theta =\frac{m+nk}{n\sqrt{1-k^2}}\\\tan \theta =\frac{n\sqrt{1-k^2}}{m+nk}\tag 6$
Therefore
$\boxed{\color{red}{\theta}=\arctan \frac{n\sqrt{1-k^2}}{m+nk}} \tag {6a}$
\begin{align}\boxed{|BA'|=\frac{n}{\tan\theta},|BC'|=\frac{m}{\cot\theta}} \tag {6b}\end{align}
$\vec {BA'} =\frac{\vec {BA}}{|\vec{BA}|}|\vec{BA'}|=\frac{(-x_b,-y_b)}{a} \frac{n}{\tan\theta},A'=-(x_b,y_b)(\frac{1}{a} \frac{n}{\tan\theta} +1)$
Let $\vec {A'P}=(p,q)\perp \vec {BA'}, \vec {A'P}\cdot\vec{B'A}=0,|\vec{A'P}|=n$
$p^2+q^2=n^2,p\cdot x_b+q\cdot y_b=0 ,$
$q=-p\cdot\frac{x_b}{y_b}$
$p^2(1+ (  \frac{x_b}{y_b})^2)=n^2$
$p=\sqrt{  (1+ (  \frac{x_b}{y_b})^2)}n \tag 7$
$q=-\sqrt{  (1+ (  \frac{x_b}{y_b})^2)}n\cdot\frac{x_b}{y_b}
\tag 8$
$\vec{OP}=\vec {OA'}+\vec{A'P}\\= (p,q)+ -(x_b,y_b)(\frac{1}{a} \frac{n}{\tan\theta} +1)\tag 9$
Please note all values in (8) are known by now.
P's coordinates are the same as $\vec {OP}$'s coordinates. DONE.
Comment: Wow good work @BStar, didn't even need any trig functions! I had `tan` coming out the wazoo.  It works perfectly when I translate it into PHP and run it in my context.
 I'm in the process of rewriting it where `A` is not `0,0`, for the opposite edge of our product.  I must say the 5th line loses me with the notation, I think the apostrophe is called 'prime' in that notation, but I think I can struggle through with your excellent foundation.  Question: What should I rewrite the title of this post, and any better tags to use, since it doesn't involve trig, or just leave it for posterity?
Comment: Ah I see, `A'` and `C'` are midway points on the lines `AB` and `BC`. Duh.  Plugging this formula in for our opposite edge (a 'top right' corner where `C` is over to the left) seems to give a slightly off position, debugging it now.
Comment: Question about line 5 in your calculation, my problem is that the vector `C'P` is not parallel to `BA`.  You state that `BA' = (m / |BA|) * BA`, which seems to presume that the vector of length `m` is parallel to `BA`.  I'm suspecting this is why my point P is coming out "slightly off" as I mentioned before.  Am I misunderstanding something?
Comment: Thanks BStar.. I'm suffering from my rusty maths. Your step 6 makes a few leaps I can't follow, whereas I could follow the vector math in the previous worksheet.  I don't see that `theta` is known, since we don't know the length `|BA'|`.  Ending with a statement about  `tan(theta)` leaves me at a dead end.  Could you please show where this would result in known coordinates of `P`?  I'm unwilling to reorient the axes such that `AB` is vertical, as I presume we would then need to use vector rotation matrices to rotate `P` back into original world coordinates.
Comment: All is updated now. Let me know if any questions.
Comment: Here is the process: First  calculate cos B and use arccos to get B. Second calculate $\tan\theta$ to get $\theta$ with arctan by using |BP| is the same from two triangles. Knowing these, we can get vectors BA' and B'P, thus  vectors OA and OP. We get $\theta$ to grt vector BA' in this case, not the other way around.


About the interior of a polyhedron

Question: Let us consider a polyhedron in $\mathbb{R}^n$ (in this context it must NOT be bounded) $\mathcal{P} = \{ x: A \cdot x \leq c\}$ for some matrix $A$. Let $\mathcal{I} = \{ x: A \cdot x < c\}$ be a non-empty set. I want to prove that the closure of $\mathcal{I}$ is $\mathcal{P}$. The inclusion $\overline{\mathcal{I}} \subset \mathcal{P}$ is trivial. Probably also the other one, but maybe there is some standart procedure to prove this, without any strange reasoning.
My idea is to take $Q \in \mathcal{P}$ and any $R \in \mathcal{I}$. Then I would take the line from $R$ to $Q$ and try to prove that it is entirely contained in $\mathcal{I}$, save for the point $Q$. This would prove the statement.
Comment: I'd rather call your set: a *polyhedron*.
Comment: you are right, I edited, though saying that it can be unbounded sort of clears the definition anyhow. Any suggestions for the proof?
Answer: So here is the proof I managed to get. I´m not sure it´s the best there is.
Take $Q$ and $R$ as above. Now let $T \in [QR]$ be a point in the segment of the line from $Q$ to $R$, with $T \neq Q,R$. Suppose $T$ is not in $\mathcal{I}$. Than some of the inequalities has to be an equality. Suppose $A_1 \cdot T -c_1= 0$, and let us call $r$ the line defined by $A_1 \cdot x -c_1= 0$, and $s$ the line passing through $Q$ and $R$. These lines have intersection point $T$, so either they are identical (which is impossible because $P$ does not lie on $r$), or they have only one intersection in $T$. This is impossible aswell, because we would find $P$ in the wrong halfspace.

About the interior of a polyhedron


Easy-rsa files including ca.key deleted from server

Question: My server's easy-rsa file structure was accidentally deleted from the server during an os upgrade. I still have the ca.crt but no longer have ca.key or the client keys.
What are the ramifications for OpenVPN? Can I make new client certificates or revoke existing client certificates?
Answer: You cannot sign anything without the private key.  That includes new client certificates and CRLs.  If the same CA signed the OpenVPN server certificate, you won't be able to renew that when it expires.
Assuming you didn't have a backup of your system; your only option it to start again as far as certificates are concerned.  You'll need to create a new CA and issue replacement certificates to all.
As you'll stop trusting your original (now defunct) CA, the current certificates will simply become invalid - no need to worry about not being able to revoke them.


int16 is not supported in a windows presentation foundation project wpf

Question: Why am I getting the following error: "Int16 is not supported in a windows presentation foundation project wpf."
I was reading the following MSDN text:
MSDN TEXT regrading primitives mapping
Below is my simple code:
<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Window.Resources>
        <x:Int16 x:Key="cnst">12</x:Int16>
    </Window.Resources>

    <Grid>

    </Grid>

</Window>

Why doesn't this code work? And what needs to be done to get it working.
My guess: 2006 needs to be replaced with 2009 for some future version.
Answer: Basic types like Int16 are defined in the System namespace (in the assembly mscorlib.dll), which is not mapped to the x XAML namespace.
Although XAML 2009 maps these types to the x namespace, you can't directly use them in your MainWindow's XAML, because (according to the WPF Support paragraph in the XAML 2009 Language Features MSDN page)

In WPF, you can use XAML 2009 features but only for XAML that is not
  markup-compiled. Markup-compiled XAML for WPF and the BAML form of
  XAML do not currently support the XAML 2009 keywords and features.

You may hence only add another XAML namespace that maps the System CLR namespace like this:
<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        ...>

    <Window.Resources>
        <sys:Int16 x:Key="cnst">12</sys:Int16>
    </Window.Resources>
    ...
</Window>

Please also see the XAML Namespaces and Namespace Mapping for WPF XAML article on MSDN for more details.
Comment: I know your current approach. But I was curious about MSDN paragraph. So, XAML 2009 is not launched yet ? And presently are we using XAML 2006 as reflected in  Also, do we need for XAML 2009 to be launched in future to use this syntax ?
Comment: It is already launched, but can still not be used in compiled XAML. From the article: *A scenario where you can use XAML 2009 features together with WPF is if you author loose XAML and you then load that XAML into a WPF runtime and object graph with XamlReader.Load. The WPF System.Windows.Markup.XamlReader and its Load can process XAML 2009 language keywords and features into a valid object graph representation.*


How do you inject dependencies in your classes from external packages?

Question: My project has external PHP packages pulled in via Composer.
I would like to inject one of the classes in that package as a dependency, instead of do new Class(); inside my Controller methods.
The documentation says you can define a service like the following:
services:
  mymodule.example_service:
    class: Drupal\path\to\Class

What do you do when you want to use an external PHP package not native to Drupal?
Answer: You should be able to use the fully qualified namespace for the injection:
services:
  mymodule.example_service:
    class: path\to\Class

Answer: If anyone want to use external packages into Drupal controller, note that you can actually use one without dependency injection. For example, if you want to use Carbon (DateTime API):
Step 1: Install the package
composer require nesbot/carbon

Step 2: Use the namespace
use Carbon\Carbon;

That's all. You are ready to use the package now.
Code sample:
<?php

namespace Drupal\foo\Controller;

use Carbon\Carbon;
use Drupal\Core\Controller\ControllerBase;

class FooController extends ControllerBase {

    public function bar() {
        return [
            '#markup' => Carbon::now(),
        ];
    }
}

?>

Comment: It's best practice to adhere to DI as much as possible. In this example you are using a static method, similar to what Url and Link classes have.


Archiving multiple items

Question: I'm working on a document-based app without CoreData. I have a class Player, which is a subclass of NSObject. The class has some variables and I have also properly implemented - (id)initWithCoder:(NSCoder *)coderand - (void)encodeWithCoder:(NSCoder *)coder methods. That's how I'm archiving my data:
- (NSData *) dataOfType:(NSString *)aType
                  error:(NSError **)outError
{
    return [NSKeyedArchiver archivedDataWithRootObject:players];
}

(players is an NSMutableArray holding some instances of the Player class). The saving works absolutely fine. What I would like to know is how I can also archive (and unarchive later) some variables, declared in the Document.h file?
Answer: Look into NSFileWrapper, where you can define & implement saving  to / initializing from a file type which is a bundle (basically a folder) then you can save your document object alongside this array
Comment: Thank you, I'll have a look

Archiving multiple items


Why does simpletest report a missing schema for my custom module?

Question: My custom module is working as expected with the following settings, config and config export. But when I try to run tests, I get the following error. I'm not sure what is wrong.

Drupal\Core\Config\Schema\SchemaIncompleteException: Schema errors for riddler.settings with the following errors: riddler.settings:riddles missing schema in Drupal\Core\Config\Testing\ConfigSchemaChecker->onConfigSave() (line 102 of /var/www/sb/sboss/docroot/core/lib/Drupal/Core/Config/Testing/ConfigSchemaChecker.php).

# settings.yml
riddles:
 -
    question: 'Do you really hate Spam?'
    response: 'Yes!'
langcode: en

--------------------------------

#schema
riddler.settings:
  type: config_object
  riddles:
      question:
        type: label
        label: 'Question'
      response:
        type: label
        label: 'Response'

#config export

riddles:
 -
    question: 'Do you really hate Spam?'
    response: Yes!
  -
    question: 'What''s your favorite primary color?'
    response: 'blue, yellow, red'

Answer: There are several errors. You missed a type for riddles and tried to define a mapping immediately under, but riddles is a sequence and each element in the sequence is that mapping. This is probably what you wanted.

riddler.settings:
  type: config_object
  mapping:
    riddles:
      type: sequence
      sequence:
        type: mapping
          question:
            type: label
            label: 'Question'
          response:
            type: label
            label: 'Response'

Answer: Here's what worked.
riddler.settings:
  type: config_object
  mapping:
    riddles:
      type: sequence
      sequence:
        type: mapping
        mapping:
          question:
            type: label
            label: 'Question'
          response:
            type: label
            label: 'Response'

Thanks to chx for getting this most of the way there.


Can two arrays which contain the same elements not be equal?

Question: I encountered a stunning problem today where I'm trying to find if an object is contained in an List collection. The problem is that the list doesn't find the object and returns index as -1 when I can see it right there already. I then created a custom Index Finder to look for the object by comparing the properties rather than a direct equality where I discovered that one of the object's properties, a ushort array which was identical was returning false when compared, but they contain exactly the same element.
The array is as follows:

{ushort[1]} [0]13

and they're exactly the same in both except that one of the object is contained in a List while the other one is on it's own. What could be the cause of this problem? I've tried all types of different ways to get around the problem but I can't just figure out what the problem is. In this particular case what is causing the comparison between the two arrays to return false, I've tied using Object.equals as well as the normal == comparer. Thanks
Comment: What kind of array is this `{ushort[1]} [0]13`? What is this syntax?
Comment: Sorry, was just displaying it the way it's shown in debugger. It means ushort array of 1 element and first element is 13
Answer: For arrays, Equals will return true only if you compare two references that point to the same array. To compare different arrays by content, you can use:
 Enumerable.SequenceEqual(a1, a2)

Also, if collection contains objects of your custom type, make sure that these types override Equals, equality operator(==) and GetHashCode.
Comment: OMG, I understand why this does work but this will increase the time in comparing considering large arrays. Also how is it that it works for some types of arrays but not all? How is it that it doesn't even find the object in the list in some cases.
Comment: The object is simply a class which has a ushort array, a ushort and an int as public properties. There is absolutely no overriding of anything
Comment: Comparing arrays will take time proportional to array size. Regarding the case that sometimes comparison works and sometime it does not, probably in the first scenario you are comparing the same object, while in the second you are comparing two different object with the same properties.
Comment: Hmmm, so you're saying the equality comparer treats native arrays as objects?
Comment: Every object, including arrays and lists has it's own equality comparer, implemented by Equals method. Default implementation, `object.Equals` , compares only the references to the object, but not it's contents.
Comment: You don't *need* to overload the `==` operator for custom types.  It's occasionally convenient, but in most cases overriding `Equals` and not overloading `==` is at least acceptable.
Answer: Faced with the same issue using IEnumerable property with c# 9 records like in this question.
public record Person
{
    public IEnumerable<string> Names { get; }

    public Person(IEnumerable<string> names)
    {
        Names = names;
    }
}

The result of the Equals method will be false.
So I decided to declare specific class to be used in record's generated equitable check:
public class EquatableEnumeration<TItem> : IEnumerable<TItem>, IEquatable<EquatableEnumeration<TItem>>
{
    public IEnumerable<TItem> Values { get; }

    public EquatableEnumeration(IEnumerable<TItem> values)
    {
        Values = values;
    }

    public IEnumerator<TItem> GetEnumerator()
        => Values.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator()
        => Values.GetEnumerator();

    public bool Equals(EquatableEnumeration<TItem>? other)
        => other is not null && other.Values.SequenceEqual(Values);
}

public record Person
{
    public EquatableEnumeration<string> Names { get; }

    public Person(IEnumerable<string> names)
    {
        Names = new EquatableEnumeration<string>(names);
    }
}

With this implementation the result of Equals method will be true.


In pytest, how to run against different ip for cases with different marks or name patterns

Question: I have a question here.
I am using Pytest.
I have two cases with mark and name as:
1)
@pytest.mark.ip1
def test_ip1_actions()
    ...

@pytest.mark.ip2
def test_ip2_actions()
...

what I want is:
if the mark is ip1, then I will run the test against 1st ip - 192.168.2.23; if the mark is ip2, then the case should run against 2nd ip - 192.168.2.100
or:
based on the name, if case name contains "ip1", it will run against 1st ip; if case name contains "ip2", then run against 2nd ip.
In fact I have many cases to run against 2 ips, not only 2. and the ip information (as well some other information of the two hosts) are written in an json file. So I would like to find out a general and simple solution.
I tried but didn't get it.
I thought maybe do something in the conftest.py file? for example, before the case running, judge the mark or the name? But don't know how to handle.
Looking forward to your advice, to my first question in stackoverflow! :)
thanks very much!
Answer: Don't quite understand, and it's hard to understand more without seeing an example test, but how about using parameters to determine which ips are passed in.
Say you have a test to check ips are accessible. This would be one way to do it, but it's not very nice or extensible.
def test_ip_accessible():
    assert is_accessible("192.168.2.23")
    assert is_accessible("192.168.2.100")

Instead you can create helper functions that return specific ips, or a list of ips, and then use these as parameters.

ip_map: Dict[int, str] = {  # ip id to address
    1: "192.168.2.23",
    2: "192.168.2.100",
    3: "192.168.2.254",
}

def get_single_ip(id_: int) -> str:
    return ip_map[id_]

def get_multiple_ips(*ids) -> Tuple[str]:
    return tuple(ip_map[i] for i in ids)

@pytest.mark.parametrize("ip_address", [get_single_ip(1), get_single_ip(2)])
def test_ip_accessible(ip_address):
    # ip_address will be 192.168.2.23 then 192.168.2.100 in two separate tests
    assert is_accessible(ip_address)

@pytest.mark.parametrize("ip_addresses", [get_multiple_ips(1, 2), get_multiple_ips(2, 3)])
def test_with_multiple_ips(ip_addresses):
    # this test will also be run twice. the first time, ip_addresses will be
    # ["126.96.36.199", "192.168.2.100"]. the second time, it will be
    # ["192.168.2.100", "192.168.2.254"].
    assert something_with_a_list_of_ips(ip_addresses)


How to create a zip archive from a bytes data in Python 3

Question: I am trying to get a file data from a REST WS response, when I print the file data. I get something like:
PK  aB™OÉf         TestFile.txtÉÈ,V ¢D…'Ôâ…´ÌœT PK  aB™OÉf                 €    TestFile.txtPK      :   =

When I print the type of the file, I get the following:
<class 'str'>

I am having trouble writing the contents of the file data to a file path, I used the following approach in order to write the file data.
f = open(filename_path, 'w+',errors='ignore')
for chunk in file_data:
    f.write(chunk)

I also tried to convert the string data to bytes and tried writing it to file path without success. Please suggest me a way to overcome this problem.
bytes_file_data = file_data.encode()
with open(filename_path, 'w') as f:
   f.write('bytes_file_data')

This will return the file from WS response and then this is being passed as a parameter as file_data
response = get_data('get/file/' + str(token))

def get_data(urlPart):
   URL = 'some/url/path+'urlPart
   headers = {'Content-Type':'application/json;charset=UTF-8'} response =
   requests.get(url = URL, verify=False, headers = headers, auth=(requester,''))
   if response != None:
      if response.text:
          if isfile == True:
              responsetext = response.text
return responsetext

Comment: `w+` is almost always the wrong filemode, use `w`
Comment: You have to read the result of the REST-Request as bytes. Please show that part of the code.
Comment: bytes_file_data = file_data.encode()
with open(filename_path, 'w') as f:
                f.write('bytes_file_data')
Even I tried with 'wb' without much success.
Comment: please show the code that generates `file_data`.
Comment: I am getting file_data as a response from WS in the form of :

PK  aB™OÉf         TestFile.txtÉÈ,V ¢D…'Ôâ…´ÌœT PK  aB™OÉf                 €    TestFile.txtPK      :   =
Comment: please show the code of your WS-call. There you find the error.
Comment: response = get_data('get/file/' + str(token))

def get_data(urlPart):
    URL = 'some/url/path'
    headers = {'Content-Type':'application/json;charset=UTF-8'}
response = requests.get(url = URL, verify=False, headers = headers, auth=(requester,''))
if response != None:
            if response.text:
                if isfile == True:
                    responsetext = response.text
Comment: please, edit your question. How does `responsetext` and `file_data` fit together?
Comment: responsetext  is returned from a different function and passed as a parameter file_data to the current method where I am trying to write this response.
Comment: `f.write('bytes_file_data')` is hopefully a typo. Remove the quotes from the name, and open the file with a `b` in the mode.
Comment: Why are you using `response.text` when the content isn't text?
Comment: Your question is not detailed enough. You need to provide both server and client side of a code, or at least description of that REST server you are using.
Answer: You have to use response.content if you get binary data as result.
The header argument seems to be ignored by your REST server. You also don't have a websocket (WS) response, which was very confusing to me.
Simplifying to the basic parts, this should solve your problem:
def get_binary_data(url_part):
    url = 'some/url/path/' + url_part
    response = requests.get(url=url, verify=False, auth=(requester, ''))
    return response.content

file_data = get_binary_data(f'get/file/{token}')
with open(filename_path, 'wb') as output:
    output.write(file_data)

Comment: I still have the same issue as earlier that after writing while I try to extract I get the error: The archive is corrupt, I believe I am doing something wrong while writing the data to the folder.
Comment: without further information about the service you call, nobody can help you.
Comment: Sorry for the late update. I was doing something wrong on my part that I figured it out but the above solution from Daniel help me resolve this issue. Thanks, Daniel & others for the prompt help.


Prove that if $(m - 1)! + 1$ is divisible by $m$, $m$ is a prime with $(m - 1)! = 1.2.3...(m - 2)(m - 1)$

Question: $m$ is a positive integer, and $ m > 1$,
Prove that if $(m - 1)! + 1$ is divisible by $m$, $m$ is a prime.
Solve this by making a contradiction.
My english isn't so well.
Please help and thank you for your attention :)
Comment: The converse is also true; see [Wilson's Theorem](http://en.wikipedia.org/wiki/Wilson's_theorem).
Answer:
Let $m$ be a positive integer $> 1$. Show that if $(m-1)! + 1$ is divisible by $m$, then $m$ is a prime.

HINTS

Suppose, for the sake of contradiction, that $m$ is not prime. Then there is some prime $p<m$ such that $m = pk$, i.e. such that $p \mid m$.
Since $p \mid m$, we can say something about $p$ dividing or not dividing $(m-1)!$.
In general, if a number $a>1$ divides another number $b>1$, then we cannot have that $a \mid (b+1)$, as in the typical proof of the infinitude of primes.
Comment: I can't understand the $p<m$ such that $m=pk$, i.e. such that $p∣m$

What is the $|$
Comment: Every number can be written as a product of primes. Thus if $m$ is not prime, a smaller prime divides it.
Comment: @Vchau_VN $p|m$ means "p divides m" or "m is divisible by p".
Comment: @Mike: Aha - I missed that he missed that part. Thanks for that!
Answer: If $m$ is not a prime, then it obviously contains some prime factor $m'$ such that $1<m'<m$. Thus $m'|(m-1)!$. Then given $m'|(m-1)!-1$, it follows that $m'|1$ which is impossible.
Answer: If m is not a prime, it has a prime divisor $p<m\implies p≤m-1$, hence $p\mid(m-1)!$.
But as $p\mid m$ and $m\mid((m-1)!+1)$  so, $p\mid((m-1)!+1)$
$\implies p\mid((m-1)!+1-(m-1)!)$ as $q\mid a$ and $q\mid b\implies q\mid (ax+by)$ where $a,b$ are any integers.
$\implies p\mid 1\implies m$ can not have divisor p such that $1<p≤m-1$, hence $m$  must be prime.
Comment: I rectified the lapsus calami.
Answer: If $m$ divides $(m-1)!+1$, there exists $k \in \mathbb{Z}$ such that $(m-1)!+1=km$ so $-(m-1)!+km=1$. From Bézout's identity, you deduce that for all $n <m$, $n$ and $m$ are relatively primes ($n$ appears in the product $(m-1)!$). So $m$ is necessarly prime.


Customize BIRT "Export Report" dialogue box

Question: In Export Report dialogue box, we want to provide a new option "Choose XSLT" if user selects "Export Format" as XML.
How to customize this dialogue box?
Answer: This can be customized in a JSP page:
[birt app root]/webcontent/birt/pages/dialog/ExportReportDialogFragment.jsp
However the emitter probaly needs to be customized too to take this new input into consideration
Comment: Thanks @Dominique. That's the file which we were looking for !


unsupervised Time series anomaly detection

Question: I have 3D printer that working exactly 400 second for printing element X [0-400].
The printer produce 30 signals (features like VOLT,X,Y,Z,TEMP etc') in frequency of 50HZ (every sample 0.02 ms) ,for every print I monitor this features in log with time tag (0-400) .
The features are not stationary during the activation (changed ) ,the features also depends. The features value can be change from one printing to another (not exactly ), the duration of printing can change for example coloring mission can take more time in one print than other .
I want to create automate system that will detect if there anomaly (problem) during the printing process without human check  .
I have more than 100 logs (printing logs of element of type X) that I sure the are good.
I am looking machine learning algorithm for unsupervised feature learning for time series that will give me the ability to classify if the printing is good or not, I think about LSTM or DBN (deep belief Net) but something say to me their another option that may I don't know    .
Thanks.
MAK
Comment: In your scenario are you always printing the same object?
Answer: you need not to have a time series algoritm for anomaly detection-
First of all Identify- "WHAT IS ANOMLAY IN YOUR APPLICATION", there is no algorithm that will give u direct abnormality. they are focused on outlier detection.
1) If you can generate some data at abnormality, build a classification model.
2) Can you build a relation among variables present in data. Find a relation by NN or regression, any deviation from known relation is abnormality.
3) If outliers are abnormalities in your application. I can share some links like- https://machinelearningstories.blogspot.com/2018/07/anomaly-detection-anomaly-detection-by.html
Answer: Have a look at https://github.com/datamllab/tods for anomaly detection in timeseries
Answer: I've built a number of anomaly detectors for streaming data. Here's what I would suggest:
First, consider each of your 30 features (signals) independently, i.e., build an unsupervised anomaly detector for each feature and run them in parallel. For a given component, I would:

create bins for the values, e.g., if $x$ is in range [0,100], maybe make 10 bins [0,10), [10, 20), .. Or for something like temp, maybe your bins are [0,70), [70, 85), [85, 95), [95, 100), [100, 140), [140, infinity). Varying the width of the bins may help with some dominating all of the data. Since you're looking for anomalies, you will want the bins to be crafted so you can have less likely bins than others. On the other hand you don't want bins that never occur and ones that always occur.
create a multinomial (a die) with the probability of a new data feature/signal observation landing in each bin. To do this, before you see any data, instantiate the bin count to 1 for all bins and store the denominator as n (number of bins).
given a new observation of the signal, you will compute its p-value, then increment the count of the bin it landed in and the denominator.

E.g., suppose  we have three bins, $b1, b2, b3$. We initialize
counts = {b_1: 1, b_2: 1, b_3: 1}
n = 3
This means the multinomial when starting is $p(bj) = 1/3 $ for $j = 1,2,3$.
def p(b): return counts[b]/n
Suppose we see new data (signal) with value $x1$ and it lands in bin $b2$. First, we compute the p-value$(b_2 = \sum_{\{j:p(b_j)<= p(b_2)\}} p(b_j) = 1$ (b/c all bins have the same probability at start). Next we'd increment the count of $b_2, n$:
counts[b_2] += 1
n+=1
Second, suppose we see a second value $x_2$ that lands in bin $b_3$. Then we'd repeat the previous paragraph, computing p_value$(b_3)$ (and you'll get 2/3), and incrementing bin b_2's count and the n.
Finally, those signals with low p-value are the anomalies.
This has lots of advantages: your p-values are comparable across all these different signals, and across time (note that your distribution is changing in time); it is fast and easy to implement. you can alert or look back over historical data;
These papers describe this workflow or an application of it in more detail:

https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=6406752
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8258031
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8440825


windows not accepting static dns from mikrotik

Question: I have mikrotik on which I set up static DNS entries for my network. Form linuxes everything works correctly even from one of windows computers (windows 7) but from other windows computers I can't resolve dns entries. I don't know where to find the issue. Please can you suggest where should I start?
Thanks
Answer: use "device.lan" instead of "device" in your static DNS entries
Comment: This works! It can be any names but it needs a dot in between.
Answer: Some advises:

Try to use on windows ipconfig /flushdns
On Mikrotik /ip dns cache flush
On Mikrotik open/allow TCP/UPD 53 port
Check that the windows instances has correct DNS (mikrotik IP)


Negative square roots of Reals in inequalities

Question: Where r $ \epsilon \Bbb { R,}$
determine the range of r.
$$\left\lvert 1-2 \sqrt{-r}\right\rvert < 1$$
$$-1< (1-2 \sqrt{-r}) < 1$$
$$-2< (-2\sqrt -r) < 0 $$
$$1>(\sqrt -r) > 0$$
The answer is: $-1<r<0$
So why do I not believe it was found using the following?
continuing from above at $\quad1>(\sqrt -r)> 0 $
$$(1)^2>(\sqrt -r)^2>(0)^2 $$
$$1> -r > 0$$
$$-1<r<0$$
This is where I began to wonder about $\;(\sqrt -r)^2$
and why not...$\;(-{\sqrt -r})^2$ too?
Because $\quad(-{\sqrt -r})*(-{\sqrt -r})\neq \sqrt -r$ or does it? I must keep firm that r is not complex, r is in the reals.
I know I am missing something but am not sure what that is. Can anyone please tell me what I am not understanding about these statements?
Thanks.
Comment: Let $r'=-r$ and do the computation with $r'$ instead. It may be way less confusing this way.
Comment: "*Because $(-\sqrt{-r})*(-\sqrt{-r})\neq \sqrt{-r}$ or does it?*"  You surely have a typo there somewhere, the expression on the left is of cardinality $|r|$ while the expression on the right is only of cardinality $|\sqrt{r}|$.  Either way, you seem to be reaching for something along the lines of how [$\sqrt{(-1)\times(-1)}\neq (\sqrt{-1})^2$](https://math.stackexchange.com/questions/438/why-sqrt-1-times-1-neq-sqrt-12).
Comment: "I began to wonder about $(\sqrt{-r})^2$ and why not ... $(-\sqrt{-r})^2$ too".  $(\sqrt{-r})^2= (-\sqrt{-r})^2$.  "Because $(-\sqrt{-r})*(-\sqrt{-r})\neq \sqrt{-r}$ or does it".  Well, no, but $(-\sqrt{-r})*(-\sqrt{-r})=(\sqrt{-r})*(\sqrt{-r})=-r$.
Answer: $$\left\lvert 1-2 \sqrt{-r}\right\rvert < 1$$
Let r=-x, then we have  $$\left\lvert 1-2 \sqrt{x}\right\rvert < 1$$
$$-1<1-2 \sqrt{x}<1$$
$$-2<-2 \sqrt{x}<0$$
$$0<2 \sqrt{x}<2$$
$$0<\sqrt{x}<1$$
$$0<x<1$$
$$0<-r<1$$
$$-1<r<0$$


stop windows service in onStart() method

Question: I want to stop windows service in onStart() method when customer doesn't have a license. I use service.Stop(), but it does not work.
protected override void OnStart(string[] args)
{
    try
    {
        _bridgeServiceEventLog.WriteEntry("new OnStart");
        if (LicenseValidetor.ValidCountAndTypeDevices())
        {
            WsInitializeBridge();
        }
        else
        {
            service = new ServiceController("BridgeService");
            service.Stop();
            _bridgeServiceEventLog.WriteEntry("LicenseValidetor Error");
        }
        _bridgeServiceEventLog.WriteEntry("end Start");
    }
    catch (Exception e)
    {
        _bridgeServiceEventLog.WriteEntry("error In onstart method ");
    }

}

Comment: Um. If it's the same service as you're running in, then simply exiting the `OnStart` method without leaving any other threads running will stop the service.
Comment: What is `service`?  And are you sure that the line of code is being hit?
Comment: Are you doing This Remotely? Or from the Client machine?
Answer: You cannot stop a service from within the OnStart method of that same service.
The ServiceController.Stop method internally calls ControlService (or it's Ex counterpart). Notice that one of the reasons that this function can fail is:

ERROR_SERVICE_CANNOT_ACCEPT_CTRL
  The requested control code cannot be sent to the service because the state of the service is SERVICE_STOPPED, SERVICE_START_PENDING, or SERVICE_STOP_PENDING.

Well, guess what - when you're inside your OnStart method, the state of your service is SERVICE_START_PENDING.

The correct way to cope with this situation is to signal any other threads that you may have started to have them exit, and then to exit your OnStart method. The service control manager will notice that the process has exited and revert your service status to SERVICE_STOPPED. It may also notify an interactive user that "The service started and then stopped" or words to that effect.
Comment: Hi. Could you expand on the "signal any other threads" comment? If I am running a service (with TopShelf in my case), I would have thought my program's thread is the only thread running. Why would other "threads" be running? Thanks
Comment: @Fandango68 - that sentence continues with "that you may have started". So if you haven't started any other threads, you can ignore that sentence. Note that it's not all that uncommon for services to run multiple threads and the point here is that if you leave any other (foreground) threads running, the service won't be considered to be stopped.
Answer: I want to add that "simply not starting any workers" may not work (or perhaps I am being just plain stupid ;) ).
I built a service, with a try/catch(all) around my OnStart code. Because of a missing line in my .config file it crashed with an IOException, before it started any worker thread. The exception skipped over my thread starters. No thread was started by my code. Honestly.
But the service DID NOT STOP. I don't know why. As a desperate measure, I rethrew the exception, that helped.
I am still wondering if the file system watcher threads in Enterprise Library configuration were the problem. EntLib is woven to deeply into my code to remove it as an experiment, so I did not investigate further.
Answer: The accepted answer explains why what you are doing doesn't work but doesn't offer a good solution.
There are a couple of things your code isn't doing that it should.

Set the .ExitCode to indicate that your service is in an error state.
Throw an exception. Not having a license is exceptional. Throw it.

EXAMPLE:
protected override void OnStart(string[] args)
{
    _bridgeServiceEventLog.WriteEntry("new OnStart");
    try
    {
        if (LicenseValidetor.ValidCountAndTypeDevices())
        {
            WsInitializeBridge();
        }
        else
        {
            throw new ApplicationException("LicenseValidetor Error");
        }
    }
    catch (Exception e)
    {
        this.ExitCode = e.HResult
        _bridgeServiceEventLog.WriteEntry($"error In onstart method: {e.Message}");
        throw
    }

    _bridgeServiceEventLog.WriteEntry("end Start");
}

Answer: I have noticed that your not waiting to ensure that the Service has actually stopped or if it is even running in the first instance.
Do this :-
protected override void OnStart(string[] args)
{
    try
    {
        _bridgeServiceEventLog.WriteEntry("new OnStart");
        if (LicenseValidetor.ValidCountAndTypeDevices())
        {
            WsInitializeBridge();
        }
        else
        {
            int time = 10000;

            TimeSpan timeout = TimeSpan.FromMilliseconds(time);

            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

            _bridgeServiceEventLog.WriteEntry("LicenseValidetor Error");
        }
        _bridgeServiceEventLog.WriteEntry("end Start");
    }
    catch (Exception e)
    {
        _bridgeServiceEventLog.WriteEntry("error In onstart method ");
    }
}


How to select from a table in a different database in SQL Server 2008

Question: I have many database instances say for e.g EWB1,EWB2,EWB3 and so on..if suppose I am in EWB1 and I want to access a particular table's column from other nstances (in this case say EWB2,EWB3 and so on).. I am doing something like this
declare @name varchar(10);
DECLARE cur3 CURSOR FOR select EnterpriseDBInstance from [EWB_DAL].[dbo].[Enterprise] where EnterpriseDBInstance <>  CONVERT(varchar(10),DB_NAME());
OPEN cur3;
Fetch next from cur3 into @name;
WHILE @@FETCH_STATUS = 0
BEGIN
declare @test varchar(10);
set @test = (select @name);
select ChapterName from [@test].[dbo].[FormData] -- This line is giving error
                                                 -- unable to find @test....
Fetch next from cur3 into @name;
END
close cur3;
deallocate cur3;

But I could see EWB2,EWB3... in @test..
Comment: What database are you using? Each vendor has a different way of supporting such functionality (if at all). What is "SQL 2008"? Do you mean SQL Server 2008?
Answer: You can't use database names dynamically (i.e using variables), in the same way that you can't use table or column names in such a manner.
The query you have is trying to find a database named @test.
You need to look at using dynamic SQL for such work, or rethink your approach. I suggest reading The Curse and Blessings of Dynamic SQL by Erland Sommarskog.
Answer: use qoutename like qoutename(ur DB variable name) this works...


How to load script component of a prefab on an AssetBundle in Unity3D?

Question: So I have a gameObject(Let's call it XX) and I have created a Prefab of XX that contains a script (the XX prefab has a script component). When I build the AssetBundle and I load XX on a button click the gameObject of XX loads correctly but the script component doesn't come along. Is there a way to load XX with the script component?
Thanks!
Comment: Taking a look at [AssetBundle](https://docs.unity3d.com/Manual/AssetBundlesIntro.html) it is platform-specific non-code Assets. This might help: https://forum.unity.com/threads/missing-scripts-on-loading-scene-asset-bundle.590824/
Answer: The Solution to my question is that you create the asset bundle from your model-object and then through code you AddComponent to this. Something like this: MyClass xx = anObject.AddComponent(typeof(MyClass)) as MyClass;


Tomcat, wildcard subdomains?

Question: Is this possible with Tomcat?
Answer: Please use apache in front of tomcat for best results.
Use ajp connector and mod_proxy_ajp in your configs. Mod_jk is not that good as mod_proxy_ajp IMHO.
HTH

Tomcat, wildcard subdomains?


Showing that $\left(1-2p^{2}\sin^2{\omega}\right)^2 + p^{2}\sin^{2} w\leq 1$ implies $4p^2 \leq 4$

Question: If $\xi = 1-2p^{2}\sin^{2} \omega -ip\sin w$, then the modulus of $\xi$ is
$$|\xi|^{2} = \left(1-2p^{2}\sin^2{\omega}\right)^2 + p^{2}\sin^{2} w$$
For $|\xi|^2 \leq 1$,
$$4p^2 \leq {4\sin^2{\omega \over 2}-\sin^2\omega \over \sin^4{\omega \over 2}}= 4$$
I am not sure how to get the second line. Can anyone show me? I have expanded out the bracket, etc, but do not get this expression.
Comment: You have sufficient rep to indicate that you ought to be using mathjax within your posts, and not an uploaded image.  Please edit this post to use mathjax to express what is in the image.
Comment: Also, please show your work, after, as you claim, you expanded out the bracket.
Comment: If you're going to edit the post *for* the OP, do so correctly, @ChristianF
Comment: I had just last line in my proof so I edit only that one.
Answer: Since $$1\geq 1-4p^2\sin^2{\omega \over 2}+4p^4\sin^4{\omega \over 2}+p^2\sin^2\omega$$
we have $$0\geq p^2(-4\sin^2{\omega \over 2}+4p^2\sin^4{\omega \over 2}+\sin^2\omega)$$
so  $$0\geq -4\sin^2{\omega \over 2}+4p^2\sin^4{\omega \over 2}+\sin^2\omega$$
so $$ 4\sin^2{\omega \over 2}-\sin^2\omega\geq 4p^2\sin^4{\omega \over 2}$$
so $$ {4\sin^2{\omega \over 2}-\sin^2\omega \over \sin^4{\omega \over 2}}\geq 4p^2$$
Comment: thank you, i understand now.


PHP: elementos com e sem chaves explicitas numa mesma array

Question: Estou tentando descobrir uma forma melhor ou mais limpa de fazer algo assim em PHP:
// Isto será passado como argumento de uma função...
$params = array('Nome', 'Idade', 'Mail' => 'firstname.lastname@example.com');

"Nome" e "Idade" são valores com chaves atribuídas automaticamente (0 e 1, por exemplo), e "Mail" é uma chave com o valor "firstname.lastname@example.com":
[0] => 'Nome',
[1] => 'Idade',
['Mail'] => 'email@example.com'

Quando eu passo isso por um loop "foreach", estou fazendo isso para ter "Nome" e "Idade" como os parâmetros de fato:
foreach ($params as $k => $i) {

    // Esta é a parte "feia"!
    if (is_int($k)) {
        $k = $i;
        $i = false;
    }

    // Para fazer algo assim, por exemplo...
    $out = "";
    if ($i) {
        $out .= "
$k
\n";
    } else {
        $out .= "
$k
\n";
    }

}

O que irá retornar algo assim:

Name

Age

Mail

A questão é: existe uma forma limpa do PHP diferenciar os elementos de uma mesma array que possuem uma chave explícita (Mail => firstname.lastname@example.com) dos que não possuem (Nome e Idade)?
Observação: o código acima foi dividido em duas etapas para melhor entendimento da solução atual, que é diferenciar o valor da chave testando se ele é uma integer, mas o código que estou usando na verdade é:
$o = "";
foreach ($params as $k => $i) {
    if (!is_int($k)) {
        $o .= "
$k
\n";
    } else {
        $o .= "
$i
\n";
    }
}

Comment: Para capturar os argumentos: http://php.net/manual/pt_BR/function.func-get-args.php
Comment: Não seria mais intuitivo ter `array('Nome'=>null, 'Idade'=>null, 'Mail' => 'firstname.lastname@example.com')`?
Comment: @bfavaretto Sim, se este procedimento não estivesse dentro de uma função genérica para, por exemplo, criar linhas de uma tabela, onde a tag "td" poderia ou não ter parâmetros adicionais. O ideal seria: funcao_tal('nome', 'idade', array('mail' => 'firstname.lastname@example.com')), mas não sei se existe uma forma do PHP entender que a quantidade de argumentos da função pode variar. Ao mesmo tempo, passar todo o argumento como uma única string e fatiá-lo depois seria igualmente sujo. Veja também que estou querendo aproveitar o novo formato de arrays do PHP>=3.4 "[elementos]", por uma questão de legibilidade.
Comment: Não entendo o que você quer dizer com sujo? Por não ser dinâmico? Não vejo problema algum nisso, talvez seja só gosto pessoal seu.
Comment: @Marcelo Aymone, eu acabei de descobrir isso e de fato é a solução. Muito obrigado.
Comment: Fico feliz que isto ajudou a encontrar a resposta, abração!
Answer: Ao que tudo indica, a resposta para a pergunta original é mesmo não, não existe um modo do PHP diferenciar elementos com e sem chaves dentro de uma mesma array.
Mas, o problema original derivava da necessidade de criar uma função legível onde a quantidade de argumentos passados poderia variar, daí a opção inicial por uma array, que permitiria uma chamada assim:
add_table_row(['Nome', 'Idade', 'Mail' => 'firstname.lastname@example.com']);

ou assim...
add_table_row(array('Nome', 'Idade', 'Mail' => 'firstname.lastname@example.com'));

Contudo, como acabei de descobrir, existe uma forma de passar uma quantidade variável de argumentos para uma função, utilizando a função "func_get_args()", e a chamada da função pode ficar ainda mais legível:
// PHP >= 5.4
add_table_row('Nome', 'Idade', ['Mail' => 'firstname.lastname@example.com']);

ou
add_table_row('Nome', 'Idade', array('Mail' => 'firstname.lastname@example.com'));

Portanto, um exemplo do código completo da função seria algo assim:
function add_table_row() {
    $args = func_get_args(); // retorna uma array de argumentos...
    $o = "
\n";
    foreach ($args as $value) {
        if (is_array($value)) {       // Se o argumento é uma array...
            $cont = key($value);      // O dado da célula é a chave...
            $param = current($value); // E o parâmetro da tag é o valor...
            $o .= "$cont	\n";
        } else {
            $o .= "$value	\n";
        }
    }
    $o .= "
\n";
    return $o;
}

Espero que isso seja útil a mais alguém.
Comment: isso é permitido sim. Escolha sua própria resposta como resolvendo o problema
Comment: Outra maneira bem comum é passar uma única array para a função, com outras dentro se necessário. Por exemplo: `add_table_row(['Nome', 'Idade', ['Mail' => 'email@example.com']]);`. Dentro da função, você pode checar se cada um dos itens é outra array com `is_array()`.
Answer: Já que você vai criar uma função para isso, você pode passar como string e encontrar os elementos marcadores... Basta explodir nas , e se houver : a função vai entender que é um array.
add_table_row('Nome,Idade,Mail:firstname.lastname@example.com')
    function add_table_row( $string )
    {
        $string = explode( ',' , $string );

        foreach( $string as $line )
        {
            if( strpos( $line , ':' ) && $elementos = explode( ':' , $line ) )
            {
                echo $elementos[0] . ', ' . $elementos[1];
            }
            else
            {
                echo $line;
            }
        }
    }

output
Nome
  Idade
  Mail, email@example.com
Comment: esse foi o meu primeiro impulso, até porque geralmente eu uso e abuso das implosões, explosões e outras operações com strings. Só que isso implica em processar os dados duas vezes: na preparação da string dos argumentos e na "decodificação" dentro da função. Já usando uma array (ou com func_get_args(), como foi minha escolha), eu só preciso preparar os dados para a função, que por sua vez fica muito mais limpa, objetiva e legível, eu acho. Mas a sua solução é tão boa quanto qualquer outra.


C# How to sync Two Lisboxes with MultiSimple as SelectionMode

Question: As the question suggests, I have two listboxes. I use one to get me the ID from the database, and another to display the related information to the user.
I've been using this for other tables like:
int IDIndex = Listbox1.SelectedIndex;
ListBox2.SelectedIndex = IDIndex;

How do I do that if ListBox1 has more than one item selected?
@Edit: The following code is what I've used for this. Check @Pikoh's answer also
Boolean IndexChanged = false;
int IDIndex = -1;
foreach(int ind in ListBox1.SelectedIndices)
{
    if (!ListBox2.SelectedIndices.Contains(ind)) {
        ListBox2.SetSelected(ind, true);
        //Index Selected: ind
        IDIndex = ind;
        IndexChanged = true;
    }
}
if (!IndexChanged)
{
    foreach (int ind in ListBox2.SelectedIndices)
    {
        if (!ListBox1.SelectedIndices.Contains(ind))
        {
            ListBox2.SetSelected(ind, false);
            //Index Deselected: ind
            IDIndex = ind;
            IndexChanged = true;
        }
    }
}

This allows me to know which index was changed. My program has to know this to check the database for the related information.
Comment: Is it winforms?
Comment: Yes, with visual studio
Answer: You can use the SelectedIndices collection. Then, you can do something like:
if (Listbox1.SelectedIndices.Count>0)
{
     IDIndex = Listbox1.SelectedIndices[0];
}

Or
IDIndex = this.listBox1.SelectedIndices.Cast<int>().First();

Or you can loop on the collection. It depends on the behaviour you want. This answer assumes a Winforms Listbox
Edit
If you want to replicate the selected indices of Listbox1 in Listbox2, you can do something like this:
Listbox2.ClearSelected();
foreach (int ind in Listbox1.SelectedIndices)
{
     Listbox2.SetSelected(ind, true);
}

Comment: The behaviour I want is, if user selects [0], system will select [0] in the second ListBox. If the user, then, selects [2], [2] is selected as well. If User deselects [2], only [0] will be selected. And so on. Should I use a cycle for that?
Comment: I've inserted my code up there (the one I'll be using)


Chow test or not?

Question: I am trying to set up an automatic screen to detect structural breaks in large numbers of time series.
The time series are weekly and represent behaviour of customers. I have set up a Chow test. I use the most recent 4 weeks and compare it to the preceding 22. I want to know if their recent behaviour has significantly diverged from the preceding behaviour.
My question is this:

Is the Chow Test the most appropriate test for this question?

If this is not the most appropriate test how can I determine what test is the most appropriate one?
Comment: Search on the "change-point" tag for some leads: http://stats.stackexchange.com/questions/tagged/change-point
Answer: Your question is most interesting to me and it's solution has been my primary research for a number of years.
There are a number of ways that "a structural break" may occur.
If there is a change in the Intercept or a change in Trend in "the latter portion of the time series" then one would be better suited to perform Intervention Detection (N.B. this is the empirical identification of the significant impact of an unspecified Deterministic Variable such as a Level Shift or a Change in Trend or the onset of a Seasonal Pulse ). Intervention Detection then is a pre-cursor to Intervention Modelling where a suggested variable is included in the model. You can find information on the web by googling "AUTOMATIC INTERVENTION DETECTION" . Some authors use the term "OUTLIER DETECTION" but like a lot of statistical language this can be confusing/imprecise . Detected Interventions can be any of the following (detecting a significant change in the mean of the residuals );

a 1 period change in Level ( i.e. a Pulse )
a multi-period contiguous change in Level ( i.e. a change in Intercept )
a systematic Pulse ( i.e. a Seasonal Pulse )
a trend change  (i.e. 1,2,3,4,5,7,9,11,13,15 ..... )

These procedures are easily programmed IN R/SAS/Matlab and routinely available in a number of commercially available time series packages however there are many pitfalls that you need to be wary of such as whether to detect the stochastic structure first or do Intervention detection on the original series.  This is like the chicken and egg problem. Early work in this area was limited to type 1's and as such will probably be insufficient for your needs .
If no such phenomenon is detected then one might consider the CHOW TEST which normally requires the user to pre-specify the point of hypothesized change. I have been researching and implementing procedures to DETECT the point of change by evaluating alternative hypothetical points in time to determine the most likely break point.
In closing one might also be sensitive to the possibility that there might have been a structural change in the error variance thus that might mask the CHOW TEST leading to a false acceptance of the null hypothesis of no significant break points in parameters.
Comment: Thankyou very much. I will do the search and the reading.

Chow test or not?