Display block based on main content type with view

Question: I have created a view in a block, to display some related information to the current content type being displayed into the block. More precisely, I want to display the block only for book pages.
What I did is to add a contextual filter based on content type.
For "WHEN THE FILTER VALUE IS NOT AVAILABLE", I provide a default value for "PHP contextual filter code" as follows
$node = node_load(arg(1));
return $node->type;

For "WHEN THE FILTER VALUE IS AVAILABLE", I use "Specify validation criteria" for content types with "book page".
I tried this but it didn't work. I think because I am using aliases in the url, it does not work.
What am I missing?
P.S: My final goal is actually to extract the group audience from the current book page and display the admins of that group into the block.
Answer: In your case you don't need to provide any default value with PHP code.
Remove your contextual filter and add new one: Content: nid.
"WHEN THE FILTER VALUE IS NOT AVAILABLE"
Provide default value -> content ID from URL
"When the filter value IS available or a default is provided"
Specify validation criteria
Validator -> Content -> book
Answer: Why are you checking the content type with the view?
If I understood your question, you want to display the view's block only on certain content type ('Book').
A much easier solution will be:

Go to Dashboard >> Structure >> Blocks
Find the view's block and go to its configuration
Under the 'Content Types' tab add 'Book'

That is it!


Terms in Fourier Series

Question: Can any one explain why?
$$\int_0^\pi \sin(nx)\sin(mx)\,dx=\begin{cases}0,&n\not=m,\\ {\pi\over 2},&n=m,\end{cases}$$
and
$$\int_0^\pi \cos(nx)\cos(mx)\,dx=\begin{cases} 0, &n\not=m,\\ {\pi\over 2},  &n=m,\end{cases}$$
Comment: Simply use the formulas $$ 2\sin a\sin b=\cos(a-b)-\cos(a+b), \\
Comment: NB there should be some additional condition on $m, n$, say, requiring them both to be positive integers.
Comment: This *must* be a duplicate...
Answer: HINT:
Use Werner Formulas
 $$2\sin mx\sin nx=\cos(m-n)x-\cos(m+n)x$$
$$2\cos mx\cos nx=\cos(m-n)x+\cos(m+n)x$$
See the difference in behavior for  $m=n$
Answer: Observe that the set $\{1,sinx,sin2x,...sinmx,cosx,...,cosmx\}$ is an orthonormal basis of the space of $2\pi$ -periodic functions ,let's say $T_m$,which is a Hilbert space with inner product $<f,g>=\frac {1}{\pi}\int_{-\pi}^{\pi} f\cdot g$. The only way i know to prove it ,is by using the formula above,though.

Terms in Fourier Series


Design of Experiments: Factorial design 2^2 with center point added. Does it make sense?

Question: This question is about factorial design of experiments, let's say with two factors $x_1$ and $x_2$ in the following picture. In a $2^2$ factorial design there would be only the black circles. But what if I add the center point in blue? Intuitively I would think one gains some information about the curvature of the response or at least about the current experimental design in comparison with some variations. Does it make sense to add the center point??

The background of my question is about an experiment I'm thinking about where blue is the current configuration and black points are $\pm10\%$ variations of some input parameters. I remember from some DoE trainings to have read about $2^k$ factorial design but intuitively I think that the information about the current configuration should be important.
Comment: It's a good idea.  See https://www.google.com/search?q=experimental+design+center+point.
Answer: This is a matter of what model you fit and your experimental objective.
The short answer is that including a central point (a) makes it possible to detect when a more complicated model is needed and, regardless, (b) is required if you are searching for optimal responses.
Let's look at some of the possibilities.
1. Linear fit
Assuming you want to model some differential among the responses, about the simplest model that allows for (a) an average value to be estimated and (b, c) variations along both the $x$ and $y$ coordinates would take the form
$$z = \beta_0 + \beta_1 f(x) + \beta_2 g(y) + \text{error}$$
where $f$ is some specified function expected to describe variation in the $x$ coordinate (up to some multiple $\beta_1$ to be estimated) and likewise for $g$ relative to $y.$  Generally, $f$ and $g$ are "feature engineering" functions that transform the data $(x,y)$ as recorded into variables $(f(x), g(y))$ you hope are linearly related to the response $z.$  The very simplest case takes $f(x) = x$ and $g(y) = y,$ where you don't transform the data at all.
Geometrically, this model fits a plane to the data.

In this pseudo-3D image, colors indicate function values and $f$ labels the "height" or "response" axis.
It is a geometrical fact, going back to Euclid, that to determine a plane you need to make observations at a minimum of three distinct, non-collinear points in the plane.  Taking the values of the features at these three points to be $(f_1,g_1),$ $(f_2,g_2),$ and $(f_3,g_3),$ an algebraic statement of this criterion is
$$\det \pmatrix {1 & f_1 & g_1 \\1 & f_2 & g_2 \\ 1 & f_3 & g_3} \ne 0.$$
This generalizes to more variables, as we will see.
2. Linear fit with interaction
This model includes one more feature formed from the product of the two features, known as an "interaction:"
$$z = \beta_0 + \beta_1 f(x) + \beta_2 g(y) + \beta_{12} f(x)g(y) + \text{error}$$
It requires one more parameter $\beta_{12}$ to be fit.
Geometrically, this model fits a ruled surface to the data.

When $f = x$ and $g = y,$ the gridlines are straight.  That is because each one traces out points on the surface whether one of $x$ or $y$ is fixed.  For instance, taking $y$ to be constant, any such gridline satisfies the equation
$$z = (\beta_0 + \beta_2 y) + (\beta_1 + \beta_{12}g(y)) x = \alpha_0 + \alpha_1 x,$$
which as $x$ varies describes a line.
Such a model would be indicated when the estimate of the interaction coefficient $\hat\beta_{12}$ is significant: that is, it is so much larger in size than its standard error that you would be uncomfortable not including the interaction.
A basic theorem about ruled surfaces is that every point on a smooth, non-flat ruled surface has negative Gaussian curvature.  For optimal response surface design that is really bad, because at a point of negative curvature the surface curves up in one direction and down in perpendicular directions.  Maxima and minima don't exist!
Incidentally, the criterion for fitting all four parameters to the data is that
$$\det \pmatrix {1 & f_1 & g_1 & f_1 g_1 \\1 & f_2 & g_2 & f_2g_2 \\ 1 & f_3 & g_3 & f_3g_3 \\ 1 & f_4 & g_4 & f_4g_4} \ne 0$$
where the subscripts $1,2,3,4$ refer to four of the points where you made measurements.  (If you used more than four points, it suffices for some four of them to satisfy this criterion.)
In particular, to succeed in estimating all four parameters you need to make observations at at least four distinct points.  When the points are placed at vertices of a rectangle parallel to the coordinate axes, as in the question, this determinant will be nonzero, assuring a unique solution.
3. Fits with positive curvature
At any smooth, non-flat local extremum, the Gaussian curvature is positive.  In order to create that possibility in the model, at least one more term must be included.  Ordinarily we would include terms for both $f(x)^2$ and $g(y)^2,$ but if we wish to be truly parsimonious we might suppose their coefficients are the same ("isotropy"), so that only one more parameter is needed.  Now the model is
$$z = \beta_0 + \beta_1 f(x) + \beta_2 g(y) + \beta_{12} f(x)g(y) + \beta_3(f(x)^2 + g(y)^2) + \text{error}$$
For the first time, the surface may exhibit an extremum:

However, in order to identify this surface uniquely, observations must be made on at least five distinct locations.  The criterion for successfully fitting all five parameters is now
$$\det \pmatrix {1 & f_1 & g_1 & f_1 g_1 & f_1^2 + g_1^2\\1 & f_2 & g_2 & f_2g_2 & f_2^2 + g_2^2\\ 1 & f_3 & g_3 & f_3g_3 & f_3^2 + g_3^2\\ 1 & f_4 & g_4 & f_4g_4& f_4^2 + g_4^2\\ 1 & f_5 & g_5 & f_5g_5& f_5^2 + g_5^2} \ne 0$$
for some five points of the experiment.  This will be the case for the center-point design shown in the question.
Even if this new coefficient estimate $\hat\beta_3$ appears non-significant, you might want to include it anyway.  After all, without it there is no possibility of finding a local optimum within the interior (convex hull) of your design points.  Moreover, you shouldn't be testing $\beta_3$ by itself for significance.  It's really part of the two sets of factors (the interaction and quadratic term) the model departures from the initial linear fit.  It's possible for each of $\hat\beta_{12}$ and $\hat\beta_3$ to be individually not significant but for the two of them together to be significant.


Greatest common divisor, no prime factor without power

Question: If I try to get the GCD of 272 and 210 I end up with the following

$272 = 272/2=136/2=68/2=34/2=17$
$2^4 \times 17$
$210 = 210/2=105/5=21/3=7$
$2 \times 5 \times 3 \times 7$

Normally if there are 2 equal numbers with a different force, the one with the highest force is scrapped. But that would mean there are no equal numbers left. So am I to understand the scrapping rule is ignored in these situations and the GCD is 2 or did I make a mistake?
Comment: I don't know the "scrapping rule", but you showed that the only prime that divides both numbers is $2$ and only $2^1$ divides both. So, where's the problem? Yes, the gcd is $2$.
Comment: I don't know about the "force" of a number, but GCD$(272,210)\ge 2$ since both numbers are divisible by $2$.
Comment: Probably a poor translation from Dutch.. I'll look in to it.
Answer: The GCD of two numbers stands for the "greatest common divisor", or the "greatest common factor" shared by the two numbers.
$$272 = 2^4 \times 17 = \color{blue}{2^1}\times 2^3 \times 17$$
$$210 = \color{blue}{2^1}\times 3\times 5 \times 7.$$
In this case, as you've shown, the two numbers share only one factor of $2$, so the greatest common factor shared by each of $272$ and $210$ is precisely that one factor of $2$.
What we do ignore is the factor $2^3 = 8$ of $272$, since $210$ has only one factor of $2$, so we scrap the number of factors of any particular prime in one number that exceed the number of factors of that same prime in the second number.
Hence, $\;\gcd(272, 210) = 2.$
For a more general case,
For integers $\,m, n$, $\,a, b,\,$ with $\,a, b \geq 0,\;$ if $\,m = p_1^{a}\times p_2^b,\;$ and $\,n = p_1^c\times q,\,$ where $\,p_1, p_2, q\,$ are distinct primes, then if $\,a \lt c,\,$ $\,\gcd(m,n) = p_1^{a},\,$ and if $\,c\lt a,\,$ then $\,\gcd(m,n) = p_1^c.$
Comment: Needs a TU --->>> +1
Comment: +1 this is an excellent explenation. There's a typo though, it should be $210 = 2^1\times3\times5\times7$
Comment: $+ \Leftrightarrow +$
Answer: Scrapping rule is not ignored. Rather, scrapping means taking away the extra force of the larger number. So 2^4 is scrapped down to 2, because it has 3 extra force.
Hope this helped.
(I assumed force means power/exponent. Also, the word "scrap" is not really used to describe what is being done here.)


Disabling language prefix for route in module

Question: How can I disable the automatic redirect to the language prefixed URL for a URL defined in a routing.yml in my module?
I'm developing a custom sitemap.xml module, because the Simple Sitemap XML module does not have the options I need. I've got it just about working, except the URL /sitemap.xml 301 automatically redirects to the URL /lang/sitemap.xml - and it really shouldn't. How can I disable this redirect?
Comment: Do you have the Redirect module installed?
Comment: In language detection settings, disable the url prefix or assign it larger weight.
Comment: The 3.x branch of [simple_sitemap](https://www.drupal.org/project/simple_sitemap) supports {variant}/sitemap.xml and also implements the no-redirect directive you are asking about. What functionality are you missing from it?
Answer: Yes, has to be redirect.module, core doesn't do that. See https://www.drupal.org/node/2854462#comment-12047347, just add the '_disable_route_normalizer' flag to your route and you should be fine.
module_sitemap.routing.yml:
module_sitemap.sitemap:
  path: '/sitemap.xml'
  defaults:
    _controller: '\Drupal\module_sitemap\Controller\SitemapController::view'
    _title: 'View Site Map'
    _disable_route_normalizer: 'TRUE'

Comment: I've tried adding this flag both in the options section, and the root in my routing.yml:

`  options:
    _disable_route_normalizer: 'TRUE'
  _disable_route_normalizer: 'TRUE'`

Neither appears to work. Am I doing it wrong, or do I have to add it in a hook somewhere?
Comment: " $route->setDefault('_disable_route_normalizer', TRUE);", which means it is in the defaults section, not options or root
Comment: Thanks! That did the trick. I edited in the code that worked.


I can't move any controls in designer

Question: All my controls are now in the lower panel of the designer and I can't move them or select them in the upper panel.
What did I do and how do I put it back to normal?
screetshot
Answer: So apparently, there is a difference between unused references and unneeded ones. I caused the problem by removing all unused references not thinking that they may  be unused but still necessary.
It cost me 6 hours to invent lots of new curse words and learn one lesson.
Thank you anyway

I can't move any controls in designer


How registered COM interface is linked to twapi moniker?

Question: I want to use c# code app in tcl using COM > twapi > tcl path.
By studying "call c# code from tcl" wiki page I understood two things.
We need to compile c# code with com interface register VS option. Then use that namespacename.classname to create object instance. But it is not clear how twapi (or tcom) will use that com (or link). Can you please explain in more details. Thanking you in advance.

C# code
using System;
 namespace MyClassLib
 {
    public class Class1
    {
    public Class1()   {}
    public int Double (int val)  { return val * 2 ;  }
    }

 }

Answer: When the project is registered for COM Interop and built, the class is registered in the system's Registry as a provider for that class name. The tcom package knows how to use that information. When you do:
set myCom [tcom::ref createobject "ClassLibrary1.Class1"]

It goes away and asks the COM service that's built into Windows to make an instance of that object and give a reference to it back to you. That reference is what is stored in the variable. You can then invoke methods of the object; the syntax for that is Tcl-ish rather than C#-ish, but the models line up.
$myCom Double 6

Yes, there's a lot of complexity going on behind the scenes, mostly centred on IDispatch and its related interfaces.
Comment: How tcom knows the path of the code (dll or exe). Or is it copies the compiled code into windows somewhere so that windows com program can access through some kind of "key" code in registry?


I need to display an Arabic date picker

Question: I need to display an Arabic date picker , I can't control this with Locale constructor .
It's only display an English view .

Pick date metod

  DateTime selectedDate = DateTime.now();

  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2000, 1),
        lastDate: DateTime(2100),
        builder: (BuildContext context, Widget child) {
          return Theme(
            data: Theme.of(context).copyWith(
                colorScheme: ColorScheme.light(primary: primaryColor)),
            child: child,
          );
        });

    if (picked != null && picked != selectedDate) {
      selectedDate = picked;
    }
  }

Main Screen

void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await GetStorage.init();
      runApp(
        MyApp(),
      );
    }

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      translations: Translation(),
      locale: Locale(AuthController().appLocal.value),
      fallbackLocale: Locale(AuthController().appLocal.value),
      title: 'Hesabate App',
      theme: ThemeData(
        canvasColor: Colors.transparent,
        fontFamily: "NotoNaskhArabic_font",
      ),
      initialRoute: AppRoutes.splashScreen,
      getPages: AppRoutes.routes,
    );
  }
}

I have an updated language(en&ar) at this variable

AuthController().appLocal.value

Answer: thank you , I found the solution I was looking for .
to solve the Issue , I did some steps :

In order to show the date picker in local language, you need to make
use of flutter_localizations plugin and specify localizationDelegates
and supportedLocales inside MaterialApp in your main code

1.Add flutter_localizations plugin in pubspec.yaml and run pub get.
flutter_localizations:
        sdk: flutter

2.Import the plugin in dart file
import 'package:flutter_localizations/flutter_localizations.dart';

3.Inside MaterialApp, add following
  return GetMaterialApp(
       localizationsDelegates: [
         GlobalMaterialLocalizations.delegate
       ],
       supportedLocales: [
         const Locale('en'),
         const Locale('ar')
       ],

4.then implement default datePicker as following
 DateTime selectedDate = DateTime.now();

  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2000, 1),
        lastDate: DateTime(2100),
        builder: (BuildContext context, Widget child) {
          return Theme(
            data: Theme.of(context).copyWith(
                colorScheme: ColorScheme.light(primary: primaryColor)),
            child: child,
          );
        });

    if (picked != null && picked != selectedDate) {
      selectedDate = picked;
    }
  }

5.finally call the previous method into your date TextField as following
Expanded(
       child: CustomTextField(
         hint: "date".tr,
         onPress: () => _selectDate(context),
        ),

Answer: Can you be more specific on which package you are using?. For example flutter_datetime_picker have parameter locale, where you can pass LocalType.ar
  static Future<DateTime?> showPicker(
BuildContext context, {
bool showTitleActions: true,
DateChangedCallback? onChanged,
DateChangedCallback? onConfirm,
DateCancelledCallback? onCancel,
locale: LocaleType.en,
BasePickerModel? pickerModel,
DatePickerTheme? theme,

Edited per Nader clarification, you can pass locale:Locale("ar") to the internal date_picker
  const Locale(
this._languageCode, [
this._countryCode, ])

Comment: I'm not using an external package , it's a showDatePicker built in method into flutter . I can only show an english view through this constructor =>  locale: Locale("en").
Comment: Ok, so in the internal showDatePicker(), there is also a param locale in the native one, you can pass locale: Locale("ar")
Comment: I already did, and it shows an error says "No MaterialLocalizations found." . however I'm using Getx state managment and GetMaterialApp as a root of the app .
Comment: Can you be more specific next time asking question
https://stackoverflow.com/help/how-to-ask

So can you explain the steps you make, the code where you init you local in the main.dart

Have you added Arabic as supported locale?
Comment: sorry , I  provided my question with more details
Answer: use this it worked for me -

add flutter_localizations to pub.yaml

add this two line to main material app widget

localizationsDelegates[GlobalMaterialLocalizations.delegate],
supportedLocales: [const Locale('en'), const Locale('ar')],

for me my main looklike -
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetMaterialApp(
    localizationsDelegates: [GlobalMaterialLocalizations.delegate],
    supportedLocales: [const Locale('en'), const Locale('ar')],
    debugShowCheckedModeBanner: false,
    initialRoute: get_initial_route(),
    getPages: app_routes());
}
}

place it in your code in any child widget from this material -

IconButton(
    onPressed: () async {
      final DateTime? pickedDate = await showDatePicker(
          context: context,
          initialDate: DateTime(1999),
          firstDate: DateTime(1960),
          lastDate: DateTime(2025),
          locale: Locale('ar'));
    },
    icon: Icon(
      Icons.date_range,
      color: Colors.blue,
    ),
  ),

and we are done every thing should be ok

I need to display an Arabic date picker


search in html file and show it in the list

Question: I'm trying to search a word in all html files which are stored in my project assets folder. But my method is only searching in current html file.
findBox = new EditText(this);
    findBox.setMinEms(30);
    findBox.setSingleLine(true);
    findBox.setHint("Ara...");
    findBox.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                    && ((keyCode == KeyEvent.KEYCODE_ENTER))) {
                wv.findAll(findBox.getText().toString());
                try {
                    // Can't use getMethod() as it's a private method
                    for (Method m : WebView.class.getDeclaredMethods()) {
                        if (m.getName().equals("setFindIsUp")) {
                            m.setAccessible(true);
                            m.invoke(wv, true);
                            break;
                        }
                    }
                } catch (Exception ignored) {
                }
            }

            return false;
        }
    });

Comment: `But my method is only searching in current html file.` As it should. WebView.findAll() searches the current document. Your code clearly does nothing with assets.
Answer: I think you are misunderstanding how WebView works. When you load a html document with a:
WebView wv;
// ... some initialization here
wv.loadUrl("file:///android_asset/page.html");

It loads just one particular page, it won't help you find content in all html files in assets.
Regarding searching through all the files:
1) get all file names in assets dir or some sub dir in it. In the example below I get all the files in a /assets/html:
String dirFrom = "html"
AssetManager am = res.getAssets();
String fileList[] = am.list(dirFrom);

2) open an InputStream for each file and use it to search through its contents, similarly to this
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

3) Then you will know the file names, their locations and ofc if you want to have everything displayed in WebView now you can just load each file with loadUrl.
On a side note I've noticed you are using:

public int findAll (String find)

And you should:

public void findAllAsync (String find)
Comment: Thanks for answer. I can search all files, with your algorithm. Actually ı want to store words which we find in html files with their file name and show a listview. But findAllAsync() is insufficient for it. Can you help me in this matter?
Comment: - Scan all the `html` files in `assets` directory in search of a string
- Show which files contain the search result in a `ListView`

WebView's method `findAllAsync()` is used to perform a browser-like find. Like let's say in Firefox where you use `ctrl-F` to find something and it allows you to jump between results. It won't return you any info other then number of results found + `findNext()` will scroll the WebView to the next result.


Converting set of inequalities to LP

Question: I have a problem where I have a bunch of inequalities in the form:

$a_{1,1}b_{1,1} + a_{1,2}b_{1,2} + ... + a_{1,n}b_{1,n} >
   a_{2,1}b_{2,1} + a_{2,2}b_{2,2} + ... + a_{2,n}b_{2,n}$

$a_{2,1}b_{2,1} + a_{2,2}b_{2,2} + ... + a_{2,n}b_{2,n} >
   a_{3,1}b_{3,1} + a_{3,2}b_{3,2} + ... + a_{3,n}b_{3,n}$

$a_{1,1}b_{1,1} + a_{1,2}b_{1,2} + ... + a_{1,n}b_{1,n} <
   a_{3,1}b_{3,1} + a_{3,2}b_{3,2} + ... + a_{3,n}b_{3,n}$

etc.

I've randomly distributed the < and > signs in the inequalities for the example; they can be any of ≤, ≥, <, or >. All the b variables are dummy variables (either 0 or 1).
I want to find values of all the a variables, assuming possible given the data. This seems like a linear programming problem, but I'm struggling to convert it to one.
One further problem is that I may come to a point where there is not solution by classic linear programming (ex. the example above). In this case, I would want to find the point that is "closest" to being a valid point (think OLS error reduction). I know how to do this for linear programming (another reason I jumped to lp), but am unsure on how to do it for the problem statement above. As a side note, I plan to do this mainly computationally.
What method would I use to solve the above?
Comment: What is a "dummy variable"? Do you mean they are constants or actual (binary)  optimization variables in your model?
Comment: So the $b$ come as part of input? Well then you already have an LP: every constraint is a linear inequality in the $a_{i,j}$s. You can maybe move all terms to one side to get a more standard form if necessary.
Comment: They're binary data variables, so for any equation we will end up with something of the form $a_{1,1} + a_{1,3} + \dots + a_{1,n} > a_{2,3} + a_{2,7} + \dots + a_{2,n}$. The `b` variables are there for expository ease
Comment: ah that's embarrassing. if you would like to make that an answer, i can accept it
Answer: Accepting Micheal Adamaszek's answer that he commented. It's already in LP form, just move the terms to one side to get to standard form.

Converting set of inequalities to LP


Encontrar chave e valor correspondente em arquivo de texto

Question: Tenho um arquivo de texto:
0 GATO
1 CACHORRO
2 COELHO
3 RATO

E eu quero pegar o id e o valor correspondente, por exemplo: quando eu inserir 0 retornar "Gato" e assim por diante.
$text = file_get_contents('animals.txt');
$id = "1";
$id_str = strlen($id);
$pos = stristr($text, $id, true);
$pos_str = strlen($pos);
$pos_str = ($pos_str - $id_str);
$res = substr($pos, $id_str, $pos_str);
echo $res;

Dessa forma ele me Retorna:

"Gato".

Mas se no ID eu colocar 2 ele retorna:

"Gato 1 Cachorro"

Não sei se estou fazendo corretamente o uso dessas funções PHP
Answer: A flag em $pos deve estar em false para não incluir o que vem antes, aproveitando o teu exemplo:
<?php
$text = file_get_contents('animals.txt');
$id = "2";
$id_str = strlen($id);
$pos = stristr($text, $id, false);
$pos_str = strlen($pos);
$pos_str = ($pos_str - $id_str);
$res = substr($pos, $id_str, $pos_str);
echo explode("\n", $res)[0]; // excluir o que vem depois da quebra de linha

Não imprime nada se não for encontrado.
Mas acho que tens maneiras mais diretas e legíveis de o fazer, e não tão custosas. EX:
<?php
$lines = file('animals.txt');
$id = 2;
foreach($lines as $line) {
    $params = explode(' ', $line); // dividir cada linha por espaço, id - valor
    if($params[0] == $id && isset($params[1])) { // ver se é igual e cobrir a hipotese de poder haver linhas sem o valor (segundo elemento de $params)
        $ani = $params[1];
        break;
    }
}
if(isset($ani)) { // se tivermos encontrado o valor relativo ao id
    echo 'Foi encontrado o valor do id ' .$id. ' é: ' .$ani; // COELHO
}
else {
    echo 'Nenhum valor para o id ' .$id; // nao encontramos nenhum valor para aquele id
}

O que fiz aqui foi percorrer cada linha do array de todas as linhas, devolvido por file('animals.txt');, a cada linha vou dividir pelo espaço, fico com o array neste formato (ex da primeira volta do foreach):
$params = array(0 => 0, 1 => 'GATO');, depois comparamos o $id que queremos com cada um na posição 0 deste array.
Se quiseres mesmo usar file_get_contents:
<?php
$content = file_get_contents('animals.txt');
$lines = explode("\n", $content); // acrescentar esta linha, dividir por quebra de linha para ficar com todas as linhas num array
$id = 2;
// ... O RESTO É IGUAL AO EXEMPLO ACIMA

Comment: Exacto @JacksonAntunes. `file()` devolve um `array`, em cada elemento é uma linha. De nada
Comment: Saquei, o `file_get_contents` lê o arquivo como string, enquanto o `file` lê ele como array, era isso que eu estava procurando mesmo! Obrigado Miguel!
Answer: Ao invés de usar file_get_contents() você poderia usar também fopen().
$arr = array();

$file = fopen('texto.txt', 'r');

while (!feof($file)) {
    $line = fgets($file);
    $arr[] = explode(' ', $line);
}

fclose($file);

var_dump($arr);

Saida:
array(4) {
[0] =>
 array(2) {
   [0] =>
   string(1) "0"
   [1] =>
   string(5) "GATO"
}
[1] =>
array(2) {
  [0] =>
  string(1) "1"
  [1] =>
  string(9) "CACHORRO"
}
[2] =>
array(2) {
  [0] =>
  string(1) "2"
  [1] =>
  string(7) "COELHO"
}
[3] =>
array(2) {
  [0] =>
  string(1) "3"
  [1] =>
  string(4) "RATO"
 }
}

Ou se quiser utilizar a chave dos arrays como o ID do animal:
while (!feof($file)) {
    $line = fgets($file);
    $itens = explode(' ', $line);
    $arr[$itens[0]] = $itens[1];
}

Saida:
array(4) {
[0] =>
  string(5) "GATO"
[1] =>
  string(9) "CACHORRO"
[2] =>
  string(7) "COELHO"
[3] =>
  string(4) "RATO"
}

echo $arr[0]; // GATO

Se a ideia for receber os valores por algum modo interativo, você pode colocar o recebimento dentro do $arr[..numero aqui] e pronto.
Comment: resumidamente `fopen` = `open file` :)
Comment: Interessante também seu exemplo, não conheço muito sobre a função `fopen` vou dar uma pesquisada depois pra saber mais! Obrigado!


Given $x^2+y^2=n$ and $2^k\| n$, prove that $2^{k/2}\| \gcd(x,y)$ if $k$ is even, and $2^{(k-1)/2}\| \gcd(x,y)$ if $k$ is odd.

Question: Question: Given three integers $x,y,n$ such that $x^2+y^2=n$ and $2^k\| n$, prove that $2^{k/2}\| \gcd(x,y)$ if $k$ is even, and $2^{(k-1)/2}\| \gcd(x,y)$ if $k$ is odd.
Could anybody please give me a hint?
Note: $a^b\| n$ means that $a^b\mid n$ but $a^{b+1}\not\mid n$
Comment: Try induction. If $4 | n$ then $x, y$ must be even, and substituting $x = 2x', y=2y', n= 4n'$ gives you $x'^2 + y'^2 = n'$.
Comment: Have you studied divisibility in the ring of Gaussian integers? This follows immediately from the fact that $1+i$ is the only prime above $2$ andthat the ring is a UFD.
Answer: If $2^d\|\gcd(x,y)$, write $x=2^da$, $y=2^db$, where at least one of $a,b$ is odd.
Then
$$ x^2+y^2=2^{2d}(a^2+b^2)$$
and $a^2+b^2$ is either odd (if $a\not\equiv b\pmod 2$), or is $\equiv 2\pmod 8$ (if both $a$ and $b$ are odd). Hence either $2^{2d}\|n$ or $2^{2d+1}\|n$.


Why background-Image not getting applied using inline styles?

Question: I have a Hero component in react.js :
<code> if(item.fields!=undefined)
  {
    var img1=item.fields.images[0].fields.file.url
  return (
    <Hero hero="roomshero" style={{backgroundImage:`${img1}`}}>
      <Banner className="banner" title={`${item.fields.name}`} subtitle="none">
        <Link to="/rooms" className="btn-primary">Back to Rooms</Link>
      </Banner>
    </Hero>
  )}
</code>
I am getting matching the item clicked by the user and after searching it my data.js file, setting the appropriate item. Each item has a unique image and hence has to be rendered dynamically.
But this is not working in my case.
Comment: Did you mean `backgroundImage:\`url(${img1})\``
Comment: You have to use `url{${img1})` to get image as background
Answer: You have to use the url() CSS function there.
<code><Hero hero="roomshero" style={{backgroundImage:`url(${img1})`}}>
     ...
</Hero>
</code>
Hope this would be helpful.
Answer: You have to add url infront of your given img1 url .
Example :
<code> if(item.fields!=undefined)
 {
    var img1=item.fields.images[0].fields.file.url
    return (
        <Hero hero="roomshero" style={{backgroundImage:`url(${img1})`}}>
            <Banner className="banner" title={`${item.fields.name}`} subtitle="none">
                 <Link to="/rooms" className="btn-primary">Back to Rooms</Link>
            </Banner>
         </Hero>
  )}
</code>
Also don't forget to set the width and height properties to banner tag to view the image.


Is it good practice to declare derivate classes in the same C++ header?

Question: I'm declaring a pure virtual class that will provide a unified interface for a handful of derived classes. My instinctual way to organize this would be to create a base folder with the header for the base class (e.g lib/Base.h)  and then create subfolders for the header + source file of the derived classes (so lib/implA/ImplA.h,lib/implA/ImplA.cpp and so forth). This keeps the files short, but feels cluttered.
Would it be considered good practice to gather the definitions of the derived classes in the header lib/Base.h and keep the various implementations in the same folder?
Comment: When someone `#include "lib/Base.h"`, he/she will know all subclasses and their definitions. Do you want that?
Comment: If the header contains everything, I would call it `lib.h` rather than `Base.h`. It can be ok if the header is still of reasonable size, and most users need several derived classes.
Comment: Can this question be improved?
Answer: It is neither good nor bad. What matters is what you want to present as an API, that is what a user or your classes will have to write in their own sources. #include "lib/implA/ImplA.h" uses 2 directory level which is not very common while not being too much either IMHO. It can makes sense if a single application will seldom use more than one implementation.
For the way you want to organize your headers and translation units, it is really a question of having reasonable sizes. And the magnitude order may vary between teams...
Answer: Two-file folders (like lib/implA/ImplA.h, lib/implA/ImplA.cpp) are unnecessary, for small projects people usually just put everything in lib/. If lib/ becomes too cluttered, put this whole hierarchy in lib/my_hierarchy/Base.h, lib/my_hierarchy/ImplA.cpp, etc. Maybe extract a logical subsystem instead of a hierarchy. Just keep reasonable folder sizes and some organized structure.
As for putting multiple declarations in the same header, it's your design choice. As far as I know, there's no single "best practice" in C++ regarding this. C++ doesn't enforce one class per file, like Java does. However, including a lot of classes in a single header means slightly longer compilation times for users, because that long header needs to be parsed in every .cpp file where it's #included. Usually people try to keep their headers minimal, but also provide a convenience "aggregate" header that includes all other headers (like bits/stdc++.h for the standard library). In your case, that would be:
// lib/lib.h

#include "my_hierarchy/Base.h"
#include "my_hierarchy/ImplA.h"
// etc.

So that users who don't mind longer compilation times can just #include <lib/lib.h> and have everything, while others can #include only classes they need.


What is a good way to cluster a variable length sequence data

Question: I have a dataset consisting of variable length sequences: There are about 5000 instances. Each instance is a variable length sequence. The shortest sequence has a length of 2 and the longest sequence has a length of 64.
An example sequence looks something like this: ["31A354", "42C164", "39A200", "33B126", "33A443"]. This sequence has a length of 5. Each element of this sequence represents a step in a manufacturing process. The complete sequence thus represents a product. I am tring to do a cluster analysis so that similar processes are grouped together. Thus each cluster would represent a unique product.
An important detail to note is that the order of the elements in the sequence is crucial. If the order of the elements (the steps in manufacturing process) is altered, it would produce a different product. The total number of unique process steps in the dataset is 300.
Based on all these details, I used Sequence Graph Transform to convert the variable length sequences into constant length vectors. This technique preserves the positional and order information of the sequences:

Since all the elements in the sequences are strings, I converted them to integers. Each element was mapped to an integer between 1 and 300.
I applied Sequence Graph Transform on the integer sequences to obtain fixed lenght vectors.
The result was a sparse array of dimension 5000x90000 (5000 instances and 90000 features).

After obtaining constant length for all the instances, I applied Principal Component Analysis to bring down the number of features from 90000 to 3 (Maybe this is where I need to do something else). After obtaining the 3 dimensional feature set, I did cluster analysis but did not get any intuitive results.
Could anyone advise any improvements on the steps that I've done or any other techniques to perform the cluster analysis?
Comment: In bioinformatics they have a problem of aligning many (R)DNA sequences from various source and lengths, classical algorithms are the Needleman-Wunsch or Smith-Waterman algorithm, which are not clustering algorithms but they do find best matches between all the sequences.
Answer: The TraMineR R package proposes several dissimilarity measures (See seqdist function) between categorical sequences, most of them (Optimal matching, which is Needlman-Wunsch, and its variants, number of matching subsequences, ...) applying to sequences of different length. Function seqdist proposes also different normalization options of the distances.
Function seqdist returns the matrix of pairwise dissimilarities between sequences, which can then be inputted to any clustering function based on a pairwise distance matrix. The WeightedCluster package, for example, offers efficient PAM (partitioning around medoids) functions for clustering sequences.
The approach above should work with your data. Nevertheless, it will not tell you if it makes sense to compare a sequence of length 2 with one of length 64. (The distance between two such sequences would essentially be their difference in length.) To give more sense to your analysis, I would suggest to restrict the set of sequences by excluding those with extremes lengths, e.g., such that the shortest sequences have at least half the length of the longest ones.


One mysterious step in proof of Lemma 3 Devroye 83

Question: Can someone help me with one step of the following proof of a multinomial concentration inequality taken from Lemma 3 of "The equivalence of weak, strong and complete convergence in l1 for kernel density estimate" (Devroye 83).
Let $p_1, p_2, ..., p_k$ be the parameter of a multinomial distribution ($\sum p_i = 1$). In $n$ experiments for some fixed $n$, let $X_i$ be the number of times that $i$ appears. $\sum_{i=1}^k X_i = n$
Now, let $N \sim $Poisson(n). After another $N$ experiments (completely independent of the previous n experiments), let $X'_i$ be the number of times that $i$ appears in these $N$ experiments. $\sum_{i=1}^k X'_i = N$. This is also known as Poissonization and each $X'_i$ is actually independent Poisson variable with parameter $np_i$.
I understand and can reproduce every other step except for the following inequality:
$$ P(\sum_{i=1}^k \frac{1}{n} |X_i - np_i| \geq \epsilon ) \leq P(|N-n| \geq \frac{2n\epsilon}{5}) + P(\sum_{i=1}^k\frac{1}{n} |X_i'- np_i| \geq \frac{3n\epsilon}{5}) $$
I'm not sure how he obtained this inequality. Also note how there seems to be an extra "n" in the second term. Inequality (2) (Which I think he used for this step) from the proof is the following simple observation:
$$ \frac{1}{n} \sum_{i=1}^k |X_i - np_i| \leq \frac{1}{n}\sum_{i=1}^k |X_i-X'_i| + \frac{1}{n}\sum_{i=1}^k |X'_i - np_i| $$
Would greatly appreciate any help/suggestions/pointers to similar proofs. The full proof is pasted below for context:
Comment: Please do [not use pictures for critical portions](//math.meta.stackexchange.com/a/20529/290189) of your post. Pictures may not be legible, cannot be searched and are not viewable to some, such as those who use screen readers. [Scanned pages from books are discouraged on SE network](//meta.stackexchange.com/q/155600/259305). Questions should contain sufficient context so that it is [answerable with the text alone](//math.meta.stackexchange.com/a/1807/290189).
Answer: Turns out that I needed to think about Poissonization in the right way to see this.
Fixing an n, $ U_1, U_2, ..., U_n $ are drawn from the multinomial distribution. Now imagine that these draws are snap-shots taken from another random process where we first pick the number of experiments according to $N \sim Poi(n)$, and then take $N$ draw from the multinomial distribution like before.
So there are two cases: if $ n \geq N$, we have something like:
$$ U_1=U'_1, ..., U_N=U'_N, U_{N+1},..., U_n $$
On the other hand, if $N > n$:
$$ U_1=U'_1,..., U_n=U'_n, U'_{n+1},..., U_N $$
So we have something rather surprising (to me at least) that is $|N-n| = \sum_{i=1}^k |X_i - X'_i|$. Combining with (2) in the proof and union bound argument, we get
$$ p(\sum_{i=1}^k \frac{1}{n} |X_i-np_i| \geq \epsilon) \leq p(\frac{1}{n}\sum_{i=1}^k |X_i-X'_i| + |X'_i - npi| \geq \epsilon) $$
$$ \leq p(\sum_{i=1}^k \frac{1}{n} |X_i-X'_i| \geq \frac{2\epsilon}{5}) + p(\sum_{i=1}^k \frac{1}{n} |X'_i - npi| \geq \frac{3\epsilon}{5}) $$
$$ = p(|N-n|\geq \frac{2n\epsilon}{5}) + p(|X'_i - npi| \geq \frac{3n\epsilon}{5}) $$
So there is actually an extra $\frac{1}{n}$ in the manuscript.


Tempo and Rhythm

Question: If an eighth note is half the duration of a quarter note, would the duration of an eighth note played at 60bpm be equal to the duration of a quarter note at 120bpm? If yes, why was the concept of different notes, like half, quarter, eighth, formed?
Wouldn't it be easier to have just one base/reference note and vary the tempo of the song whenever necessary?
Because if the first para is true, then having an 8th/16th note would be the same as changing the tempo of a quarter note to make it twice or 4 times as fast
Comment: It works just like that. Depending on the majority of notes (short or long), the writer will make the decision. Too many long or too many short notes makes a piece more difficult to read.
Comment: Are asking about only the tempo indications in a score like =120? But, if all the notes in a composition were written as one type of note - like  - and then you changed tempo to get eighths, sixteenths, triples, dotted durations a score would be hard to read.
Answer: I'm sure other reasons exist, but to give you a quick answer, I'll extract it right from your question:

If yes, why was the concept of different notes, like half, quarter, eighth, formed?
Wouldn't it be easier to have just one base/reference note and vary the tempo of the song whenever necessary?

The notation system sets a particular duration per note, tempo is per song. Try to apply your idea to something like this (i.e. different notes played at the same time)

It won't work.
Comment: you would have to have different tempo changes for each staff and the voices would line up.
Answer: Your math is correct and we do that type of thing all the time.  But one fixed reference note or tempo would not allow us to express all the subtle variability of time, and syncopation.  This could be partly an historical issue (a lot of musical definitions and conventions can be thought of as obsolete in modern times).
As the other answer points out, with one note type how could you tell one player to hold a long note while the other player plays a melody?  Would you have them count at different speed?  It makes more sense to have everyone counting together and direct musician to play different delta(T) by the current convention.  Your idea may make sense for a programing trying to indicate note duration by number of clock cycles in a computer.
Answer: Notation is useful in simple uncomplicated arrangements of a given song, however sometimes a song is arranged in a manner so that it contains several parts all performed in synchronization with each other. A tempo is selected and each player uses it as a reference as they play their individual parts. Where a bass player may be playing half notes according to the chosen tempo, a lead guitar or horn part may be calling for any combination of whole, half, quarter, eighth, notes all referenced back to the chosen tempo of the song. It's a system that allows several parts to be played together, all at the same tempo.

Tempo and Rhythm


Topology - A continuous map from the circle that can be extended to a continuous map from the disc is null

Question: a question from my h.w.

Let $h:S^1 \rightarrow X$ be continuous map, and suppose it can be extended continuously to the Disc meaning there exists a continuous map $k:D^2 \rightarrow X$ such that $k|_{S^1}=h$.
Show explicitly that $h$ is nulhomotopic without using the induced homomorphism $h_*$ between the fundamental groups.

Munkres deals with this topic through the use of group homomorphisms. I have a feeling this is particularly simple and that I'm expected to construct some straight forward homotopy using $k$. I admit that I don't fully understand the significance of the fact that a map can be continuously extended as in this problem - what does this imply and how can I use a map defined on the disc to construct a homotopy on the circle?
Thanks!
Comment: Alternative hint: polar coordinates.
Comment: Yes, a straightforward homotopy using $k$ is the thing. Unfortunately, I have no idea for a hint that wouldn't give it all away.
Comment: What is a cylinder mod one of its boundary circles?
Comment: I'll take mlk's hint. I want to treat the disc with polar coordinates - it is comprised of all points $re^{i\varphi}$ for $0\leq r\leq1$. I define the homotopy to be $k(r,\varphi)$ and since $k(0)=0$ and $k(1,\varphi)=h$ this is the desired homotopy. Correct?
Comment: I realize I had a basic misunderstanding regarding the definition of a homotopy which is why I didn't understand this approach immediately. Thanks for the help!
Comment: Well, you don't necessarily have $k(0) = 0$. But whatever it is, it is some constant.
Comment: Yeah thanks I was just a bit sloppy there.
Answer: Treat the disc with polar coordinates - it is comprised of all points $re^{i\varphi}$ for $0 \leq r \leq 1$. Define the homotopy to be $k(r,\varphi)$ and since $k(0,\varphi)=k(0)$ is some constant, and $k(1,\varphi)=h$ this is the desired homotopy.


corresponding indices from two different matrices in matlab

Question: In an algorithm, in each level, I have two corresponding matrices in a way one of them has 4 times more element than the other. like children and parent, but i need to have the corresponding elements. consider the two following indices as an example for a level
1 5 9  13
2 6 10 14   and  1 3
3 7 11 15        2 4
4 8 12 16

so for example, I want to receive the element by the index of 1 from the second matrix when i have each of 1,2,5,6 element indices from the first matrix or 2 when i have 3,4,7,8 or 3 for 9,10,16,14 and so on. how can i do that?
as an another example for another level:
1 9  17 25 33 41 49 57
2 10 18 26 34 42 50 58
3 11 19 27 35 43 51 59  and  1 5 9  13
4 12 20 28 36 44 52 60       2 6 10 14
5 13 21 29 37 45 53 61       3 7 11 15
6 14 22 30 38 46 54 62       4 8 12 16
7 15 23 31 39 47 55 63
8 16 24 32 40 48 56 64

Comment: Not sure what you mean by "I want to receive element 1 element index". Can you explain more clearly "for these two matrices A and B, when the input is X I want the output to be Y".
Answer: Here is one way of doing that:
% Size of matrix A (8x8)
sizeA = 8;

% Size of matrix B (4x4)
sizeB = 4;

% Index of element on matrix A
idxA = 43;

% That is how you can get the corresponding index on matrix B
[r, c] = ind2sub([sizeA sizeA], idxA);
idxB = sub2ind([sizeB sizeB], ceil(r / 2), ceil(c / 2))

It will give you idxB = 10.
Answer: It is possible that reshape could be helpful for you.
Consider
A = [1 5 9  13;
     2 6 10 14;
     3 7 11 15;
     4 8 12 16];
B = reshape(permute(reshape(A, [2 2 2 2]), [2 4 1 3]), [4 4]);
B
  1  2  5  6
  3  4  7  8
  9 10 13 14
 11 12 15 16

Now you have a nice mapping of the indices from one level to the next.
B(1,:) corresponds to all the indices that map to element 1 in your second array, etc.
When the matrix gets larger (2n x 2n), the operation becomes
B = reshape(permute(reshape(A, [2 n 2 n]), [2 4 1 3]), [n*n 4]);

Answer: If you know the 2D indices for the first matrix, then you just divide each by 2 to get the second pair indices:
r = 3;
c = 2;
% Then A(r,c) corresponds to B(floor(r/2), floor(c/2))

If you DON'T know the indices, but instead have the element value itself, you have to find the 2D index first:
val = 7;  % test value
[r c] = find(A==val);
other_val = B(floor(r/2), floor(c/2));

Comment: Peter : I want to use the column wise indexing, Suppose that the matrix with more element is divided into 4 parts, so for example the elements by the index 1,2,5,6 are together, because of that i am using a loop and i have the 1, 2, 5 or 6 i want to have the element with index 1 from the second matrix


Ruby on Rails - JSON Format

Question: I have the following controller code:
def calculate_quote

  @mouldings = Moulding.find( params[:id].split(","), :select => 'id, cost, width' )
  @mouldings.collect! do |moulding|
    { "moulding_id_#{moulding.id}" => { :cost => moulding.cost, :width => moulding.width } }
  end
  @material_costs = MaterialCost.all
  @material_costs.collect! do |material_cost|
    { material_cost.material.gsub(" ", "_").downcase => { :cost => material_cost.cost_per_square_mm } }
  end
  @app_options = AppOption.all
  @app_options.collect! do |app_option|
    { app_option.name.gsub(" ", "_").downcase => { :value => app_option.value } }
  end

  respond_to do |format|
    format.json { render :json => { :mouldings => @mouldings, :material_costs => @material_costs, :app_options => @app_options } }
  end
end

And this gives me the following JSON output:
{"mouldings":[{"moulding_id_2":{"cost":"3.1","width":45}},{"moulding_id_4":{"cost":"1.5","width":30}},{"moulding_id_6":{"cost":"2.1","width":50}}],"material_costs":[{"mountboard":{"cost":"0.00000246494303242769"}},{"glass":{"cost":"0.0000032426589803639"}},{"backing_board":{"cost":"0.00000135110790848496"}}],"app_options":[{"vat":{"value":"17.5"}},{"wastage":{"value":"20"}},{"markup":{"value":"3"}}]}

I want to format the JSON output so I can use jQuery to extract the data using the following sort of syntax:
data.mouldings.moulding_id_2.cost

How would I change the controller to achieve this?
Answer: Let's try rethinking the way you're constructing your data. In my opinion, it doesn't make a whole lot of sense to use ids as object indexes. Instead, why not do something like this:
@mouldings = Moulding.find( params[:id].split(","), :select => 'id, cost, width' )
@mouldings.collect! do |moulding|
  { :id => moulding.id, :cost => moulding.cost, :width => moulding.width }
end

This way, you should have an array of objects containing all the data you need for that moulding. In jQuery, you can then iterate over this array and grab all the information you need, like this:
$.each(data.mouldings, function(index, moulding) {
    alert("This moulding has an id of " + moulding.id + " and costs " + moulding.cost);
});

I think this makes a lot more sense than explicitly calling:

data.mouldings.moulding_id_2.cost

If you want to find the exact moulding_id #2, then you should iterate over your dataset as I showed above, and perform a check like this:
if (moulding.id == 2) {//do something};

Comment: I want to use all the data in the JSON feed to perform a calculation on the client.  Surely is it not easier to get the data using something like `data.mouldings.moulding_id_2.cost` and `data.material_costs.mountboard.cost` rather than doing multiple loops through the data?
Comment: @freshest yes, it certainly would be faster, but it would also mean hard-coding the IDs into your JavaScript. If your data ever changes, you'll be glad for the loop. At the same time, if you only have 3 or 4 mouldings in the array, the speed difference on all computers built after 1998 will be entirely unnoticeable. If you know your data isn't going to change and performance really is an issue, naturally, your way works better.
Answer: At the moment, mouldings is a list of singleton hashes. You want it to be a single hash mapping ids to detail hashes.

Ruby on Rails - JSON Format


How do I undo the command $ eval "$(docker-machine env blog)"

Question: I think that command redirected $ docker commands to the docker machine.  Now all my docker commands are giving me an error FATA[0000] Couldn't read ca cert... follwed by the path to the docker-machine I created.  How can I fix my shell?
Answer: What you are looking for is:
eval "$(docker-machine env -u)"

It will unset the DOCKER_* variables.
For the record, here's the output of docker-machine env -u:
unset DOCKER_TLS_VERIFY
unset DOCKER_HOST
unset DOCKER_CERT_PATH
unset DOCKER_MACHINE_NAME

Comment: I am getting the message _Host "default" does not exist_.
Comment: Yes however above does not leave environment in condition prior to running docker-machine ... values prior to docker-machine are not saved for later ... it simply does an unset of docker-machine settings without restoring env settings to original settings ... we need to run a save-current-docker-settings before running docker-machine which post docker-machine and be used to restore original docker settings
Comment: Worked for me. I had switched to minikube docker context. I was able to go back to my 'regular' context by executing the 4 unset commands above. I am using Docker for mac community edition 18.06.1 on mac os High Sierra.
Comment: Running this command gives a `command not found`, instead it refers to use `eval $(docker-machine env -u)` - so without the quotes. Perhaps things have changed over the years?
Comment: When I try this on Windows, running `docker-machine env -u` is giving `'docker-machine' is not recognized as an internal or external command, operable program or batch file.`.
Answer: You could also restart your shell. This will drop the variables that minkube docker-env exports.
Comment: This was a simple and easy fix for me.
Answer: I can see that this is an old post but if someone else runs into this issue, who is new to docker like me this can help. By typing:
eval $(docker-machine env nameOfVm)

you are setting your current shell to use docker in that docker-machine. You can check if you type docker-machine ls
that under active tab, that status is changed from - to * for that machine. You can also check which machine is active by running docker-machine active.
If you want to undo eval, just run:
eval $(docker-machine env -u)

and it will unset variables for active machine (You don't have to specify the name of the machine). This is all under macOS but I think it should be same on linux as well.
You can read more about this here:
Docker documentation: docker-machine env
Answer: I had been searching for an answer to this for quite awhile.  Shortly after posting the question on stackoverflow I realized typing in to the terminal the export commands docker gives on startup resolved my issue.
To connect the Docker client to the Docker daemon, please set:
export DOCKER_HOST=tcp:// some IP address
export DOCKER_CERT_PATH= some file path
export DOCKER_TLS_VERIFY=1

Answer: All you have to do is run
docker-machine env machine-name

Then, copy and run the last segment in the output to set or remove the env variables.
Which looks like this in Windows :
eval $("C:\Program Files\Docker Toolbox\docker-machine.exe" env machine-name)

If it's set already, docker adds a "-u" at the tail to make the task easy.
like this in Windows :
eval $("C:\Program Files\Docker Toolbox\docker-machine.exe" env -u)

That's all.
Comment: This does not seem to add anything to the existing answers.


Is there an efficient way to determine whether a given contiguous sequence can appear within a de Bruijn sequence?

Question: I am curious whether an efficient algorithm exists to determine whether a sequence $S$ can appear within a de Bruijn sequence of order $n$.
For example, for $n=3$, I believe the only de Bruijn sequence is 00010111 (and its rotations/reflection). By definition, any sequence of length $3$ or less will appear at some point, assuming you allow wrapping around or the equivalent. However, 0110 does not appear; you can even prove it cannot fairly easily, as it would still require 111 at some point, granting you a total of 5 1-bits, where the maximum can only be $2^{n-1}=4$ of the 1-bits.
For larger values of $n$ where there are a great many distinct de Bruijn sequences, it seems like deciding whether some sequence may ever appear might turn out to be very difficult to work out. Or perhaps there's some easy trick to it.
If anyone can describe how you could do this/point me towards an algorithm for it, or alternatively confirm that it is difficult after all (in the rough sense of being not computationally feasible past more than the first handful of $n$), I'll consider this answered.
Comment: The following thing is computationally feasible for $n = 3$, $n = 4$, and $n = 5$: produce all de Bruijn sequences of order $n$ and find all substrings of length $n + 1$ in each of them and take the complement of the union.  This might provide insight into whether there is any hope of giving a characterization.
Comment: Not being aware of this question I posted a similar one today: https://math.stackexchange.com/questions/4508387/binary-sequences-of-length-n-including-all-numbers-upto-n
Answer: There are many different ways of obtaining de Bruijn sequences, even for the algebraic ones [generate a maximal length sequence and insert a zero to get a string of $n$ zeroes] unless you knew the generating recurrence you wouldn't have a check. You could use Berlekamp Massey to obtain the recurrence and then use the parity check the recurrence represents to rule out the sequence being part of that de Bruijn sequence of order $n.$
So, in general, I strongly believe the answer is no other than checking for violations of the de Bruijn property such as the one you suggested [too many zeroes or ones]. Another possible one is a sequence indicating that there are two $n+1$ sequences which match in the last $n$ symbols.


How to get plain link with views-data-export module in CSV?

Question: I have a view with field that provides a simple link to the content.
Problem: When I export the data into a csv file there is only the word link instead of a link.
How can I get there the content URL instead of the word link?
Answer: CSV is not an interactive format. When you export column with literal "link" in it's data, you get link in CSV.
Instead of exporting word column, with link added at rewrite or template level, export column that actually contains the URL you want. For nodes, this issue indicates that you should be able to use 'Path' field, description: 'The aliased path to this node.'.
Comment: That `Path` thing made the difference! Additionally you can setup the link to absolute link at `rewrite results`.
Comment: Well, that is the problem. There is only this single field (`content: link`) which `Provide a simple link to the content.`.
Comment: @Jurik see https://www.drupal.org/node/548292


multidimensional array in angular

Question: I have a multidimensional array from an API. Is it possible to programatically loop through the array?
{
    success: true,
    categories: [{
            cat_id: "2",
            name: "This is category One",
            description: null,
            photo_url: "/img/test.png",
            order: "1",
            items: [{
                    item_id: "1",
                    title: "Desk",
                    item_url: "/690928460",
                    photo_url: "/desk.png",
                }, {
                    item_id: "2",
                    title: "Chair",
                    item_url: "/18882823",
                    photo_url: "/chair.png",
                },
            }]
    }]
}

My controller looks like this:
myApp.controller('items', function($scope, $http, $location, Data) {
    var apiUrl = '/api/items';
    $http.get(apiUrl).
    success(function(data) {
        $scope.data = Data;
        $scope.allData = data;
    });
    $scope.changeView = function(view) {
        $location.path(view);
    }
});

Angular index file just has:

View file

                        {{ category.name }}

I can loop through the category names fine, but when trying to return items for EACH category I don't understand the logic behind it...
Comment: Your JSON is wrong, did you copy and past it or write it from scratch?  Items has an extra ',}' at the end.
Comment: Can you explain better?  What is `allData`?  Is it the complete json at the top so `allData.success` is true?
Comment: What have you tried doing? What does this get you: `ng-repeat="item in category.items"`. Then using `{{ item.title }}`
Comment: @ZackArgyle sorry, yes I wrote it from scratch -- forgot the ; at the end
Comment: @JasonGoemaat allData is the data i get from the API
Comment: @brouxhaha i tried that but then for every category i have it just displays the items from the first category [0]
Comment: `ng-repeat="categories in allData"` <-- this is wrong usage of ng-repeat, unless you want to loop over every items of `allData` which would be a loop over the `success` and `categories` properties.
Answer: I would suggest some simple nested for loops, as for each gives rise to more complexity.
As I'm not sure what you want to do with the data let's just create an array of all item names and one of all category names:
Within your success function:
var items = [], categories = []
for(var i = 0; i < data.categories.length;i++){
    categories.push(data.categories[i].name);
    for(var j = 0; j < data.categories[i].items.length;j++){
        items.push(data.categories[i].items[j].name);
    }
}
console.log(categories);
console.log(items);

EDIT:
Completely missed your html code somehow, here is my solution:

                    {{ category.name }}

EDIT 2:
As to your comment:
If you want to select the secondary view's contents(ie the items) based on the selection of a category I would suggest a ng-click attribute. A directive could be used but isn't necessary:

                {{ category.name }}

                {{ item.name }}

So when your categories data is loaded the first ng-repeat is populated with the categories. Each div with class title will have a function called on click which will make the selected_category object equal the selected category.
This will then cause the second view to be populated with all the items in the selected category by Angular's two way bind.
Comment: is there a way to just display data from one category? example: in the categories view it displays the categories, but when you press a category it takes you to another view to display the items in the selected category.
Comment: Sure, You can either (1)make this your main content and read through the ng-view and routeprovider docs or (2) use ng-include and a template or (3) make your own directive. I would use the 3rd but explain to me if these categories are the main focus of the view, or if the view refers to your whole page: basically what you want to accomplish
Comment: thanks man, appreciate it. basically this is a small app; user logs in, has an inbox (view), has a button to select from a bunch of categories (another view) and in each of those categories there are items for that category that the user can choose. all the data is populated via an api. i'm still learning, i can do this in javascript but want to work with angular to learn

multidimensional array in angular


Summation Notation using Induction

Question: $$\sum_{k=1}^{2n}\frac{(-1)^{k+1}}{k} = \sum_{k=n+1}^{2n} \frac{1}{k}$$
I am trying to prove this inductively, so I thought that I would expand the right side out of sigma form to get
$$\sum_{k=1}^{2n}\frac{(-1)^{k+1}}{k} = \frac{2}{2n(2n+1)} - \frac{1}{n}$$
which simplified to
$$\sum_{k=1}^{2n}\frac{(-1)^{k+1}}{k} = \frac{-2}{2n+1}$$
but apparently that isn't correct, can someone provide some insight into what I am doing wrong?
Comment: That's what it looked like you were doing, and what I alluded to in my answer.  You can't flip over a sum: $\frac1{a+b}$ doesn't equal $\frac1{a}+\frac1{b}.$
Comment: The second equation, how did you expand it out of sigma form?
Comment: $$\sum_{k=1}^n k =  \frac{(n)(n+1)}{2}$$ so I flipped that upside down as the k was in the denominator, replaced every k with 2n and subtracted the first term, $$\frac{(1)}{n}$$ to make the lower limit k = 1
Answer: The right side doesn't equal what you think it equals.  I think maybe you're confusing this with the different, and unrelated, formula $\sum_{k=1}^n k = \frac{n(n+1)}{2}.$  You can't get from that formula to a formula for $\sum_{k=1}^n \frac1{k}$ or anything similar.
See https://math.stackexchange.com/a/1961771/35021 for a detailed answer to your question.  (The question in the other post is phrased as a limit, but the answer there solves your problem exactly.)
Answer:
INDUCTION PROOF:

If one wishes to prove the identity using induction, we first establish a benchmark.  Letting $n=1$, we find that $\sum_{k=1}^{2}\frac{(-1)^{k+1}}{k}=1/2=\sum_{k=2}^2\frac1k$.
Next, we assume that the identity works for some number $n$
$$\color{blue}{\sum_{k=1}^{2n}\frac{(-1)^{k+1}}{k}}=\color{red}{\sum_{k=n+1}^{2n}\frac1k} \tag 1$$
Then, we test the validity of the relationship in $(1)$ for $n+1$.  Proceeding we find that
$$\begin{align}
\sum_{k=1}^{2n+2}\frac{(-1)^{k+1}}{k}&=\color{blue}{\sum_{k=1}^{2n}\frac{(-1)^{k+1}}{k}}+\frac{1}{2n+1}-\frac{1}{2n+2}\\\\
&=\color{red}{\sum_{k=n+1}^{2n}\frac1k}+\left(\frac{1}{2n+1}-\frac{1}{2n+2}\right)\\\\
&=\sum_{k=n+2}^{2n+2}\frac1k+\frac{1}{n+1}-\left(\frac{1}{2n+1}+\frac{1}{2n+2}\right)+\left(\frac{1}{2n+1}-\frac{1}{2n+2}\right)\\\\
&=\sum_{k=n+2}^{2n+2}\frac1k
\end{align}$$
as expected.

DIRECT PROOF:

Note that we can write
$$\begin{align}
\sum_{k=1}^{2n}\frac{(-1)^{k+1}}{k}&=\sum_{k=1}^n\frac{1}{2k-1}-\sum_{k=1}^n\frac1{2k}\\\\
&=\sum_{k=1}^n\left(\frac{1}{2k-1}+\frac{1}{2n}\right)-2\sum_{k=1}^{n}\frac1{2k}\\\\
&=\sum_{k=1}^{2n}\frac1k-\sum_{k=1}^n\frac1{k}\\\\
&=\sum_{k=n+1}^{2n}\frac1k
\end{align}$$
as was to be shown!

Summation Notation using Induction


Posterior predictive: what happens to integral over parameters?

Question: Question
I don't understand how when integrating over the parameters in the posterior predictive, the integration "disappears". It's hard for me to ask simply because I am confused, so here is an example.
Example
Imagine we have a Gaussian model with unknown mean $\mu$ and fixed variance $\sigma^2$. If $D$ is the training data and $D'$ is unseen data, then the posterior predictive is
$$
\begin{align}
p(D' \mid D)
&= \int p(D' \mid D, \mu) p(\mu \mid D) d\mu
\\
&\stackrel{\star}{=} \int p(D' \mid \mu) p(\mu \mid D) d\mu
\\
&\triangleq \int \mathcal{N}(D' \mid \mu, \sigma^2) \mathcal{N}(\mu \mid \mu_N, \sigma_N^2) d \mu
\end{align}
$$
where step $\star$ holds because the modeling assumption is that $D'$ is conditionally independent from $D$ given $\mu$ and the definitions of $\mu_N$ and $\sigma_N^2$ fall out of computing the posterior. See Bishop (2006) page 98 for details.
Here is where I am confused. I can show that
$$
\mathcal{N}(D' \mid \mu, \sigma^2) \mathcal{N}(\mu \mid \mu_N, \sigma_N^2) = \mathcal{N}(D' \mid \mu_N, \sigma_N^2 + \sigma^2)
$$
Murphy's derivation in Conjugate Bayesian analysis of the Gaussian distribution suggests looking at Bishop, equation 2.115 (see my edit for more). My trouble is, Murphy then claims that
$$
p(D \mid D') = \mathcal{N}(D' \mid \mu_N, \sigma_N^2 + \sigma^2)
$$
which is what I mean by the integration should "disappearing". What happened? I understand that this new distribution has no dependence on $\mu$, but I would have expected
$$
\begin{align}
p(D' \mid D)
&= \int \mathcal{N}(D' \mid \mu, \sigma^2) \mathcal{N}(\mu \mid \mu_N, \sigma_N^2) d \mu
\\
&= \int \mathcal{N}(D' \mid \mu_N, \sigma_N^2 + \sigma^2) d \mu
\\
&= \mathcal{N}(D' \mid \mu_N, \sigma_N^2 + \sigma^2) \int d \mu
\end{align}
$$
But it's unclear what becomes of the integral. It's not a probability, so it's not like this is guaranteed to be 1.

Edit
This is my derivation based on Murphy's hint to look at Bishop (2006), page 93. Since both our posterior and prior are Gaussians, we can use the following fact:
$$
\begin{align}
p(\textbf{x}) &= \mathcal{N}(\textbf{x} \mid \boldsymbol{\mu}, \boldsymbol{\Psi})
\\
p(\textbf{y} \mid \textbf{x}) &= \mathcal{N}(\textbf{y} \mid A \textbf{x} + \textbf{b}, \textbf{P})
\\
&\Downarrow
\\
p(\textbf{y}) &= \mathcal{N}(\textbf{y} \mid \textbf{A} \boldsymbol{\mu} + \textbf{b}, \textbf{P} + \textbf{A} \boldsymbol{\Psi} \textbf{A}^{\top})
\end{align}
$$
where we have
$$
\begin{align}
\textbf{x} &= \mu \\
\boldsymbol{\mu} &= \mu_N \\
\boldsymbol{\Psi} &= \sigma_N^2 \\
\textbf{y} &= D' \\
\textbf{A} &= 1 \\
\textbf{b} &= 0 \\
\textbf{P} &= \sigma^2
\end{align}
$$
This gives us
$$
\begin{align}
p(\mu) &= \mathcal{N}(\mu \mid \mu_N, \mu_N^2)
\\
p(D' \mid \mu) &= \mathcal{N}(D' \mid \mu, \sigma^2)
\\
p(D' \mid \mu) p(\mu) = p(D') &= \mathcal{N}(D' \mid \mu_N, \sigma^2 + \sigma_N^2)
\end{align}
$$
We can add conditioning on $D$ at every step if we'd like, since it doesn't effect the distributions provided we have the parameters (i.i.d.):
$$
\begin{align}
p(\mu \mid D) &= \mathcal{N}(\mu \mid \mu_N, \mu_N^2)
\\
p(D' \mid \mu, D) &= \mathcal{N}(D' \mid \mu, \sigma^2)
\\
p(D' \mid \mu, D) p(\mu) = p(D' \mid D) &= \mathcal{N}(D' \mid \mu_N, \sigma^2 + \sigma_N^2)
\end{align}
$$
Comment: How did you manage to show that $
\mathcal{N}(D' \mid \mu, \sigma^2) \mathcal{N}(\mu \mid \mu_N, \sigma_N^2) = \mathcal{N}(D' \mid \mu_N, \sigma_N^2 + \sigma^2)
$ without integrating out $\mu$, after which the integral has disappeared?
Comment: As far as I can tell, $p(D^\prime\mid D)$ isn't a probability, either: it's a probability *density* and therefore can have any nonnegative value--and even be infinite.
Comment: The line after "I would have expected" doesn't make sense; you are integrating with respect to $u$, but there is no $u$ in the formula being integrated.  Do you mean to integrate wrt $\mu$?  If so, note that $
\mathcal{N}(D' \mid \mu, \sigma^2) \mathcal{N}(\mu \mid \mu_N, \sigma_N^2) = \mathcal{N}(D' \mid \mu_N, \sigma_N^2 + \sigma^2)
$ is not true; what *is* true is that $
\int_{\mu} \mathcal{N}(D' \mid \mu, \sigma^2) \mathcal{N}(\mu \mid \mu_N, \sigma_N^2)d\mu = \mathcal{N}(D' \mid \mu_N, \sigma_N^2 + \sigma^2)
$, so your next derivation won't have a $du$ in it if you do it correctly.
Comment: @jbowman, I've added the derivation I used based on Murphy's hint to look at Bishop, equation 2.115.
Comment: Thanks for your help. Yes, I meant w.r.t $\mu$ (so $d \mu$) and have fixed that typo. I appreciate your comment, but my entire question is why your comment holds. Another way of asking my question is: what is wrong with my derivation in my edit? In my edit, I show my logic for why $\mathcal{N}(D' \mid \mu, \sigma^2) \mathcal{N}(\mu \mid \mu_N, \sigma_N^2) = \mathcal{N}(D' \mid \mu_N, \sigma_N^2 + \sigma^2)$. I understand that this must be wrong (or is inconsistent with Murphy). I don't understand why it is wrong.
Answer: If I understand correctly the question, it seems to me (and others before me in the comment section) that the derivation
$$\mathcal{N}(D' \mid \mu, \sigma^2) \mathcal{N}(\mu \mid \mu_N, \sigma_N^2) = \mathcal{N}(D' \mid \mu_N, \sigma_N^2 + \sigma^2)$$
or equivalently
$$p(D' \mid \mu, D) p(\mu) = p(D' \mid D) = \mathcal{N}(D' \mid \mu_N, \sigma^2 + \sigma_N^2)$$
is incorrect since the left hand side is a joint density on $(D',\mu)$ and the right hand side is a marginal density on $D'$. (When removing $\mu$ from the above rhs, it is as if $\mu$ is already integrated, but I advise against such loose reasonging.)
What is correct is that, if
$$\underbrace{D'|\mu\sim}_\text{conditional}\mathcal{N}(\mu,\sigma^2)\qquad\text{and}\qquad\underbrace{\mu\sim}_\text{marginal}\mathcal{N}(\mu_N, \sigma_N^2)$$then
$$\underbrace{D'\sim}_\text{marginal}\mathcal{N}(\mu_N, \sigma^2+\sigma_N^2)$$
as stated in the book.
Comment: I see. I used Bishop's 2.115 incorrectly. It is not that $p(y) = p(y \mid x)p(x)$, which is obviously wrong now that I write it out explicitly. It is $p(y) = \int p(y \mid x)p(x) dx$.


Where can I purchase tickets for the 2018 World Cup?

Question: Where can I purchase tickets for the 2018 World Cup?

If I cannot find any tickets online to buy, can I get tickets from the stadium two or three days before the match?
Can I apply for a "wheelchair user" FIFA ticket even if I am not a disabled person? They opened the W ticket section online with tickets selling for $105.
Answer:
As it stands right now: No. Tickets are sold on the respective Website only and possibly in so-called Ticket Venue Centres sometime during the final sales phase if there are still enough tickets for sale for a certain game (There is no news about the exact time and location yet, but for the Confed Cup there were three: St. Petersburg, Sochi and Moscow). If there are any tickets left from the previous stage (e.g. ordered but not paid for in time) they will be sold in the next stages. Even the last minute sales will be held online. If there are still tickets available after that the FIFA will publish information in time about how to order them (Online or as of then maybe even in Ticket Venue Centres).

Ticket Sales Regulations:

5.1 Tickets will be made available in different sales phases. FIFA has the right to determine the number of Tickets made available for sale
  to the  general public and other customer groups in each of the sales
  phases.  The sales phases are described in the Ticket Application Form
  and further Ticket sales materials which FIFA may publish and update
  from time to time.

No. Definitely not. Special Access Tickets are that for a reason and they want proof:

Please note that customers who apply for Special Access Tickets are
  required to provide proof of eligibility documents as part of the
  Ticket Application process. If not already provided and approved
  online, such proof of eligibility documents must be provided upon
  Ticket collection (if applicable) or when purchasing Tickets over the
  counter as well as, upon request, at the entrance to the Stadium.
Comment: I need to buy a ticket for germany and mexico but it is closed. The tickets are sold or it may be opened in the next phase ?
Comment: @droidnation it is possible that it will be reopened again during the next phase. It always happens that some unsold or unallocated tickets will be made available again... but usually Germany's games are sold out early, so you need some luck. Just don't fall for viagogo and the likes.. they're known for screwing people over (and they're [banned](http://www.fifa.com/worldcup/news/y=2018/m=1/news=fifa-obtains-preliminary-injunction-against-viagogo-2926697.html)).
Comment: What is this: `In the Last Minute Sales Phase from 18th April 2018 up until the final Match day of the Competition, the remaining Tickets will be available to all customers online and, from a date to be defined up until the final Match day of the competition, remaining Tickets will also be available Over the Counter at the designated FIFA Venue Ticketing Centres. During the Last Minute Sales Phase, Ticket purchases are processed as a real-time transaction to the extent inventory remains available`
Comment: These are special locations where you can buy tickets directly as of 18th April. The FIFA has placed a lot of locations where you can collect your purchased tickets and three of them actually sell them too. I'll append them to my answer
Comment: @droidnation added to my answer.. These are usually for the less frequented games, though. They can't sell tickets for already sold out games :)
Comment: Even round 2 are sold ?
Comment: @droidnation we don't know that yet. FIFA will announce how they sell them.


Is there something wrong in my script?

Question: I am new to client-side scripting. My problem is I've got a lot of textboxes and I want them to auto-calculate, but so far nothing works. Is there something wrong on my script?
function totaltraininghour()
{
var totalhour1=0;
var a1= parseInt(document.getElementById("a1").value);
var b1= parseInt(document.getElementById("b1").value);
var c1= parseInt(document.getElementById("c1").value);
var d1= parseInt(document.getElementById("d1").value);

var totalhour2=0;
var a2= parseInt(document.getElementById("a2").value);
var b2= parseInt(document.getElementById("b2").value);
var c2= parseInt(document.getElementById("c2").value);
var d2= parseInt(document.getElementById("d2").value);

var totalhour3=0;
var a3= parseInt(document.getElementById("a3").value);
var b3= parseInt(document.getElementById("b3").value);
var c3= parseInt(document.getElementById("c3").value);
var d3= parseInt(document.getElementById("d3").value);
var totaltraining=0;

if (a1 >=0)
{
totalhour1 = totalhour1 + a1
}
if (b1>=0)
{
totalhour1 = totalhour1+ b1
}
if (c1>=0)
{
totalhour1 = totalhour1+ c1
}
if (d1>=0)
{
totalhour1 = totalhour1+ d1
}
document.getElementById("txttotalhour1").value = totalhour1

if (a2 >=0)
{
totalhour2 = totalhour2 + a2
}
if (b2>=0)
{
totalhour2 = totalhour2+ b2
}
if (c2>=0)
{
totalhour2 = totalhour2+ c2
}
if (d2>=0)
{
totalhour2 = totalhour2+ d2
}
document.getElementById("txttotalhour2").value = totalhour2

if (a3 >=0)
{
totalhour3 = totalhour2 + a3
}
if (b3>=0)
{
totalhour3 = totalhour2+ b3
 }
if (c3>=0)
{
totalhour3 = totalhour2+ c3
}
if (d3>=0)
{
totalhour3 = totalhour2+ d3
}
document.getElementById("txttotalhour3").value = totalhour3

totaltraining = totalhour1 + totalhour2 + totalhour3
document.getElementById("txttotaltraininghours").value = totaltraining
 </script>

<asp:TextBox ID="a2" runat="server" Width="100px" onkeyup="totaltraininghour
();"></asp:TextBox> And so on..

Comment: To start with, nearly every Javscript statement ends with a semi-colon which you aren't typing.  Then, have you looked in the error console or debugger console to see what Javascript errors are being reported?
Comment: I've heard that ASP.NET changes IDs of controls in the generated HTML, which might be your problem. (unfortunately, I don't work with ASP.NET and don't know how to fix it)
Comment: What's actually happening when you run it? I can tell you that the code as posted has several typos in the calculation of the `totalhour3` field because you say `totalhour3 = totalhour2 + a3` - adding `totalhour2` in instead of `totalhour3`. (You can avoid this issue and make your code neater by saying `totalhour3 += a3`.) @jfriend00: I prefer semicolons on every line, but the code as posted doesn't actually _need_ them explicitly typed in.
Comment: Can you post the generated HTML so we can see what's actually in the web page - not the ASP HTML, but what the browser actually sees?
Comment: when i type on textbox where i put onkeyup event an error shows on the left bottom side saying ive got an error on web page. @jfriend00 sorry sir m just new on this site and i dont know how to do it.  To nnnnn Ill try to renew it based on what you said. (i was trying to add all of the var ex: a1 will be added to totalhour1 + b1 + c1) Im just new on javascripting
Comment: thanks all got it ive got an error on bracketing. I forgot one bracket on ending >_< (im used in vb.net so pardon me) heheheh
Comment: If some of the inputs are empty, or if you type non-numeric data, then `parseInt()` will be returning `NaN` (not-a-number) which won't work in your calculations. (Also, and this is probably not your problem, but anyway: _always_ specify a radix when using `parseInt()`, e.g., `parseInt(someVal, 10)`.) If you're new to JavaSript and don't have any debugging tools (or don't yet know how to use them), try to put several `alert()` statements in your function so that you can perhaps figure out how much of the function gets executed before the error. Or, better look into `console.log()`.
Comment: Not sure will it help, but it's a good practice to us semicolons at the end of statement.
Answer: Make sure your IDs are what you think they are. If the controls are within a naming container, the IDs will be mangled. To get around it, have ASP.NET insert the ClientID, like this:
var a1= parseInt(document.getElementById("<%= a1.ClientID %>").value);

Note, unless you fiddle with your web server's settings, this will only work for scripts within .aspx files, not external .js files.
Comment: You can verify if this is the problem or not by viewing the source in your browser. The mangled IDs will be fairly obvious. They are basically constructed by concatenating all the IDs of the container and contained elements with underscores.
Answer: Here's a lot shorter way to do what you're trying to do without typing lots of duplicate code:
function calcSum(root, num, totalID) {
    var total = 0;
    for (var i = 1; i <= num; i++) {
        var val = document.getElementById(root + i).value || "0";
        total += parseInt(val, 10);
    }
    document.getElementById(totalID).value = total;
}

function calc() {
    calcSum("a", 4, "totalhour1");
    calcSum("b", 4, "totalhour2");
    calcSum("c", 4, "totalhour3");
}

You can see it working here with all the code visible: http://jsfiddle.net/jfriend00/CZPKM/.  I'd suggest you study how this works so you can vastly simplify your code.
In jQuery, you could do the whole thing like this:
$("#calc").click(function() {
    $(".group").each(function() {          // find each group and iterate through them
        var total = 0;
        $(".row", this).each(function() {
            total += parseInt(this.value || "0", 10);   // total all rows in the group
        });
        $(".total", this).val(total);      // store total
    });
});

This works with much simpler and more generic HTML you can see here in the working example: http://jsfiddle.net/jfriend00/fCLT7/.  This works for an arbitrary number of groups of boxes and an arbitrary number of items in each group.
Comment: Added a generic jQuery option to my answer that totals arbitrary groups of rows, just using class names and a parent div for each group.

Is there something wrong in my script?


How do you solve this differential equation by changing the dependent variable $y$?

Question: $$(1+y^2)=(\arctan(y)-x)\frac{dy} {dx}$$
The hint says to use $u=\arctan(y)$.
My working out so far is:
$$y=\tan(u) \implies \frac{dy} {dx}=\sec^2(u)\frac{du} {dx}\\ \text{Substituting: }\; 1+\tan^2 (u)=(u-x)\sec^2 (u)\frac{du} {dx}\\
\sec^2 (u)=(u-x)\sec^2 (u)\frac{du} {dx}\\
1=(u-x)\frac{du} {dx}.$$
Any help would be greatly appreciated.
Comment: What about initial conditions?
Comment: No initial conditions were given.
Comment: the solution containes the Product-Logarithmus
Answer: Assuma u(x) is an invertible function, and set x(u) as the inverse. Then
$\frac{dx}{du} = x' = u-x$
$\implies x' + x = u$
Homogenious solution is $x_h = c.e^{-u}$, c any constant depending on initial condition.
The particular solution is $x_p(u) = au + b \implies a+ au + b = u \implies a =1, b=-1 \implies x_p(u) = u-1$.
Then $x(u) = c.e^{-u} + u - 1$.
Rewrite $u = arctan(y)$.
That far I could come up without knowing about $c.$
Answer: With the hint:
Using your approach, we had $$1=(u-x)\frac{du}{dx}$$
$$\implies \frac{dx}{du}=u-x$$
$$\implies \frac{dx}{du}+x=u$$
Can you see a linear DE?
Without the hint:
Note that $$\frac{dy}{dx}=\frac{1+y^2}{\tan^{-1}y-x}$$
$$\implies \frac{dx}{dy}=\frac{\tan^{-1}y-x}{1+y^2}$$
$$\implies \frac{dx}{dy} + \frac{x}{1+y^2}= \frac{\tan^{-1}y}{1+y^2}$$
This is a linear DE, where integrating factor is $e^{\tan^{-1}y}$,
$$\implies \frac{d}{dy}(xe^{\tan^{-1}y})=e^{\tan^{-1}y}\frac{\tan^{-1}y}{1+y^2}$$
$$\implies xe^{\tan^{-1}y}= \int e^{\tan^{-1}y}\frac{\tan^{-1}y}{1+y^2}dy$$
Taking $\tan^{-1}y = t$ for the integration, we get:
$$xe^{\tan^{-1}y}=\int te^tdt$$
Applying by parts,
$$xe^{\tan^{-1}y}=te^t-e^t+C$$
And hence,
$$xe^{\tan^{-1}y}=\tan^{-1}y(e^{\tan^{-1}y}-1)+C$$
$$\implies x=\tan^{-1}y(1-e^{-\tan^{-1}y})+Ce^{-\tan^{-1}y}$$
Comment: @corbah haha thanks!


GMAP Module map not showing markers after updates with js error: Clusterer is not defined

Question: I've recently taken a live site down for updates and development. I have updated from core 7.39 to 7.41 and updated numerous modules including jQuery update. After the updated, I noticed that my map was zooming to it's max extent and not displaying markers. The only diagnostic error I get is an Uncaught ReferenceError: Clusterer is not defined.I can confirm the the markers are being loaded by going into console and logging the drupal.settings.gmap.aut1map.markers variable. I don't have a lot of experience with the GMAP module, so any help would be appreciated.
Thanks in advance.
UPDATE: tried to update to dev version, no real change.
UPDATE: From what I can tell, it appears that the GMAP version I have installed is has this patch applied GMAP Clusterer.js issues
Answer: So, it's actually a rookie mistake. Updating the module wipes out all the third party js files you download. took me longer than it should to figure this out.
Comment: Hm, think I also made such mistake in the past when I didn't realise the real purpose of the typical libraries subfolder to put module related libraries (and instead incorrectly put such libraries in the module subfolder). If you then update a module you run into a similar problem, ie the library is gone (or moved to some backup folder at best)
Comment: WHICH issue is it?
Comment: Hi pierre, just updated. As above, I'm not sure exactly.
Comment: so, it's my own fault, the script wasn't in the right place.


Showing $[a, \infty) = \bigcap (a - \frac{1}{n}, \infty) $

Question: I am trying to show: $[a, \infty) = \bigcap_{n=1}^{\infty} (a - \frac{1}{n}, \infty) $
If we take $x \in [a, \infty)$, then $x > a > a - \frac{1}{n} $ for all $n$. Hence, $x$ is in the intersection.
Similarly, if $x$ is in the intersection, then $x > a - \frac{1}{n} \implies x = a \implies x \geq a \implies x \in [a , \infty )$
Is this a valid solution? Can someone help me? Thanks
Comment: $x \geqslant a > a-\frac1n$.
Answer: The first half of your argument, showing that $[a,\infty)\subseteq\bigcap_{n\ge 1}\left(a-\frac1n,\infty\right)$, is correct, but the second half is not. It is certainly not true that $x>a-\frac1n$ implies that $x=a$, which is what you've written, though probably not what you meant. What is true is that if $x>a-\frac1n$ for all $n\in\Bbb Z^+$, then $x\ge a$; this is what you need, but it's easier to prove it indirectly.
It's probably easiest to show that $\bigcap_{n\ge 1}\left(a-\frac1n,\infty\right)\subseteq[a,\infty)$ by showing that if $x\notin[a,\infty),$, then $x\notin\bigcap_{n\ge 1}\left(a-\frac1n,\infty\right)$, so suppose that $x\notin[a,\infty)$; then $x<a$, so $a-x>0$. By the Archimedean property there in an $n\in\Bbb Z^+$ such that $\frac1n<a-x$, and hence $x<a-\frac1n$, and I expect that you can easily finish it from here.
Comment: does it not follow that if $a - b < \frac{1}{n} $ for all $n$, then $a = b $ ?
Comment: @Emprendedor: No, it follows that $a\le b$.
Comment: So To finish the proof: $x < a - 1/n$ implies $x < a$ which implies $x \in (- \infty , a) $ which implies $x$ cannot be in the intersection. Is this correct?
Comment: @Emprendedor: No, this is circular. What is true is that $x<a-\frac1n$ implies that $x\notin\left(a-\frac1n,\infty\right)$, which in turn implies that $x$ is not in the intersection. If you already knew that $x\in(-\infty,a)$ implied that $x$ is not in the intersection, you'd already know the result.
Comment: thanks you for your help Brian. One last question: Can we also show by same method above that $ ( - \infty , a] = \bigcap (- \infty, a + \frac{1}{n}) $ ?
Comment: @Emprendedor: You're very welcome. Yes, that argument will be the mirror image, so to speak, of this one.


How to make master detail relation (sub-report) in Birt designer with POJO data set?

Question: My birt report uses POJO data source. Here is my POJOs, getters and setters have been omitted for simplicity sake:
<code>public class Author{
  String name;
  String email;
  List<Book> books;
}
public class Book{
  String title;
  String genre;
  Date publishDate;
}
</code>
My POJO data set is based on Author class. Now I want to make one table which will list all Authors and all his books. I've reviewed included to BIRT example report under the Sub Report folder. It does what I want but with JDBC data set. I can't figure out how to do the same but with POJO data set. Any help much appreciated!
Comment: I am also having the same problem but grouping does not solve my problem as there are authors with the same name exist and also authors have to be listed in a particular sequence in the report. Any solution for this? kindly help me.
Answer: Similar case is described here. Your main class is Author class, but you can also add Book properties to data set columns. Then you will have the data set with all books that can be grouped by author name. Grouping can be done eg. in the list/table control configuration or in Data Cubes section.


Is this a sustainable betting strategy on a 50/50 game?

Question: There is a 50/50 chance of winning a game. I bet small on every game and wait for a certain number of losses in a row, say 5, and then bet big (more than 32 times the original bet) on the 6th game, thus increasing the probability of success. If I still continue to lose I then double up every time until I make back that 6th bet (this would be the Martingale system). I can't see the flaw but I feel like there is one? Can anyone give a probabilistic explanation as to why this strategy would fail?
Comment: The result of those five loses in the row don't increase your chances of winning in the sixth.
Comment: You always have a chance of losing again and again.  Even though the expected value of the game is presumably fair, you can always run out of money (since you presumably started with a finite quantity).  Once upon a time, I played a textbased mmorpg that had a gambling house in it, and I used to bet like this (and frequently came out on top), however I lost literally 37 games in a row (that is not an exaggeration) in a 50-50 game, bankrupting me several times.  Fortunately, I learned my lesson in a *game* and not using real money.
Comment: If I flip a coin 5 times and every time it lands on tails, isn't that a conditional probability problem? Wouldn't that lower the probability that it would land heads on the next flip?
Comment: No, that is incorrect, @omar. Look up conditional probabilities. Coin tosses are independent events.
Comment: Ok. Got it. Thanks!
Comment: @JMoravitz then the prng cheated you. you've never actually encountered 37 sequential 50-50 tosses.
Comment: @naiad 37 consecutive heads is no more or less likely than any other outcome. So to say that 37 heads is really unlikely so it must have been the prng cheating you is just as silly as saying that hhhhtththhtthhttthtthhhhtthhhtththttt is really unlikely so that couldn't happen with a true coin, either.
Comment: No, the strategy won't work. You are committing the [Gambler's fallacy](https://en.wikipedia.org/wiki/Gambler's_fallacy).
Comment: @DavidRicherby any observation of hhhhtththhtthhttthtthhhhtthhhtththttt is also cheating, yes.
Answer: There is no problem in what you describe. But your strategy assumes that you have an unlimited "bank" to bet from.
If you have a finite amount of cash in bank, then the probability of eventual bankrupt is equal to 1.
Comment: Im not sure what you mean.  If i understand you right then my answer is:

Probability doesn't work that way. Yes, the probability that you are losing 5+1=6 times is very low.

But losing the 6th time conditioned on you already lost 5 times , are still 50/50 im afraid.
Comment: Ok. So I understand that I would run out of cash if I continually doubled each losing bet. But what about the first part? Doesn't the fact that I've lost 5 in a row increase my odds of winning? Wouldn't betting large effectively increase my odds to greater than 50 percent?
Comment: Got it. Thanks!
Comment: Also, the strategy assumes that the house will accept bets of unlimited size.  (Even if you have unlimited funds, it doesn't mean the house does.)
Answer: This is a perfectly sustainable strategy, if you can take out infinite loans. This is totally possible in a pure mathematical environment, and you can make a scenario in which you win infinitely; however, if you cannot take out loans, then the odds of your losing all of your money on $1$ run are $$\dfrac{1}{\log_2\left(\dfrac{\text{total money}}{\text{base bet}}\right)}$$ and your odds of doubling your money on $1$ run are once again $$\dfrac{1}{\log_2\left(\dfrac{\text{total money}}{\text{base bet}}\right)}$$ so you are just as likely to lose everything as to double your money on a run, so your expected payout per run is $\$0$. Please do not try this strategy in real life, because it will appear that you are steadily profitable until that awkward moment when you are not, and suddenly you have lost everything.
Comment: I love that "Please do not " part , as if it was drinking soda in the bus :-)


Can't access phpmyadmin

Question: I tried to update my phpmyadmin to the newest version but now I get this error message when I try to access it:

Forbidden
You do not have permission to access
  this document.

I have a vps hosting with centos. Does anyone know how to fix this problem?
Answer: Sounds like the new phpMyAdmin directory has the wrong permissions. Try:
<code>chown -R apache:apache /home/somewhere/phpMyAdmin
</code>
Obviously substitute in the appropriate path to phpMyAdmin. Also check what user Apache is using (could be apache, nobody, www, www-data, etc...).
Comment: Tried to run the command but nothing happened!
Comment: If it worked nothing will appear to have happened. Look at the directory to see if the ownership has changed (`ls -al /somewhere/phpMyAdmin`).
Comment: It could be wrong permissions, but it could also be other cases. You should look at the error logs, like @ooshro suggests.
Answer: First you need to look the logs. In CentOS Apache write log in /var/log/httpd/.
If "/home/somewhere/phpMyAdmin" is symlink, add "Options FollowSymlinks" inside ...

Can't access phpmyadmin


Rudin Theorem 6.10 doubt

Question: This question is about Riemann Stieltjes integral:
Here is definition:

Let $\alpha$ be a monotonically increasing function on $[a, b]$ (since $\alpha(a)$ and $\alpha(b)$ are finite, it follows that $\alpha$ is bounded on $[a, b]$). Corresponding to each partition $P$ of $[a, b]$, we write
  $$ \Delta \alpha_i = \alpha \left( x_i \right) -  \alpha \left( x_{i-1} \right). $$
  It is clear that $\Delta \alpha_i \geq 0$. For any real function $f$ which is bounded on $[a, b]$ we put
  $$
\begin{align}
U(P, f, \alpha) &= \sum_{i=1}^n M_i \Delta \alpha_i, \\
L(P, f, \alpha) &= \sum_{i=1}^n m_i \Delta \alpha_i,
\end{align}
$$
  where $M_i$, $m_i$ have the same meaning as in Definition 6.1, and we define
  $$
\begin{align}
\tag{5} \overline{\int_a^b} f d \alpha = \inf U(P, f, \alpha), \\
\tag{6} \underline{\int_a^b} f d \alpha = \sup L(P, f, \alpha), \\\,
\end{align}
$$
  the $\inf$ and $\sup$ again being taken over all partitions. If the left members of (5) and (6) are equal, we denote their common value by
  $$ \tag{7} \int_a^b f d \alpha $$
  or sometimes by
  $$ \tag{8} \int_a^b f(x) d \alpha(x). $$
  This is the Riemann-Stieltjes integral (or simply the Stieltjes integral) of $f$ with respect to $\alpha$, over $[a, b]$.
If (7) exists, i.e., if (5) and (6) are equal, we say that $f$ is integrable with respect to $\alpha$, in the Riemann sense, and write $f \in \mathscr{R}(\alpha)$.

This is Rudin PMA's Th 6.10:

Suppose $f$ is bounded on $[a, b]$, $f$ has only finitely many points of discontinuity on $[a, b]$, and $\alpha$ is continuous at every point at which $f$ is discontinuous. Then $f \in \mathscr{R}(\alpha)$.
Proof: Let $\varepsilon > 0$ be given. Put $M = \sup \left\vert f(x) \right\vert$, let $E$ be the set of points at which $f$ is discontinuous. Since $E$ is finite and $\alpha$ is continuous at every point of $E$, we can cover $E$ by finitely many disjoint intervals $\left[ u_j, v_j \right] \subset [a, b]$ such that the sum of the corresponding differences $\alpha\left(v_j\right) - \alpha \left( u_j \right)$ is less than $\varepsilon$. Furthermore, we can place these intervals in such a way that every point of $E \cap (a, b)$ lies in the interior of some $\left[ u_j, v_j \right]$.
Remove the segments $\left( u_j, v_j \right)$ from $[a, b]$. The remaining set $K$ is compact. Hence $f$ is uniformly continuous on $K$, and there exists $\delta > 0$ such that $\left\vert f(s) - f(t) \right\vert < \varepsilon$ if $s \in K$, $t \in K$, $\left\vert s-t \right\vert < \delta$.
Now form a partition $P = \left\{ x_0, x_1, \ldots, x_n \right\}$ of $[a, b]$, as follows: Each $u_j$ occurs in $P$. Each $v_j$ occurs in $P$. No point of any segment $\left( u_j, v_j \right)$ occurs in $P$. If $x_{i-1}$ is not one of the $u_j$, then $\Delta \alpha_i < \delta$.
Note that $M_i - m_i \leq 2M$ for every $i$, and that $M_i - m_i \leq \varepsilon$ unless $x_{i-1}$ is one of the $u_j$. Hence, as in the proof of Theorem 6.8,
  $$ U(P, f, \alpha) - L(P, f, \alpha) \leq \left[ \alpha(b) - \alpha(a) \right] \varepsilon + 2M \varepsilon.$$
  Since $\varepsilon$ is arbitrary, Theorem 6.6 shows that $f \in \mathscr{R}(\alpha)$.

[Code borrowed from here.]
My question is:
What I can't understand is:

Why do we treat $u_j$'s differently?
How do we get $U(P, f, \alpha) - L(P, f, \alpha) \leq \left[ \alpha(b) - \alpha(a) \right] \varepsilon + 2M \varepsilon$ in last line?
Comment: You seem to be referring to Riemann-Stieltjes Integral wrt $\;\alpha\;$ . Define this clearly : not all have Rudin's book.
Comment: @DonAntonio, done, as per requirement.
Answer: The partition $P$ contains good and bad intervals $I_i$. For the good intervals we have $M_i-m_i\leq\epsilon$. Their contribution to $\Delta_{\rm total}:=U(P,f,\alpha)-L(P,f,\alpha)$ therefore is $\leq \bigl(\alpha(b)-\alpha(a)\bigr)\,\epsilon\>$; here Rudin refers  to the proof of Theorem 6.8. The sum of the increments $\Delta\alpha_i$ over the bad intervals is $\leq\epsilon$, and $M_i-m_i\leq2M$ for all these intervals. It follows that the contribution of the bad intervals to $\Delta_{\rm total}$ is $\leq2M\epsilon$.

Rudin Theorem 6.10 doubt