Correct way to create Departments/Categories cck selectors in Drupal 7?

Question: 1. My Scenario:
I'm building a shopping cart and using Ubercart+Drupal 7 for it.
Manufacturers will be able to log in and create their own products with

Product attributes {Name, SKU, price etc}
Department + Category - can be multiple
a brand

A product can exist in multiple Department/Categories too.
Sample screenshot:
http://picpaste.com/pics/menu.1375842751.png
(wanted to post here but low reputation, can an admin post it here pls?)
2. Elaboration of the situation
I'm having trouble figuring out the most correct, stable and fastest way to set up Department/Categories with the following goals and criteria:
2i. Product - CCK fields for adding Department, Categories to product:

Select a department, and it's associated category (Dep+Cat)
There are going to be about 12 Deps, 15 Cats each = 180 categories. I do not want to list this as an entire taxonomy dropdown - confusing and ugly. My thought right now is to have two multi-select boxes side by side - "Department" with 12 items & "Category". To illustrate, here's a simple wireframe: http://picpaste.com/Add_dept_cat.png
As per the wireframe, manufacturers can list the product in multiple related departments and categories.

2ii. Add / Create + Add brand to product
 - Add an existing brand to the product
 - If brand doesn't exist, add a new brand and add it to the product
 - Brands are attached to the manufacturers who created them
2iii. I'm searching and finding modules such as taxonomy_menu, taxonomy_hierarchy and content_taxonomy. However a lot of them look like they are not stable or supported for Drupal 7. Even if they are ok, I'm not sure if I'm heading in the right direction by using these modules.
2iv. Shoppers (Authenticated users) should be able to see the main menu on top which actually lists the departments available. On hovering, a particular department's categories & brands within are shown. They can click a department from the menu or drill down to category or brand. On selecting one of these three, the product listing comes up -- if department, shows department items, allowing filtering by brand/category -- if category selected, e.g "moisturisers", shows all items and allows filtering by brand --- if brand selected, shows all items for that brand in this department / category, allows you to move up and see all items for the brand in this department, and in other departments..
3. Question
Having said all that, my question is more to do with the CCK input fields of department, categories & brands and the underlying taxonomy / menu structures and modules. For 2iii, any tips are welcome, but I'm not at that stage yet anyways so I'm not looking at that yet.
I'm having trouble with

how I should structure my data in taxonomies or other structures (menus?)
how to create the cck fields for the manufacturer to add multiple department / categories to his product
how he can add a brand to his product or create and add a new brand to his product

Ideally I want to achieve the above with modules in the most Drupal-correct, stable and fastest way possible, without having to write any code.
Thanks
Edit: one more question. If user adds multiple "Department-category" to a product, how to allow one of it to be the "main"?
Answer: Your concern is true. Anyone that tried to build an eshop with multiple categories had the same question in the beggining.

1) how I should structure my data in taxonomies or other structures (menus?)

You can create a large taxonomy tree the way I see it on the screenshot. Use taxonomy_manager for better UI. Also to display the taxonomy trees as mega menus you can search for "mega menu" in the drupalmodules.com you will find many such modules.

2) how to create the cck fields for the manufacturer to add multiple department / categories to his product

You can use the Hierarchical_select module. It is a must for such functionality.

3) how he can add a brand to his product or create and add a new brand to his product

Create a new Vocabulary for Brands and add a field with autocomplete. You can use Hierarchical Select also. It has an option (with proper permissions) to add a term if it does not exist.
Comment: Thanks for the input TheodorosPloumis! You've definitely pointed me in the right direction.
Answer: For megamenus, here's an excellent click-by-click tutorial:
http://www.cmsquickstart.com/blog/drupal-theme-design-tutorial-2-mega-menus


É possível criar um objeto/class/interface que represente um assinatura de uma function?

Question: Tudo já funciona como esperado em meu código. O que estou querendo é torna-lo mais verboso, fazendo com que as assinaturas do método sejam mais auto-explicativas (sei que posso utilizar comentários Docs para isso, mais gostaria de também utilizar os tipos do TypeScript) e possam ser melhor validadas pelos TSLint's da vida.
O que tenho hoje:
class Test{
    testMetadada<T>(expression: (t: T) => void) {
        // ...
    }
}

O objeto expression é do tipo (t: T) => void, o que não é muito explicativo, gostaria por exemplo que fosse possível algo como:
class Expression<T> extends (t: T) => void{

}

ou
interface Expression<T> extends (t: T) => void{

}

ou
let Expression = ((t: T) => void)<T>;

Para que meu método fosse algo como:
class Test{
    testMetadada<T>(expression: Expression) {
        // ...
    }
}

Onde Expression representasse a mesma function (t: T) => void.
Há algo que possa fazer nesse sentido?

Veja aqui o exemplo do que estou tentando implementar com isso (a possibilidade de utilizar Arrow function do TypeScript como expressões Lambda Expressions do C# para obter metadados)
Comment: Gostei da pergunta. Acho que eu posso pensar em algo se você der um exemplo mais "palpável", eu não consegui entender bem o queres fazer.
Comment: @LINQ, pois bem, o que pretendo não é nada funcional, é apenas poder criar um Tipo, que presente a parâmetro Function. Olhando agora isso parece ser algo um pouco confuso mesmo. Não sei bem como ter algo mais "palpável". Olhou o exemplo? O que não está claro para você? Se puder me questionar sobre os pontos que não entendeu do meu objetivo?
Comment: @LINQ, veja, o que quero é tornar o tipo `(t: T) => void` do parâmetro do método `testMetadada` um Tipo realmente no **Typescript**, isso poderia ser através de um Objeto, Class ou Interface. Será que melhorou?
Answer: É possível utilizar type aliases:
type Expression<T> = (t: T) => void;

Ficando assim a assinatura do método:
class Test{
    testMetadada<T>(expression: Expression<T>) {
        // ...
    }
}

Exemplo atualizado da solução.

Baseado na resposta a essa pergunta no SOen.


Question about Ramanujan's proof of Bertrand's Postulate

Question: I am reviewing Ramanujan's proof of Bertrand's Postulate which can be found here.
At step #7, he writes: "But it is easy to see that..."
$\log\Gamma(x) - 2\log\Gamma\left(\frac{1}{2}x + \frac{1}{2}\right) \le \log[x]! - 2\log\left[\frac{1}{2}x\right]!$
As $\Gamma(x+1) = [x]!$, this seems reasonable enough to me.
My question is: why did Ramanujan choose $\frac{1}{2}$.  It seems like this would be true for any $n \ge 0$ where:
$\log\Gamma(x) - 2\log\Gamma\left(\frac{1}{2}x + n\right) \le \log[x]! - 2\log\left[\frac{1}{2}x\right]!$
Is that correct?
Thanks,
-Larry
Comment: For those interested, [here](http://www.zyymat.com/ramanujans-proof-of-bertrands-postulate.html) is an easier-to-read html version of Ramanujan's proof of Betrand's Postulate.
Comment: Having cracked a book and taken out my magnifying glass, I feel that you may have mis-stated (7). I would be the last to down-vote for a typo...
Comment: Thanks for the tip.  I'll check it and update my question.
Comment: @daniel: I checked it and it's possible that 1/3 may be 1/2.  It does look like 1/3 to me.  Is there any other area where you see a mistake?  That's the only ambiguity that I see.
Comment: Thanks!  I've change the detail to 1/2.  Thanks very much for the correction!  :-)
Answer: Inequality (7) is delicate. $\log x!-\log\Gamma(x)$ is a little bigger than $2\log (x/2)!-2\log\Gamma(x/2+1/2),$ which makes the lower bound tight. $\log\Gamma(x+1)$ is no different from $\log x!$ so he relies on $2\log\Gamma(x/2+1/2)$ being slightly less than $2\log(x/2)!$ to achieve the upper bound.
In (8) he refers to the Stirling approximation for the bounds in (7), so there may have been an element of computational convenience in the choice 1/2. Once he establishes the numerical bound in (8),(9) he has no further use for the $\log\Gamma$ functions used in (7).
There may be room for a constant other than 1/2 but anything you do will have an effect at both ends. $2\log\Gamma(x/2+3/4)$ might be closer to and still less than $2\log(x/2)!$ but will the left inequality hold? It appears not.
Whether 1/2 is optimal I am not sure but I would guess so. When you examine the asymptotic behavior of $\log\Gamma$ the derivative becomes important. Question 94582, though I can't link to it at the moment, concerned this property. The factor 1/2 in argument of $\log\Gamma$ (and 2 outside it) make it something to check as an explanation of the choice of 1/2.
Edit: In light of this question it appears that $1/2$ is needed to give desired asymptotic behavior to the l.h.s. and r.h.s. For completeness:
$PG(x) :=$ Polygamma(x). From (7):
$$\ln\Gamma(x) -2\ln\Gamma\left(\frac{x+1}{2}\right)\leq \cdot \leq \ln\Gamma\left(x+1\right)-2\ln\Gamma\left(\frac{x+1}{2}\right) $$
$$\frac{d}{dx}\left(\ln\Gamma(x)-2\ln\Gamma\left(\frac{x+1}{2}\right)\right)= PG(x)-PG\left(\frac{x+1}{2}\right)\sim \ln 2^-$$
$$\frac{d}{dx}\left(\ln\Gamma\left(x+1\right)-2\ln\Gamma\left(\frac{x+1}{2}\right)\right)= PG\left(x+1\right)-PG\left(\frac{x+1}{2}\right)\sim \ln 2^+$$
So $\log[x]! -2\log[x/2]!$ is trapped between two functions which approach $\log 2$ from above and below. The 1/2 is from $\frac{x+1}{2}$ and is essential to the asymptotic limits.


Angular CLI fileReplacements for default/development

Question: I have a rather complex angular.json because I have multiple projects. What I would like to have is separate environment.ts files per project. Replacing the environment file when the build target is production seems to be pretty straightforward:
"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/private-label/redacted/environments/environment.prod.ts"
      }
    ],
  }
}

What I'm looking for is a way to do the same with the default/development configuration. The angular.json does not contain a configuration node for anything like that that I can find and so I'm not sure if it is possible and/or where to specify fileReplacements when not targeting production.
Of course, if there is a better way to handle environments per project that I'm not seeing I would also be interested in that.
Answer: I assume with "default/development configuration" you are referring to what is served with the ng serve command.
Option 1: replace environment files:
You can specify the fileReplacements array in the build object as well (this one is used for ng serve).
  "build": {
    "options": {
      [...]
      "fileReplacements": [
        {
          "replace": "src/environments/environment.ts",
          "with": "src/environments/environment.development.ts"
        }
      ]
    },
    "configurations": {
      // other - non default - configurations
    }
  }

Option 2: specifiy default configuration:
If you want to serve an already existing configuration withng serve, you can change the serve options:
  "configurations": {
    "youConfigName": {
      // config details here
    }
  },
  [...]
  "serve": {
    "options": {
      "browserTarget": "name-of-your-app:build:youConfigName"
    }
  }

The important point is to set the build configuration target with :yourConfigName.

Both options are configured per project and therefore allow you full control.
Answer: Also, be sure to execute the right command to start/serve your app. In my case, I'm using Azure Pipelines to deploy to Azure App Service, and the command is:

Note that, "--configuration=production" is mandatory in order to achieve the file replacement.
I also put the "fileReplacements" section in both: "build" and "configuration" section of the angular.json file1:

1 In Angular 17 (and maybe earlier) you have to place fileReplacements block not next to options, but inside it. Also, bear in mind that fileReplacements inside configurations -> production overwrite fileReplacements from outer architect -> build -> options. So if you need replacements from both, you have to merge them by hand and write all fileReplacements inside configurations -> production.
Comment: By placing your replacement outside the configuration does that mean you will always build in production ?  What is the command you use for DEV and for PROD in this scenario ?
Comment: @MarcRoussel there is only one configuration in "configurations" on the screenshot, so this project can only be built with "production" configuration. If you try to specify `--configuration=asdf` parameter in build command, you'll get an error.
Answer: The answer of @jowey is working but with a small extension for Angular 8. I had to prepend the url with ./
"replace": "./src/environments/environment.ts",
"with": "./src/environments/environment.development.ts"


How to parse an XML file java

Question: I'm trying to parse this XML file to get name. For example, "2b Managing the Non-Profit Organization".
I've tried to use DOM and xpath but I failed.
I'd like to loop through this xml and extract each song name. Here is my xpath example.
 XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nList = (NodeList)xPath.evaluate("/plist/dict/dict/dict/string[@rollno='artist']", root, XPathConstants.NODESET);
        for (int i = 0; i < nList.getLength(); ++i) {
            Element e = (Element) nList.item(i);
            String value = e.getFirstChild().getNodeValue();
        //   System.out.print("string:" + value+"");
            names_and_numbers.add( value);
               System.out.print(names_and_numbers);

        }

Thanks
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict  rollno="393">
    <key>Major Version</key><integer>1</integer>
    <key>Minor Version</key><integer>1</integer>
    <key>Application Version</key><string>8.2.1</string>
    <key>Features</key><integer>5</integer>
    <key>Show Content Ratings</key><true/>
    <key>Music Folder</key><string>file://localhost/C:/WINNT/Profiles/A062616/My%20Documents/My%20Music/iTunes/iTunes%20Music/</string>
    <key>Library Persistent ID</key><string>542CEAB7C8BAE946</string>
    <key>Tracks</key>
    <dict>
        <key>124</key>
        <dict>
            <key>Track ID</key><integer>124</integer>
            <key>Name</key><string>2b Managing the Non-Profit Organization</string>
            <key>Artist</key><string>Peter Drucker</string>
            <key>Album</key><string>Managing the Non-Profit Organization</string>
            <key>Genre</key><string>AudioBook</string>
            <key>Kind</key><string>MPEG audio file</string>
            <key>Size</key><integer>15096591</integer>
            <key>Total Time</key><integer>2680320</integer>
            <key>Date Modified</key><date>2008-12-17T18:37:02Z</date>
            <key>Date Added</key><date>2008-12-17T17:36:38Z</date>
            <key>Bit Rate</key><integer>45</integer>
            <key>Sample Rate</key><integer>22050</integer>
            <key>Persistent ID</key><string>21B422A222B952AD</string>
            <key>Track Type</key><string>File</string>
            <key>Location</key><string>file://localhost/C:/WINNT/Profiles/A062616/My%20Documents/My%20Music/iTunes/iTunes%20Music/Peter%20Drucker/Managing%20the%20Non-Profit%20Organization/2b%20Managing%20the%20Non-Profit%20Organizat.mp3</string>
            <key>File Folder Count</key><integer>4</integer>
            <key>Library Folder Count</key><integer>1</integer>
        </dict>
        <key>126</key>
        <dict>
            <key>Track ID</key><integer>126</integer>
            <key>Name</key><string>1a Managing the Non-Profit Organization</string>
            <key>Artist</key><string>Peter Drucker</string>
            <key>Album</key><string>Managing the Non-Profit Organization</string>
            <key>Genre</key><string>AudioBook</string>
            <key>Kind</key><string>MPEG audio file</string>
            <key>Size</key><integer>16393005</integer>
            <key>Total Time</key><integer>2683402</integer>
            <key>Date Modified</key><date>2008-12-17T18:37:02Z</date>
            <key>Date Added</key><date>2008-12-17T17:36:38Z</date>
            <key>Bit Rate</key><integer>48</integer>
            <key>Sample Rate</key><integer>22050</integer>
            <key>Persistent ID</key><string>21B422A222B952AF</string>
            <key>Track Type</key><string>File</string>
            <key>Location</key><string>file://localhost/C:/WINNT/Profiles/A062616/My%20Documents/My%20Music/iTunes/iTunes%20Music/Peter%20Drucker/Managing%20the%20Non-Profit%20Organization/1a%20Managing%20the%20Non-Profit%20Organizat.mp3</string>
            <key>File Folder Count</key><integer>4</integer>
            <key>Library Folder Count</key><integer>1</integer>
        </dict>
        <key>128</key>
        <dict>
            <key>Track ID</key><integer>128</integer>
            <key>Name</key><string>1b Managing the Non-Profit Organization</string>
            <key>Artist</key><string>Peter Drucker</string>
            <key>Album</key><string>Managing the Non-Profit Organization</string>
            <key>Genre</key><string>AudioBook</string>
            <key>Kind</key><string>MPEG audio file</string>
            <key>Size</key><integer>16412357</integer>
            <key>Total Time</key><integer>2672195</integer>
            <key>Date Modified</key><date>2008-12-17T18:37:02Z</date>
            <key>Date Added</key><date>2008-12-17T17:36:38Z</date>
            <key>Bit Rate</key><integer>49</integer>
            <key>Sample Rate</key><integer>22050</integer>
            <key>Persistent ID</key><string>21B422A222B952B0</string>
            <key>Track Type</key><string>File</string>
            <key>Location</key><string>file://localhost/C:/WINNT/Profiles/A062616/My%20Documents/My%20Music/iTunes/iTunes%20Music/Peter%20Drucker/Managing%20the%20Non-Profit%20Organization/1b%20Managing%20the%20Non-Profit%20Organizat.mp3</string>
            <key>File Folder Count</key><integer>4</integer>
            <key>Library Folder Count</key><integer>1</integer>
        </dict>
      </dict>
   </dict>
</plist>

Comment: This is not XML. XML always has parent node which is missing
Answer: Try this XPath expression instead:
/plist/dict/dict/dict/key[text()='Name']/following::string[1]

This will select the first string following a key with text Name
public static void main(String[] args) {
  try {
    InputSource root = new InputSource(XMLParse.class.getResourceAsStream("/data.xml"));
      XPath xPath = XPathFactory.newInstance().newXPath();
      NodeList nList = (NodeList)xPath.evaluate("/plist/dict/dict/dict/key[text()='Name']/following::string[1]", root, XPathConstants.NODESET);
      for (int i = 0; i < nList.getLength(); ++i) {
          Element e = (Element) nList.item(i);
          String value = e.getFirstChild().getNodeValue();

          System.out.println("string:" + value+"");

      }
 }  catch (XPathExpressionException e) {

    e.printStackTrace();
 } catch (DOMException e) {

    e.printStackTrace();
 }
}

How to parse an XML file java


Some People just ask questions, Not giving answers at all

Question: I have found couple of people who just asking question , But never give any answer or never try to give answer We need to take some action against them.
Because they are taking benefit from community but not giving anything to community . Please see couple of user as they are asking questions only are listed below.
https://magento.stackexchange.com/users/22561/sachin-s
https://magento.stackexchange.com/users/39050/jeeva-rathinam
Comment: Here we are talking about the people who dont answer at all If you are giving less answer that is okay But you are ignoring people while you have answer and also you use community for your own selfishly then its wrong
Comment: @JulienLachal and #BabyinMagetno Still a Better Love Story than Twilight
Comment: What you said is `Golden words - sharing` , your point not only applicable for community also for all things in world.
if all rich peploes share their money with poor, than it will be awesome, no persons in the world will die by hungry....
Comment: @BabyinMagento pretty ironical coming from someone that has almost 500 questions (ratio of ~5:1 with answers) and kept spamming the community for a while don't you think?
Comment: Have some mercy, this poor guy is desparately trying to export products for several weeks now and is not able to communicate his problems clearly. Questions are downvoted and closed quickly, most probably eventually deleted, and because they are of very low quality, nobody can help anyways. This is already handled well, I'd say.
Comment: Really good question, I completely agree on your point, but what i guess is members who created account before 1.5 years may not have complete 1.5 yrs exp on magento.
they might worked on other platformas also like wordpress, drupal, joomla etc.... but i appreciate your concern for the community & its great that you answered more questions than asking.
Comment: I always Believe in that If you have knowledge then check your knowledge and share your knowledge with others. And also I am expecting with others that if you are a member of this community then share your knowledge with others
Comment: Also read this: http://meta.stackexchange.com/questions/19665/the-help-vampire-problem
Comment: @TejabhagavanKollepara He is quite new user leave him now
Comment: @TejabhagavanKollepara for new user we can put exception that they are new in magento and while they are learning they may be not understand something
Comment: https://magento.stackexchange.com/users/783/marty-wallace  this also
Answer: How about taking actions to help them instead of against them?
If the questions are high quality questions, then they help the community.
If not, just downvote them, or vote to close them.
You cannot force the people to answer if they don't know how to answer or if they don't want to answer.
Just for the record jeeva-rathinam already has a temporary ban for violating the terms of this website.
That's the most I'm willing to do.
I will not delete an account just because they don't have any answers.
I don't think it's healthy to open this pandora's box.
If I do this, people might start arguing that 10 answers in 11 months is not that much either.
I don't want to go that way.
Comment: I undersrstand you, but you cannot force people to help if they don't want to. In every community there will be lurkers. It's how it works. You can track them down and break their hands or something. (just for the record, I was trying to be sarcastic. I don't encourage violence - in this case.)
Comment: But if person has 1.5 years of exp. then they have some knowledge and if they are asking good questions then they also have very good answers but they are not sharing their knowledge with community  , that is not good
Comment: Ok Thank you for your answers and support for this community.
Answer: On top of what Marius said and if you don't feel like closing or downvoting, you have the right to ignore the questions asked by the people you mentioned if you are not fine with the way they behave.


Fix issue with VS Code: Border around all whitespaces in lines of code

Question: All my whitespaces in VS code where code is written are being highlighted and I cant seem to understand where to change these settings.
Answer: In settings (open Command Palette CTRL+SHIFT+P and search for settings) menu search for Editor: Render Whitespace it is probably set to all instead of default selection. But i honestly have no idea why it is render with boxes and not dots or arrows, maybe it can be customized by using custom themes.
Answer: It was probably because of the theme the source was using from where I copied the source code. Replaced all these spaces with regular whitespace and now it's working fine.


How to apply two color thresholds to image OpenCV

Question: I am currently trying to detect for two certain colors in a certain image. I am trying to filter an image to display pixels in a certain range. I know that to find one color, you input an upper and lower bound like so
<code>COLOR_MIN = np.array([0, 0, 130], np.uint8)
COLOR_MAX = np.array([90, 145,255], np.uint8)

dst1 = cv2.inRange(img, COLOR_MIN, COLOR_MAX)
</code>
And I simply apply dst1 to the image and everything works just as it should. An image is displayed with only pixels in those ranges. However, I would like to search for two specific ranges of colors. Should I apply the two color ranges to the image separately to get two different images, and then blend the image together? Or is there a more efficient way of displaying an image whose pixels fit in two different color ranges?
Answer: Aha! Found it. You can make a similar filter for your second color and then simply use the bitwise or operator | combining the two filters dst1 and dst2.
Comment: addWeighted() method will also work for adding 2 Mat objects, aside from bitwise operations


How to replace the host variable in a header in nginx

Question: I am trying to replace the host variable in the header in nginx configuration, such that some.random.sub.example.net becomes net-some.random.sub.example.com. i have tried the following :
if ($host ~* "^([^.]+(\.[^.]+)*)\.example.net$"){

set $sub $1;

set $host1 "http://net-$sub.example.com";

break;

}

and then in the location directive, i have:
location / {

proxy_set_header    HOST $host1;

some conf

}

it dodn't work though !
EDIT
full configuration :
server {#http

  listen          80 default_server;

  server_name     *.example.com;

  large_client_header_buffers 4 16k;

  access_log /var/log/nginx/access.log;

  error_log /var/log/nginx/error.log;

  if ($host ~* "^([^.]+(\.[^.]+)*)\.example.net$"){

  set $sub $1;

  set $host1 http://cn-$sub.example.com;

  break;

}

  location / {

    proxy_pass          http://ghs.google.com;

    proxy_set_header    HOST $host1;

    proxy_set_header    X-Forwarded-Host $host;

    proxy_set_header    X-Forwarded-Server $host;

    proxy_set_header    X-Real-IP $remote_addr;

    proxy_set_header    X-Real-HOST  $host;

    proxy_set_header    Proxy-Hostname $scheme://$http_host;

    proxy_set_header    X-Forwarded-Proto https;

    proxy_pass_request_headers     on;

    proxy_redirect                off;

    proxy_intercept_errors        on;

    proxy_redirect                false;

  }

}

Comment: What exactly didn't work?
Comment: the server passes $host instead of $host1
Comment: Show full nginx config.
Comment: updated in the question.
Answer: ok, after a lot of experiments, i solved it.
set $host1 http://cn-$sub.example.com;

should be :
set $host1 cn-$sub.example.com;

any explanation ?
Answer: See http proto -- in Host directive you don't pass http/https -- only server name


Is upstart for starting a service, and supervisord to monitor it?

Question: Is there some overlap in functionality between upstart and supervisord?
I have a java process that I need to start at boot up, and also monitor this process to make sure it stays running (try and restart it if it goes down).
Could I use upstart for both of these requirements, or would I need to use both upstart and supervisord?
Answer: If you have Upstart, then it's already likely the root process in the system (it doesn't have to be, but usually is). This means that it starts your prompt, as well as all services.
Supervisor is good at doing the same thing, as well as managing groups of programs (starting/stopping as a group, etc..) and using RPC to allow remote management of programs.
If you're not taking advantage of the last two features, then there is no real benefit. However, if you use Supervisor, it has to be started by something. You can start it from rc.local, but then it becomes your likely point of failure.
Answer: You can use upstart to both start the process at boot and restart it if it exits. The Upstart Cookbook is pretty comprehensive, and the latter functionality is documented under respawn


Adding a database to the TFS Server Instance

Question: I have posted a couple of questions about TFS databases over the past couple of months.  It was made clear that thou shall not modify TFS databases manually as it will void any support that we may have.
Is there any issue with adding a database to the TFS Server?  The database that I want to add will only have one table with about 50,000 rows and will be accessed a couple times a day.
I'm using TFS 2017.
Answer: The only rule in TFS is, don't touch the databases owned by TFS. And if you've paid for the SQL Server License you can add as many other databases as you'd like. TFS will not have any issues with that, but it won't make these databases part of the backup schedule, so you'll have to do that yourself.
AND if you're using the 1 free SQL Server Standard license that you get with a TFS server license, you're not allowed to host any other databases on that instance other than the databases that are maintained by TFS itself.


Dynamic Sizing of Circles Along a Logarithmic Spiral

Question: I have created an logarithmic spiral in HTML canvas, and plotted circles along it. Using your mouse scroll wheel you can zoom in and out of the spiral (which works) – but I am having problems updating the size of the circles to match the zoom level... I'm no math expert!
There are two values I am using when trying to calculate the circle radius:
The initial size: This makes circles smaller the further down the spiral they are. I think I have this pretty close.
The growth size: This is the amount that each circle must increase to accurately grow in size as it gets closer to the viewer. Currently circles seem to be the correct size at the beginning and end of the spiral, but are too small in the middle.
I have hacked together some janky math and I'm sure there is an actual formula for this sort of sizing. Any help would be greatly appreciated...

Here is a jsFiddle for reference
<code>// a = starting radius of spiral (2)
// b = windiness of spiral (0.05)
// spiralNum = spiral length (100.6)
// node_count_visible = number of total circles (120)
// timeOffset = scroll/zoom position at any given point (ranges from 0 to 530 when zoomed in)

offset = (spiralNum - 0.05 - node_count_visible) + id + (timeOffset/30);

var initial = Math.exp(b * offset)/4; // Eulers constant to the power of (b * offset)
var growth = a / 8.5; // This gives a rough approximation of size
node.radius = initial + growth;
</code>

Thank you in advance for any help provided...
Answer: The formula used for the spiral is $r=a\cdot e^{b\cdot\phi}$. The arc below and above a selected arc have radii $r_\pm=a\cdot e^{b\cdot(\phi\pm2\pi)}$.
The radius of a circle on the arc should be proportional to $r$, say $c⋅r$, with the condition that circles on neighboring arcs do not overlap,
$$
r_-+c⋅r_-\le r-c⋅r\land r+c⋅r\le r_+-c⋅r_+
$$
where both of them are the same condition
$$
(1+c)\le(1-c)e^{b⋅2\pi} \iff c\le \frac{e^{b⋅2\pi}-1}{e^{b⋅2\pi}+1}=\tanh(b⋅\pi).
$$
So select a $c$ satisfying this condition and use proportional circles.
Comment: Thank you, this was exactly the help I needed to figure this out...


echo data into drop list using AJAX

Question: I have this code, where when I click on a value in my first drop list, I need to get new data from MySQL into my second drop list according to my selection.
I have this code here:
$('#sale_type').change(function() {

    // get the form information
    // this can be done in many ways but we are going to put the form
    // data into a data object
    var formData = {
      'selectedValue' : $('#sale_type').val()
    };

    // send the data via Ajax
    $.ajax({
      type      : 'POST', // the method we want to use to send the data
      url       : 'getTypeDetails.php', // the url where we want to
                                                // send the data
      data      : formData, // the data object we created
      dataType  : 'json', // what type of data we want to get back
      encode    : true
    })
      // execute function when data has been sent and server
      // code is processed
      .done(function(data) {
            // HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
            // I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
            // data[0], data[1]... TO GET THE VALUE
      });

  });

});

And here is getTypeDetails.php:
<?php
    require_once('../include/global.php');

    $data = $_POST['selectedValue'];

    // Connect to database
    // Use the data to get the new information
    $query = "SELECT * FROM purchases WHERE sale_type = :data";
    // MySQL
    $results = $conn->prepare($query);
    $results->bindValue(":data", $data);
    $exec = $results->execute();
    $res = $results->fetchAll();

    $data = array();
    $i = 0;
    foreach($res as $row){
         $data[i] = $row['sale_details'];
         $i++;
    }

    echo json_encode($data);
?>

the problem is that I can't get the $data[i] into my new drop list with an id=sale_details
So I don't know what to put here:
.done(function(data) {
                // HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
                // I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
                // data[0], data[1]... TO GET THE VALUE
          });

EDIT
Those are my HTML drop lists:
النوع
                        <select id="sale_type" name="sale_type" class="dropdown-header"  style="float:right">
                                  <option value="undefined">اختر</option>
                                  <?php
                                  foreach($fetchType as $ft){ ?>
                                  <option value="<?php echo $ft['sale_type'] ?>"><?php echo $ft['sale_type'] ?></option>
                                  <?php } ?>
                            </select>
                            الصنف
                        <select id="sale_details" name="sale_details" class="dropdown-header"  style="float:right">

                            </select>

Comment: Show us the code you have tried to use in your javascript `.done` handler. Otherwise this just looks like a specification for a ___Write is all for me question___ Edit your question, DONT put code in a comment
Comment: have you got `data` in `.done`? Also write what have you done to fill second dropdown list.
Comment: I didnt add any code inside done, I am even new for AJAX and I am searching for hours now, and can't find solution
Answer: It should be something like this:
 .done(function(data) {
    var secondDropdown = $("#second-dropdown");
    secondDropdown.empty();
    $.each(data, function(index, value) {
        secondDropdown.append("<option>" + value + "</option>");
    });
   return;
  }

Comment: i tried it, no errors in the console but still not getting the result, can you help me with teamviewer ?
Answer: Replace your js code with my code

and add jquery link

in your  tag
Comment: Nope, nothing is shown, I think we should use something like data[0] data[1]...Can you help me with teamviewer ?
Comment: no, nothing, I think you should see my edit code about my html drop lists, i think I should add something to them
Comment: I have seen edit your php code like $data[$i] was $data[i]. Code should be. replace var secondDropdown = $(".dropdown-header"); into my js code.
Comment: var formData = {
          'selectedValue' : $( "#sale_type option:selected" ).val()
    };
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/100290/discussion-between-androidnation-and-jakir-hossain).

echo data into drop list using AJAX


fitting rectangle inside another rectangle in diagonal

Question: Having the following case, where we want to fit a rectangle (c,d) inside another rectangle (a,b). We know that c>b or d>a so it will not fit horizontally, so we need to check if it will fit diagonally.
Example:

What would be the condition to check if the rectangle (c,d) will fit (a,b) or not.
Thank you in advance,
Comment: You say square, but do you really mean "rectangle"?
Comment: If both sides are larger, it will have a larger surface area, so how can you imbedd the larger rectangle into a smaller one?
Comment: Yes, I meant rectangle (updated)
Both sides are not bigger. Only one of them.
Answer: Let $l=\sqrt{c^2+d^2}$ be the diagonal of the internal rectangle and $\phi=\sin^{-1}\frac{c}{l}=\sin^{-1}\frac{d}{l}$ the angle between the diagonal and a side.
Let $\alpha$ be the angle between $a$ and $c$.
Then the necessary and sufficient conditions for the internal rectangle to be inside the external one are
$$\begin{align}
a & \ge l\sin(\alpha+\phi) \\
b & \ge l\cos(\alpha-\phi)
\end{align}$$
Assume that $a<l$ and $b<l$ - otherwise the corresponding condition disappears and the problem is thus simplified.
The system of inequalities has a solution in $\alpha$ when
$$ \sin^{-1}\frac{a}{l} - \phi \ge \cos^{-1}\frac{b}{l} + \phi $$
which is the condition you are looking for.
Answer: Let $2a\geq2b$ and $2c\geq2d$ be the sidelengths of the two rectangles, and put $f:=\sqrt{c^2+d^2}$.
When $R_{cd}\subset R_{ab}$ can be realized then it can be done with common center $M$.
A necessary condition for such an inclusion is $d\leq b$, because otherwise $R_{cd}$ contains a disk of radius $d>b$, which cannot be covered by $R_{ab}$. If $c\leq a$ as well then $R_{cd}$ can be embedded in $R_{ab}$ with aligned sides.
Therefore it remains to consider the case $c>a\geq b\geq d$ which is shown in the following figure.

The short sides of $R_{cd}\subset R_{ab}$ are tangent to the circle (shown in blue) with radius $c>a$ and center $M$. This circle intersects $R_{ab}$ in four arcs cutting off the vertices of $R_{ab}$. It follows that the two shorter sides of $R_{cd}$ lie in two opposite corner regions of $R_{ab}$. Consider such a side. Its endpoints lie on a similar arc of a circle  with radius $f$ and center $M$. Therefore the  length $2d$ of this side is at most equal to the distance $|PQ|$ in the figure. This means that we have
$$(2d)^2\leq \left(b-\sqrt{f^2-a^2}\right)^2+\left(a-\sqrt{f^2-b^2}\right)^2\ .$$
Expressing $f$ in terms of $c$ and $d$, and simplifying, you obtain the condition you were looking for.


Mongodb over Lustre?

Question: I need to install a mongodb instance with a lot of data storage.
We have a Lustre FS with hundreds of terabytes, but when monogdb start show me this error:
<code>Mon Jul 15 12:06:50.898 [initandlisten] exception in initAndListen: 10310 Unable to lock file: /var/lib/mongodb/mongod.lock. Is a mongod instance already running?, terminating
Mon Jul 15 12:06:50.898 dbexit:
</code>
But the permissions should be fine:
<code># ls -lart /project/mongodb/
total 8
drwxr-xr-x 19 root   root   4096 Jul 15 11:12 ..
-rwxr-xr-x  1 mongod mongod    0 Jul 15 11:54 mongod.lock
drwxr-xr-x  2 mongod mongod 4096 Jul 15 12:10 .
</code>
And no other running process:
<code># ps -fu mongod
UID        PID  PPID  C STIME TTY          TIME CMD
#
</code>
Has anyone done this (Lustre+mongodb)?
Answer: Just delete the existing mongod.lock file and it should take care of everything.
If mongodb doesnt exit gracefully it wont clean this file up when it exits so it thinks something may still be running.
Comment: I have already tried that :(

Mongodb over Lustre?


What was the exact form of Gödel's original Second Incompleteness Theorem?

Question: Gödel's second incompleteness theorem is usually stated as:

Any consistent formal system $F$ capable of elementary arithmetic can't prove its own consistency.

I'm having trouble deducing this statement using just the pieces Gödel had available in 1931. As I understand it those were:

Suppose $G$ is provable. Then this can be converted into a proof of $\neg G$. Hence, $F$ is inconsistent.
Suppose $\neg G$ is provable. Then $F$ "believes" that $G$ can be proven. This doesn't necessarily have to be true. But at the very least $F$ is unsound.

The best I'm able to deduce from this is this:

Any sound formal system $F$ capable of elementary arithmetic can't prove its own consistency.

Take the contrapositive of the first of the previous deductions. Because consistency is a syntactic property this can be fully formalized in $F$ as "$F$ is consistent $\implies$ $\neg G$ is provable". Moreover, there really isn't anything stopping us from actually proving this theorem in $F$. But then, provided $F$ is sound, $F$ can't prove its own consistency. If it could, then using modus ponens it could prove $\neg G$. However, that would make $F$ unsound. $\square$
This is a decidedly weaker version of the second incompleteness theorem. And I don't see how to plug the hole without invoking Rosser's Theorem. Is this all that Gödel had in 1931?
Comment: The condition that the system is consistent is crucial. Otherwise it could prove everything, in particular its own consistency.
Comment: @Peter This only shows "$F$ is inconsistent $\implies$ $F$ can prove it's own consistency". What I want is the other direction: "$F$ can prove it's own consistency $\implies$ $F$ is inconsistent".
Comment: This is of course the hard part. If we assume that $F$ is consistent, then $G$ and $"not\  G"$ cannot be both deduced. This leads to the contradiction you mentioned.
Comment: Goedel showed that , if $F$ is consistent , THEN it cannot prove its own consistency.
Comment: @Peter I still don't see at what point you tightened the reasoning compared to my argument.
Comment: To be honest, I do not understand what you actually ask. My guess was that you want to know what we have in the case that $F$ is inconsistent. It would be helpful , if you clarify your question.
Comment: @Peter I'm asking how Gödel managed to arrive at the conclusion that "$F$ is consistent $\implies$ $G$" is provable in $F$. From what I can tell, he could only establish "$F$ is *sound* $\implies$ $G$". But this  statement involves soundness and can't be formalized.
Answer: The negation of "$G$ is provable" isn't "$\neg G$ is provable". It's "$G$ isn't provable" = $G$. The contrapositive of the first deduction is thus "$F$ is consistent $\implies$ $G$". Now suppose $F$ is consistent and can prove its own consistency. Then $F$ can prove $G$, rendering it inconsistent. ⚡
And all is well.
Comment: I've upvoted since this is correct, but I *strongly* think you should delete the self-deprecation - all this stuff is quite reasonable to find confusing, and for similar readers' sake we should avoid implying that these issues are stupid.


Is it possible to have a case where $D'$ is zero but Logistic Regression is still able to classify accurately?

Question: I want to know if it is possible to construct a problem with following properties:
$M_1$ is $n \times p$ matrix of $n$ observations from Class A
$M_2$ is $n \times p$ matrix of $n$ observations from Class B (I am keeping $n$ same for simplicity but it is not required)
Below function returns a vector of zeros:
D=function(X,Y)
{
    m1=colMeans(X)
    m2=colMeans(Y)
    s1=apply(X,2,sd)
    s2=apply(Y,2,sd)
    return(abs((m1-m2)/(s1+s2)))
}

when called with $X=M_1$ and $Y=M_2$.
However, when logistic regression is run on the data set, it comes up with a classifier that can accurately classify between the two classes. I think its not possible, but wanted to ask. The motivation behind the question is that I was working on a real problem where $D$ values were pretty small (less than 0.1 on average) but the LR classifier was able to score AUC of 0.66 on the training data set.
EDIT: I am posting a follow up question after the answer. Based on the answer, I feel its reasonable to hypothesize that performance of LR should be positively correlated with $D$ - indeed I use $D$ values to decide which features I want to input to LR (feature selection). But recently I came across a problem where this hypothesis seemed to be violated. I cannot post the data, but here are the two cases:
In one case (case 1) my feature vector had $D$ scores given by:
$D = (0.1290, 0.07961, 0.06397, 0.07427, 0.04373, 0.06814)$
as can be seen the values are pretty small but when I ran LR I got AUC of 0.66 and here is the output of LR:
Call:
glm(formula = class ~ ., family = "binomial", data = df)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.6911  -0.3394  -0.2880  -0.2376   2.9908

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.671e+00  3.412e-01 -10.758  < 2e-16 ***
V98          1.671e-04  2.751e-05   6.074 1.25e-09 ***
V99         -5.708e-04  1.296e-04  -4.403 1.07e-05 ***
V100         4.075e-04  8.066e-05   5.051 4.39e-07 ***
V101        -1.084e-03  2.441e-04  -4.442 8.92e-06 ***
V102         6.915e-03  1.510e-03   4.580 4.64e-06 ***
V103        -2.220e-02  5.890e-03  -3.770 0.000163 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1929.8  on 5039  degrees of freedom
Residual deviance: 1852.2  on 5033  degrees of freedom
AIC: 1866.2

Number of Fisher Scoring iterations: 7

Now compare above to case 2 where I have feature vectors with following values of $D$:
$D=(0.0350, 0.1545, 0.0942, 0.0182, 0.2346, 0.3499)$
on average above $D$ values are almost 2x higher than in case 1 but the LR classifier fell flat on its face. Here is its output:
Call:
glm(formula = class ~ ., family = "binomial", data = df)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-0.7968  -0.3597  -0.2762  -0.1380   2.8111

Coefficients:
                 Estimate Std. Error z value Pr(>|z|)
(Intercept)       7.56148    9.79303   0.772  0.44004
energy           -0.09437    0.08758  -1.078  0.28123
entropy           1.19914    2.67011   0.449  0.65336
correlation     173.27758   75.08438   2.308  0.02101 *
sd.energy         0.22770    0.16946   1.344  0.17906
sd.entropy      -15.64633    9.30878  -1.681  0.09280 .
sd.correlation -287.35575  104.54289  -2.749  0.00598 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 192.98  on 503  degrees of freedom
Residual deviance: 173.42  on 497  degrees of freedom
AIC: 187.42

Number of Fisher Scoring iterations: 8

> auc
[1] 0.4585417

So my dilemma is how can above be explained? How come features with low $D$ are able to give better classification than features with higher $D$? and thus if $D$ is not an indicator of a good feature then what metric could be used to determine what features to feed into a LR?
Answer: Your intuition is correct: such an example is impossible.
To see why not, consider both $M_1$ and $M_2$ as collections of $p$-vectors.  Because the predicted value of any vector in a logistic regression is a linear function, perfect prediction means there exists a codimension-$1$ affine hyperspace that separates all the points in $M_1$ from those in $M_2$.  That implies their centroids cannot coincide, QED.

In this figure $p=2$ and the groups have sizes $30$ (red circles) and $10$ (blue triangles). Their centroids are shown as corresponding filled graphics. Perfect separation occurs, as shown by the gray dotted line.  Since the centroids must lie on opposite sides of this line, they cannot coincide.


having problem in importing pandas in jupyter notebook

Question: This is popping up after I run the code import pandas as pd
  NameError                                 Traceback (most recent call last)
    <ipython-input-3-7dd3504c366f> in <module>
    ----> 1 import pandas as pd

c:\users\user\appdata\local\programs\python\python39\lib\site-packages\pandas\__init__.py in <module>
     49 import pandas.core.config_init
     50
---> 51 from pandas.core.api import (
     52     # dtype
     53     Int8Dtype,

c:\users\user\appdata\local\programs\python\python39\lib\site-packages\pandas\core\api.py in <module>
     13

enter code here

     14 from pandas.core.algorithms import factorize, unique, value_counts
---> 15 from pandas.core.arrays import Categorical
     16 from pandas.core.arrays.boolean import BooleanDtype
     17 from pandas.core.arrays.floating import Float32Dtype, Float64Dtype

c:\users\user\appdata\local\programs\python\python39\lib\site-packages\pandas\core\arrays\__init__.py in <module>
      5 )
      6 from pandas.core.arrays.boolean import BooleanArray
----> 7 from pandas.core.arrays.categorical import Categorical
      8 from pandas.core.arrays.datetimes import DatetimeArray
      9 from pandas.core.arrays.floating import FloatingArray

c:\users\user\appdata\local\programs\python\python39\lib\site-packages\pandas\core\arrays\categorical.py in <module>
----> 1 from csv import QUOTE_NONNUMERIC
      2 from functools import partial
      3 import operator
      4 from shutil import get_terminal_size
      5 from typing import Dict, Hashable, List, Sequence, Type, TypeVar, Union, cast

~\OneDrive\Desktop\python\Ardent\csv.py in <module>
   1175   {
   1176    "cell_type": "code",
-> 1177    "execution_count": null,
   1178    "id": "authorized-neighbor",
   1179    "metadata": {},

NameError: name 'null' is not defined

**

Comment: Naming your Python script `csv.py` is dangerous as it shadows the built-in `csv` module. And your `csv.py` script seems to contain JSON. Please re-name that script in `~\OneDrive\Desktop\python\Ardent\csv.py` to something else, and re-run.
Comment: Your csv.py script is the problem (it is invalid), not Pandas.
Comment: Thank you very much. Problem sorted. I wasted my entire day in this stupid problem.
Answer: It seems like you assigned a null value to a key in a dictionary inside csv.py.
Is null a variable?
If you want to assign an "empty"/"null" value in python, you should use None. null is not a type in python.
Answer: You can try like this:
import json
mydict = json.dumps(data)

Whatever data you are converting into dict make sure it should be json.dumps() before print or process otherwise the null will be treated as variable.


Changing Default Environment Setting when starting Visual Studio 2010

Question: Today I installed Visual Studio 2010 on a new machine.
When starting VS2010 for first time, it asked for "Default Environment Window" I selected "Visual C# Development Settings" from it by mistake.

But now i want to change that setting to "Visual Basic Development Settings". How can i do so?
Comment: I would have preferred you ask it the other way (I chose VB by mistake, now want C#). I'll +1 you but this is not an endorsement of VB!
Answer: Simplest way to go, AFAIK, is: Tools -> Import/Export Settings -> Reset All Settings.
Answer: Not sure if you saw this, but it may help:
http://msdn.microsoft.com/en-us/library/ms247075(v=vs.90).aspx
From that page, there's this instruction:

On the Tools menu, click Import and Export Settings.
If you want to delete your current settings combination, choose No,
just reset settings, overwriting my current settings, and then click
Next. This option does not delete default settings, which will still
be available the next time you use the wizard.


Construction of Cantor-like function

Question: I have a countable collection of proper disjoint closed intervals $\mathcal{C} = \left\lbrace I_n\right\rbrace$ in the unit interval $[0,1]$. I want to construct a certain non-decreasing surjective continuous function $f:[0,1]\to [0,1]$ which is locally constant (only) on the above intervals.
More precisely, $f$ is surjective, $t_1 \leq t_2$ should imply $f(t_1)\leq f(t_2)$, and
$$
f(t_1) = f(t_2) \iff t_1, t_2 \in I_n \text{ for some } n.
$$
In general the union of these disjoint intervals can have full measure so I guess I would have to imitate the Cantor function construction? So letting $U_n = [0,1] \setminus \bigcup\limits_{i=1}^n I_n$ be written as a disjoint union of open (in $[0,1]$) intervals $U_n = \bigcup V_j$, my thought was to define
$$f_1(x) = \frac{1}{|V_1| + |V_2|}\int^x_0 \left(1_{V_1}+1_{V_2}\right)
$$
and iterate the process by splitting $V_i$ based on where the next $I_n$ showed up? I'm not sure this works since I'm not convinced there will be some uniform convergence.
Can someone please help me out?
Comment: You could try defining $f$ to be $1/2$ on $I_1$, then either $1/4$ or $3/4$ on $I_2$ depending on whether $I_2$ is to the left or right of $I_1$, and continuing like that. Then imitate the Cantor function for the remaining points, but do linear interpolation if there are any gaps of positive length.
Comment: Not sure I get it; if you do the standard Cantor argument by mapping $I_n$ to some $i/2^m$, then in the case where we have, say $I_1$, away from the rest, wouldn't it spoil the special monotonicity condition above? What do you mean by linear interpolation on 'gaps of positive length'?
Comment: For the part about interpolating on gaps of positive length, what I had in mind was this: if $(a,b)$ is in the complement of the intervals, and we define $\alpha = \sup_{x \leq a} f(x)$, $\beta = \inf_{x \geq b} f(x)$, then we would take $f(x) = \frac{\beta - \alpha}{b - a}(x - a) + \alpha$ on $(a,b)$.
Comment: I do think I see a problem with what I suggested, though, that relates to a situation where there's separation between $I_1$ and the rest of the intervals. Like if $I_1 = [1/8,1/4]$ and $I_n = [1/2+2^{-2n}, 1/2+2^{-(2n-1)}]$ for $n \geq 2$, then the $I_n$ accumulate at $1/2$ and the function would end up being constant on $[1/4,1/2]$ even though this isn't part of the intervals.
Answer: Here's one way of doing this that imitates a sequential approach to defining the Cantor function. Note that we'll write $I_n = [a_n, b_n]$.
We'll also assume for convenience that among the $I_n$ there's no interval of the form $[0, b]$ or $[a, 1]$ in our collection. If one or both is in play, the process below can be adjusted slightly. (We'd want to take all the functions below to be $0$ on $[0, b]$, and $1$ on $[a, 1]$.)
Step 0:
Define $f_0(x) = x$ for all $x \in [0, 1]$.
Step 1:
Define $f_1$ as follows. On $I_1 = [a_1, b_1]$, set $f_1$ equal to the average value of $f_0$ on $I_1$; call this value $y_1$. (Equivalently, this is the value of $f_0$ at the interval midpoint $(a_1 + b_1) / 2$.) Then linearly interpolate between $f_1(0) = f_0(0) = 0$ and $f_1(a_1) = y_1$; and between $f_1(b_1) = y_1$ and $f_1(1) = f_0(1) = 1$.
Step 2:
For $j \geq 2$, define $f_j$ as follows. First locate $I_j$ with respect to $I_1, I_2, \ldots I_{j-1}$: suppose that $I_j$ is immediately to the right of $I_{j_1} = [a_{j_1}, b_{j_1}]$, and immediately to the left of $I_{j_2} = [a_{j_2}, b_{j_2}]$. (If $I_j$ doesn't have a neighbor to one side, we can adjust what follows slightly.) For $x \leq b_{j_1}$ or $x \geq a_{j_2}$, set $f_j(x) = f_{j-1}(x)$. For $x \in I_j$, set $f_j(x)$ equal to the average value of $f_{j-1}$ on $I_j$; call this value $y_j$. (Equivalently, this is the value of $f_{j-1}$ at the interval midpoint $(a_j + b_j) / 2$.) Finally, linearly interpolate between $f_j(b_{j_1}) = f_{j-1}(b_{j_1})$ and $f_j(a_j) = y_j$; and between $f_j(b_j) = y_j$ and $f_j(a_{j_2}) = f_{j-1}(a_{j_2})$.
Step 3:
Define $f(x) = \lim_{j \to \infty} f_j(x)$. I haven't been able to figure out how to show Cauchy convergence of the $f_j$ in the uniform norm, so as to simultaneously establish the existence of the limit and its continuity. But we can definitely prove the pointwise convergence of the $f_j$.

The most complicated part of the pointwise convergence, to my mind, is for a point $x \notin \bigcup I_n$ that is arbitrarily close to these intervals to both the left and right sides. To see how convergence works in this case, we first write $(0, 1) \setminus \left( \bigcup_{j=1}^{k} I_j \right)$ as the union of disjoint open intervals $V_{k,1}, V_{k,2}, \ldots, V_{k, k+1}$; and let $V_{k, \ell_k} = (c_k, d_k)$ be the interval containing $x$. Without loss of generality we can assume that $I_{k+1}$ is contained in $V_{k, \ell_k}$ for every $k$, i.e. that at each step the interval we're "removing" is in the remaining piece where $x$ lives.
Our assumption is now that $s_k = d_k - c_k \to 0$, and it's sufficient to show that $f_k(d_k) - f_k(c_k) \to 0$ as well. Recursively, we have
$$f_k(d_k) - f_k(c_k)
= [ f_{k-1}(d_{k-1}) - f_{k-1}(c_{k-1}) ]
\frac{d_k - c_k + (b_k - a_k) / 2}{d_{k-1} - c_{k-1}},$$
and tracing this back gives the product expansion
$$f_k(d_k) - f_k(c_k)
= \prod_{j=1}^{k}
\frac{d_j - c_j + (b_j - a_j) / 2}{d_{j-1} - c_{j-1}}.$$
Since $b_j - a_j < (d_{j-1} - c_{j-1}) - (d_j - c_j) = s_{j-1} - s_j$, we can estimate
$$f_k(d_k) - f_k(c_k)
\leq \prod_{j=1}^{k}
\frac{s_{j-1} + s_j}{2 s_{j-1}}
= \prod_{j=1}^{k}
\left(
1 - \frac{1}{2} \left( 1 - \frac{s_j}{s_{j-1}} \right)
\right).$$
Meanwhile, the similar-in-form products
$$\prod_{j=1}^{k}
\left(
1 - \left( 1 - \frac{s_j}{s_{j-1}} \right)
\right)$$
simplify to $s_k$, which we know go to $0$.
Letting $r_j = 1 - s_j / s_{j-1} \in (0,1)$, we can reduce things to the following result for series: if $\{ r_j \}$ has values in $(0,1)$, and $\sum \log(1 - r_j)$ diverges, then $\sum \log(1 - r_j/2)$ diverges as well. This is true, for example, because the divergence of the first series implies the divergence of $\sum r_j$, which implies the divergence of $\sum r_j/2$, which implies the divergence of $\sum \log(1 - r_j/2)$.

After all of this, there's still the question of $f$ being continuous and locally constant only on the $I_n$.
Once we know the limit exists, it's evidently a monotonic function since each $f_j$ is, and this helps with the continuity. We can then look at pointwise continuity by breaking things into cases, for example based on whether there are $I_n$ arbitrarily close to the point to one or both sides (i.e. left and right). In some cases, continuity follows from a very similar argument to the one above establishing the existence of the limit.
Being locally constant only on the $I_n$ can be handled by a similar casewise approach. It helps here to recognize that the value of $f$ on each $I_n$ is distinct. (This can be seen inductively.) You can then argue, for example, that at points which have some $I_n$ between them, $f$ takes on distinct values.
Comment: Thanks for the detailed construction.

Construction of Cantor-like function


Inheritance in class object not work and showing type error

Question: class BankAccount:
  def __init__(self):
    self.balance=0

  def withdraw(self,amount):
    self.balance-=amount
    return self.balance

  def deposit(self,amount):
    self.balance=amount+self.balance
    return self.balance

class MinimumBalanceAccount(BankAccount):
    def __init__(self, minimum_balance):
      BankAccount.__init__(self)
      self.minimum_balance = minimum_balance

    def withdraw(self, amount):
      if (self.balance - amount) < (self.minimum_balance):
        print('Sorry, minimum balance must be maintained.')
      else:
        BankAccount.withdraw(self, amount)

a=BankAccount()
a.balance
a.deposit(10)

aa=MinimumBalanceAccount(a)
aa.withdraw(1)

I'm getting the following error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-179-6160646c7f5f> in <module>()
      1 aa=MinimumBalanceAccount(a)
----> 2 aa.withdraw(1)

<ipython-input-168-6b59b3de5e45> in withdraw(self, amount)
      5
      6     def withdraw(self, amount):
----> 7       if (self.balance - amount) < (self.minimum_balance):
      8         print('Sorry, minimum balance must be maintained.')
      9       else:

TypeError: '<' not supported between instances of 'int' and 'BankAccount'

I'm revising the basics of OOP with this piece of code.Anyone can help me clear the error. I'm lost what I'm doing wrong.Why is there a type error?
Comment: `MinimumBalanceAccount(a)` — You're passing an instance of `BankAccount` as the value for `minimum_balance`…!? That should probably be a number instead?!
Comment: @deceze I created an object of Bankaccount and passed that into MinimumBalanceAccount which already has the value balance as 0..okey...I think I got the point.If I had not written created self.minimum_balance  then it would have worked?
Answer:
You have your base class BankAccount which looks fine. You could also let the initializer take a balance and set the default value to 0.
class BankAccount:
  def __init__(self, balance=0):
    self.balance = balance

  def withdraw(self, amount):
    self.balance -= amount
    return self.balance

  def deposit(self, amount):
    self.balance += amount
    return self.balance

There are some issues in your subclass. First, you attempt to initialize it with the class blueprint itself instead of its instance. You can do this by calling the __init__() method of the superclass, which will give you access to all its attributes and methods.
class MinimumBalanceAccount(BankAccount):
    def __init__(self, minimum_balance):
      super().__init__()
      self.minimum_balance = minimum_balance

You decide to override the inherited withdraw() method but try to retain some of its original functionality. Unfortunately, you can't have it both ways, so you will need to re-add that functionality to your overriden method. Note that you can now access balance from the superclass using self.balance.
def withdraw(self, amount):
      difference = self.balance - amount
      if difference < self.minimum_balance:
        print('Sorry, minimum balance must be maintained.')
      else:
        self.balance = difference
      return self.balance

With the implementation of the class outlined as above, the output of your test will then result in the following:
a = MinimumBalanceAccount(0)
a.balance  # -> 0 (by default)
a.deposit(10)  # -> 10
a.withdraw(5)  # -> 5

Edit:
Here is an implementation of the subclass which allows you to also adjust the balance in the superclass. This way, you never actually have to manually instantiate BankAccount anywhere else in your code:
class MinimumBalanceAccount(BankAccount):
    def __init__(self, balance, minimum_balance):
      super().__init__(balance)
      self.minimum_balance = minimum_balance

    def withdraw(self, amount):
      difference = self.balance - amount
      if difference < self.minimum_balance:
        print('Sorry, minimum balance must be maintained.')
      else:
        self.balance = difference
      return self.balance

The output then as follows:
a = MinimumBalanceAccount(balance=100, minimum_balance=0)
a.balance  # -> 100
a.deposit(10)  # -> 110
a.withdraw(5)  # -> 105

Comment: Hi, thank you for this explanation.As I am passing bank account in to the minimum account one, shouldn't the Minimumaccount inherit the values in the class bank account.So, why can't/ how can I pass the value of bankaccount into the MinimumBalanceaccount.
a=BankAccount will create a.balance as zero.
I want to use this for my MinimumBalanceaccount.
Comment: ```
class MinimumBalanceAccount(BankAccount):
    def __init__(self,n):
      BankAccount.__init__(self)
      self.minimum_balance = 0

`````
Comment: How can I inherit the properties of class Bankaccount ?
Comment: I edited the answer to show how you can add the balance attribute to the class. You inherit all properties of the superclass by calling `super.__init__()` in the initializer of the subclass. In your example, you are trying to call a generic class blueprint which happens to be the same type as the superclass, but this is not explicitly coupled and therefore purely coincidental.


Pandas read dataframe from csv with index as string, not int

Question: My csv file is as following :
INDEX, VAL
04016170,22
04206261,11
0420677,11

df = pd.read_csv('data.csv', index_col='INDEX')
How can I force pandas to read the index as string and not as integer (to preserve the first 0) ?
Answer: You can pass the dtype as a param this will map the column to the passed dtype:
In [130]:
import io
import pandas as pd
t="""INDEX,VAL
04016170,22
04206261,11
0420677,11"""
df = pd.read_csv(io.StringIO(t), index_col='VAL', dtype={'INDEX':str})
df

Out[130]:
        INDEX
VAL
22   04016170
11   04206261
11    0420677

In [131]:
df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 3 entries, 22 to 11
Data columns (total 1 columns):
INDEX    3 non-null object
dtypes: object(1)
memory usage: 48.0+ bytes

EDIT
OK, you can do it this way, there is a bug here when you explicitly set the index_col in read_csv, so you have to load the csv in first and then call set_index after loading:
In [134]:
df = pd.read_csv(io.StringIO(t), dtype={'INDEX':str})
df = df.set_index('INDEX')
df

Out[134]:
          VAL
INDEX
04016170   22
04206261   11
0420677    11

Comment: I'm sorry i made a mistake : index_col is INDEX (not VAL), I made the correction asap but you where too fast ! I want INDEX col as the INDEX, and keep the leading 0 in the index
Answer: Another solution in two lines:
df = pd.read_csv('data.csv',index_col=0)
df.index = [str(x) for x in df.index]

or
df.index = df.index.astype(str)


Logarithm sum inequality?

Question: I am going over Durret's probability textbook and one of the proofs uses the inequality
$$\sum_{k=n+1}^\infty \frac{1}{k^2\log k} \leq \frac{1}{n\log n}$$
But, as with much of the textbook, gives no explanation. I was thinking you could take one of the $k$'s out front to and then integrate $1/k\log k$ but that doesn't seem to be of much help.
How can I show this to be true (rather than just take Durret's word for it)?
Comment: Possible duplicate of [How do I prove the following inequality $\sum_{k=n+1}^{\infty}\frac{1}{k^{2}\log k}\leq\frac{1}{n\log n}$?](https://math.stackexchange.com/questions/855324/how-do-i-prove-the-following-inequality-sum-k-n1-infty-frac1k2-log) – found instantly with [Approach0](https://approach0.xyz/search/?q=%24%5Csum_%7Bk%3Dn%2B1%7D%5E%5Cinfty%20%5Cfrac%7B1%7D%7Bk%5E2%5Clog%20k%7D%20%5Cleq%20%5Cfrac%7B1%7D%7Bn%5Clog%20n%7D%24&p=1)
Answer: Use an integral estimate for the series:
$$
\sum_{k=n+1}^{+\infty} \frac{1}{k^2\log k} \leq \int_n^{+\infty} \frac{dx}{x^2\log x} = \int_{\log n}^{+\infty} \frac{dt}{te^t} \leq \frac{1}{\log n} \int_{\log n}^{+\infty} e^{-t}\,dt=\frac{1}{n\log n}.
$$
Comment: We can also do better: $\int_n^{+\infty} \frac{dx}{x^2\log x} \leq \frac{1}{\log n}\int_n^{+\infty} \frac{dx}{x^2}=\frac{1}{n\log n}$.
Comment: Thanks! Very straightforward.

Logarithm sum inequality?


TypeError: load() missing 1 required positional argument: 'Loader' in Google Colab

Question: I am trying to do a regular import in Google Colab.
This import worked up until now.
If I try:
import plotly.express as px

or
import pingouin as pg

I get an error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-86e89bd44552> in <module>()
----> 1 import plotly.express as px

9 frames
/usr/local/lib/python3.7/dist-packages/plotly/express/__init__.py in <module>()
     13     )
     14
---> 15 from ._imshow import imshow
     16 from ._chart_types import (  # noqa: F401
     17     scatter,

/usr/local/lib/python3.7/dist-packages/plotly/express/_imshow.py in <module>()
      9
     10 try:
---> 11     import xarray
     12
     13     xarray_imported = True

/usr/local/lib/python3.7/dist-packages/xarray/__init__.py in <module>()
      1 import pkg_resources
      2
----> 3 from . import testing, tutorial, ufuncs
      4 from .backends.api import (
      5     load_dataarray,

/usr/local/lib/python3.7/dist-packages/xarray/tutorial.py in <module>()
     11 import numpy as np
     12
---> 13 from .backends.api import open_dataset as _open_dataset
     14 from .backends.rasterio_ import open_rasterio as _open_rasterio
     15 from .core.dataarray import DataArray

/usr/local/lib/python3.7/dist-packages/xarray/backends/__init__.py in <module>()
      4 formats. They should not be used directly, but rather through Dataset objects.
      5
----> 6 from .cfgrib_ import CfGribDataStore
      7 from .common import AbstractDataStore, BackendArray, BackendEntrypoint
      8 from .file_manager import CachingFileManager, DummyFileManager, FileManager

/usr/local/lib/python3.7/dist-packages/xarray/backends/cfgrib_.py in <module>()
     14     _normalize_path,
     15 )
---> 16 from .locks import SerializableLock, ensure_lock
     17 from .store import StoreBackendEntrypoint
     18

/usr/local/lib/python3.7/dist-packages/xarray/backends/locks.py in <module>()
     11
     12 try:
---> 13     from dask.distributed import Lock as DistributedLock
     14 except ImportError:
     15     DistributedLock = None

/usr/local/lib/python3.7/dist-packages/dask/distributed.py in <module>()
      1 # flake8: noqa
      2 try:
----> 3     from distributed import *
      4 except ImportError:
      5     msg = (

/usr/local/lib/python3.7/dist-packages/distributed/__init__.py in <module>()
      1 from __future__ import print_function, division, absolute_import
      2
----> 3 from . import config
      4 from dask.config import config
      5 from .actor import Actor, ActorFuture

/usr/local/lib/python3.7/dist-packages/distributed/config.py in <module>()
     18
     19 with open(fn) as f:
---> 20     defaults = yaml.load(f)
     21
     22 dask.config.update_defaults(defaults)

TypeError: load() missing 1 required positional argument: 'Loader'

I think it might be a problem with Google Colab or some basic utility package that has been updated, but I can not find a way to solve it.
Answer: Now, the load() function requires parameter loader=Loader.
If your YAML file contains just simple YAML (str, int, lists), try to use yaml.safe_load() instead of yaml.load().
And If you need FullLoader, you can use yaml.full_load().
Starting from pyyaml>=5.4, it doesn't have any discovered critical vulnerabilities, pyyaml status.
source: https://stackoverflow.com/a/1774043/13755823

yaml.safe_load() should always be preferred unless you explicitly need
the arbitrary object serialization/deserialization provided in order
to avoid introducing the possibility for arbitrary code execution.

More about yaml.load(input) here.
Answer: Found the problem.
I was installing pandas_profiling, and this package updated pyyaml to version 6.0 which is not compatible with the current way Google Colab imports packages.
So just reverting back to pyyaml version 5.4.1 solved the problem.
For more information check versions of pyyaml here.
See this issue and formal answers in GitHub
##################################################################
For reverting back to pyyaml version 5.4.1 in your code, add the next line at the end of your packages installations:
!pip install pyyaml==5.4.1

It is important to put it at the end of the installation, some of the installations will change the pyyaml version.
Comment: You can also just pin this dependency like you would a normal dependency. The resolver will respect it.
Comment: Thanks! Installing pyyaml==5.4.1 fixed my issue & I was able to import plotly.express without any error in my colab file.
Answer: this worked for me
config = yaml.load(ymlfile, Loader=yaml.Loader)

Comment: this should be the best answer, particularly when downgrading pyyaml is not an option.
Answer: The Python "TypeError: load() missing 1 required positional argument: 'Loader'" occurs when we use the yaml.load() method without specifying the Loader keyword argument.
To solve the error, use the yaml.full_load() method instead or explicitly set the Loader keyword arg.
 config = yaml.full_load(ymlfile)

or
config = yaml.load(ymlfile, Loader=yaml.FullLoader)

Answer: pip install pyyaml==3.12

It will work fine for Python 3.10 and you have to update the constructor file also from collections.Hashable to collections.abc.Hashable.


scrapy Error module object has no attribute 'OP_SINGLE_ECDH_USE'

Question: while running scrapy I am getting the following error.
Could someone please let me know which version of scrapy is more stable?
I have referred to the following page and no help so opened a new thread.
scrapy: 'module' object has no attribute 'OP_SINGLE_ECDH_USE'
Error:
    self._options |= SSL.OP_SINGLE_DH_USE | SSL.OP_SINGLE_ECDH_USE
AttributeError: 'module' object has no attribute 'OP_SINGLE_ECDH_USE'
2017-06-09 10:05:54 [scrapy.core.scraper] ERROR: Error downloading <GET https://www.yellowpages.com.au/search/listings?clue=debt+collection+services&eventType=pagination&locationClue=Australia&pageNumber=4&referredBy=www.yellowpages.com.au>

pip freeze:
asn1crypto==0.22.0
attrs==17.2.0
Automat==0.6.0
cffi==1.10.0
constantly==15.1.0
cryptography==1.9
cssselect==1.0.1
enum34==1.1.6
idna==2.5
incremental==17.5.0
ipaddress==1.0.18
lxml==3.8.0
parsel==1.2.0
pkg-resources==0.0.0
pyasn1==0.2.3
pyasn1-modules==0.0.9
pycparser==2.17
PyDispatcher==2.0.5
pyOpenSSL==17.0.0
queuelib==1.4.2
Scrapy==1.4.0
service-identity==17.0.0
six==1.10.0
Twisted==17.1.0
w3lib==1.17.0
zope.interface==4.4.1

There is nothing wrong with the spider code, but I am using scrapy after few months so not sure if something has changed.
Class YellowSpider(Spider):
    name = "yellowpages"
    allowed_domains = ["www.yellowpages.com.au"]
    start_urls = []

    for i in range(1,5):
        start_urls.append("https://www.yellowpages.com.au/search/listings?clue=debt+collection+services&eventType"
                          "=pagination&locationClue=Australia&pageNumber=%s&referredBy=www.yellowpages.com.au"
                          % i)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        item = YellowpagesItem()
        companies = hxs.select("//*[@class='cell in-area-cell middle-cell']")

        for comapny in companies:
            name = hxs.select("//a[@class='listing-name']/text()").extract()

            print name

Comment: Looking at similar threads, usually there is a file path named before the part where you started to copy your error message. See for example [this issue](https://github.com/scrapy/scrapy/issues/2473) on github, where the path clearly shows something is happening within the Twisted package. Maybe review that path, consider upgrading/downgrading the package.
Answer: Thanks, Casper.
moving twisted to 16.4.1 resolved the issue. Posting the answer in case if someone faces the similar issue.


How do I do a case-insensitive mod_rewrite redirect to the same URL (mod case)?

Question: I'm using a case-sensitive web application to serve a few URLs that will be printed, so we expect UsErs to type them with inexact case. How do I tell mod_rewrite to redirect to the correct case URL as in [NC] without also redirecting on the case-exact URL and creating a loop?
Answer: This depends on a few things in your web application, but you could:

Use mod_speling to force the correct capitalization of filenames and directories. This requires "real" filenames.
Use RewriteMap to rewrite the url (as seen here):

In .htaccess:
RewriteEngine on
RewriteBase /
RewriteMap insensitive tolower:
RewriteRule ^[\/]*(.*)$ /${insensitive:$1} [R,L]

Answer: First off, if you can use mod_speling that's easiest, but that requires actual files, not stuff hiding inside an application somehow.
Simply set a condition so the rewriterule doesn't happen if the request is capitalized properly, like so:
RewriteCond %{REQUEST_URI} !^/Your/File$
RewriteRule ^/your/file$ /Your/File [NC,R]

Answer: Mount a Samba share to /var/www
and consider the Samba-share folder your wwwroot ;-))


How do I get immediate parent keys in firebase

Question: So I am trying to get immediate parent keys which are actually children under 'users' database.
Like so, the underlines ones -

My code for the same is as follows -
    databaseReference.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            for( DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                String  user = postSnapshot.getKey();
                list.add(user);

            }

        }

But all it is doing is returning the below image -
Comment: Please log the user.
Comment: On the contrary logged in user does not have to be shown in the list. Rest other users have to be shown. have found something over here but regex is returning weird data https://stackoverflow.com/questions/46949464/how-to-retrieve-parent-key-in-firebase-android
Answer: First your database reference must be like this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");

This is how you read the data:
ValueEventListener listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

    for(DataSnapshot ds: dataSnapshot.getChildren()){
      String  user = ds.getKey();
      list.add(user);

    }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        //log error
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

    }
};
databaseReference.addValueEventListener(listener);

Comment: You have just written same code as mine which is returning username and password like the second image posted in the question
Comment: this is a ValueEvent listener not a child listener.
Comment: and the database reference?
Comment: Sorry I had missed the last line...It worked..thank you..have accepted your answer..


MySQL IFNULL question

Question: I have a query which contains a subquery which is something like this
IFNULL((SELECT id FROM mytable WHERE id = 1), 'No')

It works OK, but I would like to return the string 'Yes' on success rather than the actual id of the row.
Is there any way to override the value it returns?
Thanks.
Answer: IFNULL((SELECT 'Yes' FROM mytable WHERE id = 1), 'No')

Answer: Little Advance example of IFNULL:
Problem: How to get the home phone number if office phone number is not available ?
Solution:
SELECT IFNULL(office_phone_no,home_phone_no) as contact_number
FROM employee_table e
where e.username = 'sumoanand';

MySQL IFNULL question


How to derive this interesting identity for $\log(\sin(x))$

Question: I saw on SE that:
$$\log(\sin x)=-\log(2)-\sum_{n=1}^{\infty}\frac{\cos(2nx)}{n} \phantom{a} (0<x<\pi)$$
This is an extremely useful identity, as it helps solve:
$$\int_{0}^{\pi} \log(\sin(x)) dx$$
But how is it derived? From Taylor series, power series? How do I get this?
Even if someone can start me off that would be great.
Comment: And BTW, $\log\sin$ has elementary primitive: http://es.numberempire.com/integralcalculator.php?function=log%28sin%28x%29%29&var=x.
Comment: @Martín-BlasPérezPinilla What is obvious to one person is not necessarily obvious to other, that's what this is all about.
Comment: @Martín-BlasPérezPinilla It's only elementary if you consider the polylogarithm to be elementary. Not many people do, I think.
Comment: @DanielR, the formula is so long that I have not seen the polylogarithms ah the end! :$
Answer: Hint: Use $~\ln(1-t)~=~-\displaystyle\sum_{n=1}^\infty\frac{t^n}n~$ in conjunction with Euler's formula.


How to theme title field

Question: Normally when I theme a field, I use a template suggestion in format field--fieldname--contenttype.  However, it doesn't seem to be possible to do this with the node title.  I've tried both of the following template suggestions:
field--title--contenttype.tpl.php
field--field-title--contenttype.tpl.php

Neither of them work (I've cleared caches).  The title isn't technically a field, since it's more like a property on the node object, so that may be the problem?
Is there any way to theme the title field?  It feels like I'm missing something simple.
N.b. I'm using panels and have dropped the node title pane into the panel but need to theme it differently.
Comment: http://www.webomelette.com/how-to-theme-fields-drupal-7
Answer: You could use the Title module to convert your title to a proper field. Following that, your template file should work.
Comment: Very cool, I will check it out.
Comment: That worked perfectly, thanks! After converting the title to a field via the manage fields page on the content type, I was able to template the field using `field--title-field--mycontenttype.tpl.php`
Comment: Great to hear, Title is an epic module!
Answer: Why not just edit the css file?
    #content h1 {
      color: blue;
    }
Something like this.
Node title is wrapped in content div and it is  or
You may check your page.tpl.php
Comment: I need to change the HTML structure as oppose to just the colour

How to theme title field


How to make the image scale to full height in Bootstrap - Carousel?

Question: I am trying to show an image that should fill up the entire screen in Bootstrap Carousel control. I am using an image with 1024px*795px
I am using the example given on Bootstrap site with full size image. Horizontally, it fills up the screen very well. But vertically it does not scale well. What properties should I add / delete so that the images fill up the entire screen, though they have smaller pixel sizes?
How can I do it in responsive designs as well, so that the images scale any size?
I am using the css as it is on the example site and only changing CSS in carousel.html.
Answer: 2019 Updated Answer for Bootstrap 4.x
Since modern browsers now support object-fit, there are better options as explained here.
Original Answer for Bootstrap 3.x
I realize this answer is a little late, but I also faced a similar challenge with the Bootstrap carousel. In order for the 100% height to work, the carousel and any of its' parent containers must also be 100% height.
I added some overrides to the Bootstrap CSS classes:
html,body{height:100%;}
.carousel,.item,.active{height:100%;}
.carousel-inner{height:100%;}
.fill{width:100%;height:100%;background-position:center;background-size:cover;}

And then add the "fill" class accordingly to your carousel:

Slide 1

Slide 2

    ‹
    ›

Here is a working example: http://bootply.com/59900


Network Interface naming conflict ubuntu

Question: I recently changed which interfaces are members of my NIC bond. The first ubuntu server I made the adjustments on worked fine, but my second one has ran into issues. Ifconfig is showing a "rename2" interface present. How can I get this all straitened out?
Looking at the output of the udev rule, I want "eth2" and "eth0" to be members of the bond.
EDIT:
Okay Matt's fix below fixes this problem temporally. It returns a few reboots later and I have to repeat the process! Any ideas?
Here is /etc/udev/rules.d/70-persistant-net.rules file
# This file was automatically generated by the /lib/udev/write_net_rules
# program, run by the persistent-net-generator.rules rules file.
#
# You can modify it, as long as you keep each rule on a single
# line, and change only the value of the NAME= key.

# PCI device 0x10ec:/sys/devices/pci0000:00/0000:00:1c.0/0000:01:00.0 (r8169)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="a0:f3:c1:00:a0:7a", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"

# PCI device 0x8086:/sys/devices/pci0000:00/0000:00:1c.4/0000:02:00.0 (e1000e)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:25:90:99:13:0c", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"

# PCI device 0x8086:/sys/devices/pci0000:00/0000:00:1c.5/0000:03:00.0 (e1000e)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="00:25:90:99:13:0d", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth2"

My /etc/network/interfaces
#loopback network interface
auto lo
iface lo inet loopback

# The primary network interface

auto eth2
iface eth2 inet manual
bond-master bond0

auto eth1
iface eth1 inet static
address 10.1.10.199
netmask 255.255.255.0
gateway 10.1.10.1
dns-nameservers 220.127.116.11 18.104.22.168

auto eth0
iface eth0 inet manual
bond-master bond0

auto bond0
iface bond0 inet static
address 192.168.1.2
netmask 255.255.255.0
#bond mode 0 is rr
bond-mode balance-rr
bond-miimon 100
bond-slaves none
mtu 9000

ifconfig -a
bond0     Link encap:Ethernet  HWaddr 00:25:90:99:13:0d
          inet addr:192.168.1.2  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::225:90ff:fe99:130d/64 Scope:Link
          UP BROADCAST RUNNING MASTER MULTICAST  MTU:9000  Metric:1
          RX packets:5236 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3265 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:782916 (782.9 KB)  TX bytes:395078 (395.0 KB)

eth1      Link encap:Ethernet  HWaddr 00:25:90:99:13:0c
          inet addr:10.1.10.199  Bcast:10.1.10.255  Mask:255.255.255.0
          inet6 addr: fe80::225:90ff:fe99:130c/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:10277 errors:0 dropped:415 overruns:0 frame:0
          TX packets:4073 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1384868 (1.3 MB)  TX bytes:540020 (540.0 KB)
          Interrupt:16 Memory:fe9e0000-fea00000

eth2      Link encap:Ethernet  HWaddr 00:25:90:99:13:0d
          UP BROADCAST RUNNING SLAVE MULTICAST  MTU:9000  Metric:1
          RX packets:5236 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3265 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:782916 (782.9 KB)  TX bytes:395078 (395.0 KB)
          Interrupt:17 Memory:feae0000-feb00000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:123 errors:0 dropped:0 overruns:0 frame:0
          TX packets:123 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:12570 (12.5 KB)  TX bytes:12570 (12.5 KB)

rename2   Link encap:Ethernet  HWaddr 00:25:90:99:13:0c
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

cat /var/log/syslog | grep -i eth
Feb 27 14:42:42 emtestserver2 kernel: [    1.707645] r8169 Gigabit Ethernet driver 2.3LK-NAPI loaded
Feb 27 14:42:42 emtestserver2 kernel: [    1.708359] r8169 0000:01:00.0: eth0: RTL8168e/8111e at 0xf8410000, 00:25:90:99:13:0c, XID 0c200000 IRQ 43
Feb 27 14:42:42 emtestserver2 kernel: [    1.708390] r8169 0000:01:00.0: eth0: jumbo features [frames: 9200 bytes, tx checksumming: ko]
Feb 27 14:42:42 emtestserver2 kernel: [    1.835800] e1000e 0000:02:00.0: eth1: (PCI Express:2.5GT/s:Width x1) 00:25:90:99:13:0c
Feb 27 14:42:42 emtestserver2 kernel: [    1.835830] e1000e 0000:02:00.0: eth1: Intel(R) PRO/1000 Network Connection
Feb 27 14:42:42 emtestserver2 kernel: [    1.835935] e1000e 0000:02:00.0: eth1: MAC: 3, PHY: 8, PBA No: 0101FF-0FF
Feb 27 14:42:42 emtestserver2 kernel: [    1.943729] e1000e 0000:03:00.0: eth2: (PCI Express:2.5GT/s:Width x1) 00:25:90:99:13:0d
Feb 27 14:42:42 emtestserver2 kernel: [    1.943759] e1000e 0000:03:00.0: eth2: Intel(R) PRO/1000 Network Connection
Feb 27 14:42:42 emtestserver2 kernel: [    1.943863] e1000e 0000:03:00.0: eth2: MAC: 3, PHY: 8, PBA No: 0101FF-0FF
Feb 27 14:42:42 emtestserver2 kernel: [    8.009312] IPv6: ADDRCONF(NETDEV_UP): eth0: link is not ready
Feb 27 14:42:42 emtestserver2 kernel: [    8.009330] IPv6: ADDRCONF(NETDEV_UP): eth1: link is not ready
Feb 27 14:42:42 emtestserver2 kernel: [    8.009345] IPv6: ADDRCONF(NETDEV_UP): eth2: link is not ready
Feb 27 14:42:42 emtestserver2 kernel: [    8.090179] bonding: Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)
Feb 27 14:42:42 emtestserver2 kernel: [    8.505554] IPv6: ADDRCONF(NETDEV_UP): eth1: link is not ready
Feb 27 14:42:42 emtestserver2 kernel: [   10.229052] e1000e: eth1 NIC Link is Up 100 Mbps Full Duplex, Flow Control: None
Feb 27 14:42:42 emtestserver2 kernel: [   10.229064] e1000e 0000:02:00.0: eth1: 10/100 speed: disabling TSO
Feb 27 14:42:42 emtestserver2 kernel: [   10.229637] IPv6: ADDRCONF(NETDEV_CHANGE): eth1: link becomes ready
Feb 27 14:44:10 emtestserver2 udevd[399]: error changing net interface name rename2 to eth1: File exists
Feb 27 14:51:45 emtestserver2 kernel: [    1.726543] r8169 Gigabit Ethernet driver 2.3LK-NAPI loaded
Feb 27 14:51:45 emtestserver2 kernel: [    1.727347] r8169 0000:01:00.0: eth0: RTL8168e/8111e at 0xf8422000, 00:25:90:99:13:0c, XID 0c200000 IRQ 46
Feb 27 14:51:45 emtestserver2 kernel: [    1.727377] r8169 0000:01:00.0: eth0: jumbo features [frames: 9200 bytes, tx checksumming: ko]
Feb 27 14:51:45 emtestserver2 kernel: [    1.835779] e1000e 0000:02:00.0: eth1: (PCI Express:2.5GT/s:Width x1) 00:25:90:99:13:0c
Feb 27 14:51:45 emtestserver2 kernel: [    1.835809] e1000e 0000:02:00.0: eth1: Intel(R) PRO/1000 Network Connection
Feb 27 14:51:45 emtestserver2 kernel: [    1.835914] e1000e 0000:02:00.0: eth1: MAC: 3, PHY: 8, PBA No: 0101FF-0FF
Feb 27 14:51:45 emtestserver2 kernel: [    1.947925] e1000e 0000:03:00.0: eth2: (PCI Express:2.5GT/s:Width x1) 00:25:90:99:13:0d
Feb 27 14:51:45 emtestserver2 kernel: [    1.947957] e1000e 0000:03:00.0: eth2: Intel(R) PRO/1000 Network Connection
Feb 27 14:51:45 emtestserver2 kernel: [    1.948088] e1000e 0000:03:00.0: eth2: MAC: 3, PHY: 8, PBA No: 0101FF-0FF
Feb 27 14:51:45 emtestserver2 kernel: [    7.896332] IPv6: ADDRCONF(NETDEV_UP): eth0: link is not ready
Feb 27 14:51:45 emtestserver2 kernel: [    7.896349] IPv6: ADDRCONF(NETDEV_UP): eth1: link is not ready
Feb 27 14:51:45 emtestserver2 kernel: [    7.896363] IPv6: ADDRCONF(NETDEV_UP): eth2: link is not ready
Feb 27 14:51:45 emtestserver2 kernel: [    8.030196] bonding: Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)
Feb 27 14:51:45 emtestserver2 kernel: [    8.257699] IPv6: ADDRCONF(NETDEV_UP): eth1: link is not ready
Feb 27 14:51:45 emtestserver2 kernel: [    8.877181] bonding: bond0: Adding slave eth2.
Feb 27 14:51:45 emtestserver2 kernel: [    8.953427] bonding: bond0: enslaving eth2 as an active interface with a down link.
Feb 27 14:51:45 emtestserver2 kernel: [    9.028338] e1000e 0000:03:00.0: eth2: changing MTU from 1500 to 9000
Feb 27 14:51:45 emtestserver2 kernel: [   10.013072] e1000e: eth1 NIC Link is Up 100 Mbps Full Duplex, Flow Control: None
Feb 27 14:51:45 emtestserver2 kernel: [   10.013088] e1000e 0000:02:00.0: eth1: 10/100 speed: disabling TSO
Feb 27 14:51:45 emtestserver2 kernel: [   10.013786] IPv6: ADDRCONF(NETDEV_CHANGE): eth1: link becomes ready
Feb 27 14:51:47 emtestserver2 kernel: [   11.741054] e1000e: eth2 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: Rx/Tx
Feb 27 14:51:47 emtestserver2 kernel: [   11.780038] bonding: bond0: link status definitely up for interface eth2, 1000 Mbps full duplex.
Feb 27 14:53:13 emtestserver2 udevd[411]: error changing net interface name rename2 to eth1: File exists
Feb 27 14:53:13 emtestserver2 kernel: [   98.504821] bonding: bond0: Interface eth0 does not exist!

Comment: If you could post the dmesg output for the NIC detection parts that may help.  From memory the rename stuff is all related to whats in the 70-persistent-net.rules file.
Comment: Alright one sec, Matt.
Comment: the syslog had more material
Answer: Backup the file 70-persistent-net.rules.
Then clear it out 70-persistent-net.rules so that it has no entries in it.
Reboot.
After reboot verify it's now looking normal.
As I recall if the persistent-net rules has any issues like mac addresses different, it'll create those rename adapters.  I did have something like this happen a few months back and clearing this file helped.
Also on my systems where bonding is working, I list the bond interface first like this.
Not sure if that would make things work better for you or not.
auto bond0
iface bond0 inet static
  address 192.168.1.2
  network 192.168.1.0
  netmask 255.255.255.0
  bond-slaves none
  bond-mode 4
  bond-mmimon 100
  bond-lacp-rate 1

auto eth0
iface eth0 inet manual
  bond-master bond0
  bond-primary eth0 eth1

auto eth1
iface eth1 inet manual
  bond-master bond0
  bond-primary eth0 eth1

Comment: Removing the udev rule fixed it. I didn't know if I could remove it. ;) Thanks! I will also edit my interfaces file just incase.
Comment: I believe that file is created if it doesn't exist.  It just means that if you swap NIC's cards around in PCI slots or remove one or add another card etc etc... it guarantees that once assigned eth0 will always belong to a particular device with a particular mac address etc.  You could imagine the chaos if the device names changed in a firewall if you need to add another ethernet card.  It is a slight annoyance if you have a portable hard drive that you carry around and plug into different computers.  The device names will keep changing.
Comment: Matt, it's constantly doing this now. If I fix it, then it's back in a few reboots and its killing my DRBD configuration. Any ideas?? This all started after changing the bonding configuration several times.


Switching from Acoustic Classical Guitar to Electric Guitar

Question: I have played a classical guitar for a while and bought an electric guitar very recently. Since there are some differences in the two guitars I find it somewhat difficult to adapt to the electric guitar.
The space between the strings are different (lesser in electric) and when picking I seem to miss the string
The high E string is a bit lower and very thinner than the other strings (in electric) and this also makes me miss the string when picking
I find it difficult to rest my picking hand on the body difficult with the electric
When picking from lower strings to higher strings, my thumb (of my picking hand) touches the higher strings muting them (in classical guitar I used finger picking). So I'm finding it difficult to let the lower notes ring. Is this normal when playing electric guitar or is it something wrong with my picking technique?
And finally, is it possible to play both forms of the guitar and be good at both? I'm asking since the two are different and being better at one might mean sacrificing the familiarity with the other.
Answer: Switching from classical guitar to electric is going to take some time and practice.  While you may be familiar with playing a nylon-stringed guitar, not all of those skills will transfer over easily or quickly to an electric.  The best advice I can give you is simple: give it time, and keep practicing.  It's not quite the same as learning the guitar from scratch, but you will have to adapt your playing style to accommodate the differences in string spacing and picking styles.
As far as some of the specific concerns you mentioned, the best thing to do would be to talk to an experienced electric guitar player or a teacher who can give you some feedback on your technique and what you might be doing wrong.  I can give you some general advice, but playing with someone in person will go a lot farther and prevent you from forming bad habits.
The string spacing is just something that takes time to get used to. You will continue to miss the strings sometimes and pick the wrong ones until you get the muscle memory down that is required when playing electric guitar with a pick.  It might help if you play fingerstyle some of the time on your electric, that way you can use the familiarity of something you do know, and focus on adapting to the different string spacing rather than learning a new picking method at the same time.
When using a pick, you shouldn't be touching the strings with your right hand thumb at all really, except when muting. In between chords or in quiet sections you can rest your thumb or the side of your palm against the strings to mute them, but when you are actually picking your thumb shouldn't really come in contact with the strings. Sometimes when picking higher strings, you can rest your thumb (specifically the fleshy part of where your thumb meets the palm) on the lower strings to mute them intentionally.  On an amplified electric, you need to be more aware of strings ringing when you don't want them to, so when playing notes on higher strings you usually adjust your technique to mute the lower strings with either your right hand like I mentioned or with the extra fingers on your left hand.  This is how a lot of guitarists can get away with just strumming all the strings all the time, and only picking out the notes they want to play and muting the other strings with left or right hand technique. Of course if you don't want to mute the strings, you just need to adjust your hand position and how you are holding the pick to make sure you don't touch the strings that are ringing.
As far as resting your picking hand on the body, I'm pretty sure that will also get more comfortable over time. I like Strat style guitars in particular because they are very comfortable to rest the forearm on while playing; some other electric guitar body-types aren't quite as accommodating.  That is mostly just personal preference, but it will also get easier for you with more practice.  Again, you are learning a new instrument- it's not going to be 100% comfortable right off the bat. This is another area where playing with someone more experienced that you will be helpful, as they can tell you if you are doing something wrong or if it's just uncomfortable because you aren't used to it yet.
I believe it is possible to play both electric and classical guitar well. It will just take practice, like anything else. If you want to stay good at both, obviously you shouldn't neglect your classical playing while you are learning electric, and be sure to continue practicing both. Metal guitar especially borrows a lot from classical styles in technique and playing style, and there are some great guitarists out there from all genres that have made the very same transition.
Answer: Picking style on an electric guitar is entirely different.  You use a pick rather than your fingernails (there is no way the nails will survive the razor-blade-like higher strings for any useful amount of time).
There are fingerpicks with sort-of mounts which you stick on individual fingers, but I don't think I've seen then in any serious use.  Instead, people use a straight pick grabbed with thumb and index finger, possibly also middle.
That takes some getting used to, like playing the piano with one finger when you are used to all.
Comment: Those fingerpicks are more popular for acoustic guitar, but on electric there are plenty of players that use their thumb/fingers to great effect- no plastic needed. (See [Mark Knopfler](https://www.youtube.com/watch?v=gf4bwFyaL90) or [Jeff Beck](https://www.youtube.com/watch?v=iv4RuGP2GEk).. of course they don't use proper classical technique, but its probably closer to what OP is used to). Still worth it to learn how to use a pick, but you can do without it too.
Comment: Finger picking electric guitarrists who worship Merle Travis and Chet Atkins will be slamming this answer in 10... 9... 8... 7...
Comment: ... or Joe Pass, or Martin Taylor, etc., etc.