Let's Encrypt certifcate for MS CRM using IIS

Question: I am installing an instance of MS CRM 2015 on-premise, on a Win 2012 R2 Server, IIS 8.5.
I would like to use the Let's Encrypt service to generate certificates for crm.example.com on this server.
Let's Encrypt would like to use the .well-known/acme-challenge directory for validation. MS CRM has taken over the Default website and redirects requests to its website folder, using Windows authentication.
Is there a way to whitelist the .well-known/acme-challenge folder within the CRM website, so as to avoid authentication?
I have tried adding a location section in the web.config, but IIS throws an error because the path starts with a dot.
https://stackoverflow.com/questions/10351075/allow-anonymous-authentication-for-a-single-folder-in-web-config
I have tried adding a handler to solve that problem, as in:
https://stackoverflow.com/questions/11728846/dots-in-url-causes-404-with-asp-net-mvc-and-iis
but I get the same error there.
As an alternative, Let's Encrypt can be validated using DNS, but I am not really up to that, and I can't find evidence that my provider has an API for that purpose.
Do I have any other options?
Comment: "*so as to avoid authentication?*" you mean "to avoid redirection", right?
Comment: Have you tried using `` in ApplicationHost.config rather than web.config, that seem to work for me
Comment: @Peter, good suggestion. I can change the authentication settings from `` in ApplicatonHost.config (beware editing with 32 bit editor). I still get a 401 for extensionless files.
Comment: @techraf, I am learning something of the innards of CRM, but I am not too sure about the actual page serving and authentication sequence. What I know is that the default response for the site is to show an authentication pop-up that I don't want for the ACME challenge.
Answer: Thanks to @Peter Hahndorf for the workaround, to @benadams letsencrypt fixes for IIS for the syntax, and to @Mike Ratcliffe (editing ApplicatonHost.config)
If you want Let's Encrypt to write to a ./well-known subfolder of CRM website, create the subfolder first and the change the configuration as follows.
Edit the  ApplicationHost.config (the main IIS config fil), mine was under  Windows/System32/inetsrv/config. If you are running a 64-bit edition of Windows, you must use a 64-bit editor (I used Windows Notepad).
I added/changed the following lines in the <location path="Microsoft Dynamics CRM/.well-known"> section.
<system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <staticContent>
          <mimeMap fileExtension=".*" mimeType="text/plain" />
          <mimeMap fileExtension="." mimeType="text/plain" />
        </staticContent>
        <handlers>
            <clear />
            <add name="StaticFile" path="*" verb="*" type=""    modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" scriptProcessor="" resourceType="Either" requireAccess="Read" allowPathInfo="false" preCondition="" responseBufferLimit="4194304" />
        </handlers>
            <security>
                <authentication>
                    <anonymousAuthentication enabled="true" />
                </authentication>
            </security>
        </system.webServer>

This allows anonymous authentication and any user access to a path starting with a dot, under the CRM default website.
With this setup I could request a certificate using letsencrypt-win-simple
PowerShell script.


how to find iso-cost contours on a 2d plot efficiently

Question: Consider a 2D plot in which dimension 1 and 2 represent quantity 1 and 2 respectively ranging over 0 to 100. Each point in the space corresponding to (x,y) represent cost of choosing quantity 1 as x and quantity 2 as y. Assume cost increases monotonically with increase in quantities. I want to find iso-cost lines(contours) in the space. Say all those points whose cost is equal to some K. How do I find it efficiently without checking cost of all the points in the space which is 100 cross 100.?
Answer: It is an optimization-problem. It can be solved with the lagrangian-method.
$min \ \ L=K(x,y)-\lambda(100-x-y)$
Now calculate the following derivations and set them all zero:
$\frac{\partial L}{\partial x  }=0,\frac{\partial L}{\partial y }=0,\frac{\partial L}{\partial \lambda }=0$
Then solve the system of 3 variables and 3 equations.
greetings,
calculus
Comment: thanks for your reply..how did u get this term               −λ(100−x−y)
Comment: It is the constraint, which says, that the sum of two quantities, x and y, must be 100. It could be for example x=30 and y=70. But the concrete values are determinated by the optimization. I hope I have understood  the situation right.
Comment: there is no constraint like that. x can be say 65 and y can be 70, f(x,y) can be some K. Also we only know that cost increases monotonically wrt quantities
Comment: O.K. You can first assume a cost funktion like this: $K=x^a\cdot y^b$ with $ a,b \geq 0$ Solve it for y and assume for $a,b$ and $K$ concrete values. The budget line is in general $x+y=c, \forall x,y \leq 100$. Just draw some budget lines which touches some iso-cost lines (curves). Only one budget line for one iso-cost line.
Comment: kindly check out this link                                                   http://math.stackexchange.com/questions/845641/how-to-find-iso-function-value-points-without-exploring-all-points-in-2d-space
Answer: The magic words are Marching Squares.
Basically, you walk through all the vertices in your mesh marking 0 if below threshold, 1 if above.  Then for each rectangle you have four bits determining if the points are above/below threshold.  These bits form an index (0-15) with which you can look up a set of contour line segments for each square.  Accumulating all the contour segments for all the squares yields the contour plot.  You probably want to linearly interpolate the location of the segment endpoints rather than just setting the location at the midpoint of the edge.


Creating a reusable component reactjs

Question: I read an article that creating small reusable components decreases the file size, makes unit testing faster and easier and a lot more. So I'm now trying to create one, however I am very new to reactjs and I'm maintaining this project for a friend, so I haven't written all the code.
Heres a code snippet:
class ObjectKeyDisplay extends Component {
  constructor(props) {
    super(props)
    this.state = { open: false } // Sets open to false (closed)
  }

  renderInner() {
    const { schema, parentDocumentId, collectionName, value } = this.props
    const { open } = this.state // equals const open = this.state.open

    let expandButton
    if (schema.type === 'belongs_to') {
      expandButton = (
        <button onClick={e => this.setState({ open: !open })}> // Sets it to true (opened)
          {open ? 'Minimera' : 'Expandera'}
        </button>
      )
    }

So I basically want to make the whole open/close process to a component, so I easily reuse the logic for other buttons. I would really appreciate if someone could help me out here!
Comment: You are missing code I guess. But I guess if you are looking for reusability of functionality you should take a deeper look into the Higher Order Component Pattern
Answer: Here's a working example.
Move the button into it's own component where it can control it's own open state. Also, it'd be a good idea to provide some callbacks when the state changes that can be used in the parent component. There are multiple ways of conditionally rendering the button contents. What I've done here is pass in an array of children and if open is true, then render the first child in the array.
class Main extends React.Component {
    render(){
    return (

        Expand button
        <ExpandButton onOpen={() => console.log('opened')} onClose={() => console.log('closed')} >

Open

Close

        </ExpandButton>

    )
  }
}
class ExpandButton extends React.Component {
    constructor(){
    super();
    this.toggleOpen = this.toggleOpen.bind(this);
    this.state = {
        open: false
    }
  }
  toggleOpen(){
    this.setState({
        open: !this.state.open
    }, () => {
        // Trigger callbacks
        if(this.state.open){
        this.props.onOpen();
      }else{
        this.props.onClose();
      }
    })
  }
    render(){
    const { open } = this.state;
    return (
        <button onClick={this.toggleOpen}>
        {open ? this.props.children[0] : this.props.children[1]}
      </button>
    )
  }
}
React.render(, document.getElementById('container'));

Creating a reusable component reactjs


Using k-means for reducing the size of the training set of a Kernel SVM

Question: I have a classification problem with the following characteristics:

a few million data points
around one hundred features
non-linearly separable
Training a SVM with an RBF Kernel is not feasible because of the size of the data set.

My idea is the following:

reduce the size of the data set to a few thousand points by applying K-Means clustering
transform the data set by replacing all the features with the the similarities between the original points and the centroids of the clusters
train a linear SVM on the new dataset

Does this approach sound reasonable from a mathematical perspective?
What other classification algorithms do you recommend for large data sets that are not linearly separable?
Comment: What you are asking is [dimensionality reduction](http://stats.stackexchange.com/questions/tagged/dimensionality-reduction), so I recommend reviewing the Q&A tagged like this. Commonly PCA/SVD are used for dimensionality reduction - why aren't you considering those methods?
Comment: Btw, I removed `kernel` tag and added `dimensionality-reduction` tag to your question since it appears more relevant.
Answer: To answer your second question, classification trees/random forests are probably a good way to go, and are usually a worthwhile tool for exploratory analysis.
As far as your approach, depending on the data, you could try just running your algorithm on a few independent samples from the data set, where the sample size is a function of the running time of your classification.
Taking multiple samples has the additional benefit of being able to quantify the variability of the classifier (This is bootstrapping in a sense but a bit more classical).
As has been stated by other's, and what I tried to elude to with "depending on the data"; if you have lot's of variables, more than likely you have lot's of variables that are correlated in some respect with each other.  PCA may be one option, but interpretability of the classification may be problematic.  Bagging, in particular with random forests as suggested by (@aginensky) can also be useful in addressing the issue of dimension reduction, or at least help ensure you are not overfitting your tree.
Comment: To amplify on the answer above, if you run a random Forest, you can (with most software packages) extract variable importance. That my solve your variable reduction problem.
Answer: This is a good strategy provided that you tune the number of clusters. I would suggest you the Sculley's paper "Detecting Adversarial Advertisements in the Wild". The paper is remarkable when it comes to practical machine learning and how to deal with large datasets. It addresses also the issues of scale, class inbalance, different misclassification costs and advices on building more complex models from basic linear classifiers.
Comment: The paper extremely good, but right now I am more in the phase of building a proof of concept rather than a fully fledged system. Thanks a lot for the link, I saved it for future reference.


Code not compiling in javascript

Question: I don't write in javascript but my friend asked me if I can help him with one kata (https://www.codewars.com/kata/ascii-fun-number-1-x-shape/)
I gave him this code, but i have no idea why it's not working, I'm totally newbie in javascript, can someone tell me what I did wrong :D?
Error message:
The server timed out waiting for the code to finish executing. It is possible that this is due to high server load. It may also be caused by inefficent code. Please try your request again.
function x(n)
{
  printlines(n);
  print("\n");
  for(column = 0; column < n; column++)
  {
    if(column = 1)
    {
      print("■");
    }
    else
    {
      print("□");
    }
  }
  print("\n");
  printlines(n);
}

function print(n)
{
  console.log(n);
}

function printlines(n)
{
  i = 1;
  for(line = 0; line < 1; line++)
  {
    for(column = 0; column < n; column++)
    {
      if(column = line)
      {
        print("■");
      }
      else if( column = n - 1)
      {
        print("■");
      }
      else
      {
        print("□");
      }
     }
     print("\n");
     i++;
  }
}

Comment: JavaScript is not a compiled language. Are you trying to execute the code and fails, or does it fail to produce the right answer? Can you provide a little more information regarding the problem that you are facing?
Comment: _"can someone tell me what I did wrong"_ - didn't you say that yourself already? You are trying to "help" someone with something you do not have the first clue about yourself. No how's that supposed to work, I wonder?
Comment: Error message: The server timed out waiting for the code to finish executing. It is possible that this is due to high server load. It may also be caused by inefficent code. Please try your request again
Answer: You have to add var column to declare it ( same in i and line )  in your loop for , and in your if u have to write == instead of = (== to test equality )
Comment: Now it says "Failed to process output. It is possible that too much data was written to STDOUT."
Comment: Are you executing `x(n)` ?  And which value u give to n ? Simply : which function do you execute ?
Answer: I like to use http://jslint.com to help me validate my JavaScript. But right off of the bat, I can tell you that you need to declare the vars that you are using to iterate in your for loops and in JavaScript you use "==" or "===" for comparison.
Hopefully this gets you on the right track.

Code not compiling in javascript


Boostrap nested row only works above columns not below

Question: I want a row with 7 columns taking up 100% of the width then nested in that row on the next line I want 1 column also taking up 100% of the width.
https://jsfiddle.net/DTcHh/27598/ The message column is in the wrong place completely.
https://jsfiddle.net/w37vs3wr/1/ the message column is the right size but the wrong place. I want to make it exactly like this but below the other columns not above them.

Result

Start

Duration

Test Case

Total Data Items Generated

Type

Username

Message

Answer: The solution is to make a row that you divide in 7 and a second row with a column taking the all space.

Result

Start

Duration

Test Case

Total Data Items Generated

Type

Username

Message

Example: https://jsfiddle.net/DTcHh/27601/
Note: the background color is just to ensure that the Message take the full width
Comment: You can also wrap the entire snippet into a row


Devise user sign up form with business model

Question: I'm trying to create a user sign up form with Devise that will also allow for the creation of a new business associated with that user.
I have a business model setup and can't seem to save the business information to the database. Below is my code, I'm fairly new to rails so I apologize if I'm asking a question with an obvious answer.
new.html.erb (user)

Sign Up

        <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
            <%= devise_error_messages! %>

                Name
                <%= f.text_field :username, :autofocus => true, :class => "form-control", :placeholder => "Full Name" %>

                <%= f.label :email %>
                <%= f.text_field :email, :class => "form-control", :placeholder => "Email" %>

                <%= f.label :password %>
                <%= f.password_field :password, :class => "form-control", :placeholder => "Password" %>

Passwords must be a minimum of 8 characters.

                <%= f.label :password_confirmation %>
                <%= f.password_field :password_confirmation, :class => "form-control", :placeholder => "Retype Password" %>

Business Information

            <%= f.fields_for :business do |b| %>

                    <%= b.label :name %>
                    <%= b.text_field :name, :class => "form-control", :placeholder => "Business Name" %>

                    <%= b.label :address %>
                    <%= b.text_field :address, :class => "form-control", :placeholder => "Address" %>

                            <%= b.label :city %>
                            <%= b.text_field :city, :class => "form-control", :placeholder => "City" %>

                            <%= b.label :state %>
                            <%= b.text_field :state, :class => "form-control", :placeholder => "State" %>

                            <%= b.label :zip %>
                            <%= b.text_field :zip, :class => "form-control", :placeholder => "ZIP" %>

                    <%= b.label :country %>
                    <%= b.text_field :country, :class => "form-control", :placeholder => "Country" %>

            <% end %>

                <%= f.submit "Sign Up", :class => "btn btn-primary" %>

        <% end %>

user.rb
class User

include Mongoid::Document
  include Mongoid::Paperclip
  rolify
  include Mongoid::Timestamps

  #embeds_many :businesses, :class_name => "Business"

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :role_ids, :as => :admin
  attr_accessible :username, :email, :password, :password_confirmation, :remember_me, :business_ids,
  :reset_password_sent_at, :reset_password_within, :address, :city, :state, :zip, :country, :phone, :business_attributes

  has_one :businesses
  accepts_nested_attributes_for :businesses

  validates_format_of :email, :with=>email_regexp, :allow_blank => true, :message=> "Justin"

  #intercom
  attr_accessor :company_name
  attr_accessible :company_name

  ## Database authenticatable
  field :email,              :type => String, :default => ""
  field :encrypted_password, :type => String, :default => ""

  ## Recoverable
  field :reset_password_token,   :type => String
  #field :reset_password_sent_at, :type => Time
  field :reset_password_sent_at, :type => Time

  ## Rememberable
  field :remember_created_at, :type => Time
  #field :remember_created_at, :type => String

  ## Trackable
  field :username,           :type => String
  field :sign_in_count,      :type => Integer, :default => 0
  #field :current_sign_in_at, :type => Time
  #field :last_sign_in_at,    :type => Time
  field :current_sign_in_at, :type => Time
  field :last_sign_in_at,    :type => Time
  field :current_sign_in_ip, :type => String
  field :last_sign_in_ip,    :type => String

  field :first_name,         :type => String
  field :last_name,          :type => String

  #field :business_ids,         :type => Array

  field :address,       :type => String
  field :city,          :type => String
  field :state,         :type => String
  field :zip,           :type => String
  field :country,       :type => String
  field :phone,         :type => String

  # User Avatar
  attr_accessible :avatar
  has_mongoid_attached_file :avatar,
    :styles => { :full => ["512x512>", :jpg], :medium => ["256x256>", :jpg] },
    :convert_options => {:medium => "-background black -gravity center -extent 256x256"},
    :default_url => "/assets/avatar-blank.png"

  validates_attachment_size :avatar, :less_than => 5.megabytes
  validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']

  ## Confirmable
  # field :confirmation_token,   :type => String
  # field :confirmed_at,         :type => Time
  # field :confirmation_sent_at, :type => Time
  # field :unconfirmed_email,    :type => String # Only if using reconfirmable

  ## Lockable
  # field :failed_attempts, :type => Integer, :default => 0 # Only if lock strategy is :failed_attempts
  # field :unlock_token,    :type => String # Only if unlock strategy is :email or :both
  # field :locked_at,       :type => Time

  ## Token authenticatable
  # field :authentication_token, :type => String

  after_create :create_business

  def create_business
    Business.create(business_id: self.id)
  end

  def assign_default_role(b)
    # assign a default role if no role is assigned
    # IF, invite token make user an editor for business

    # ELSE, make the user owner of the business
    self.add_role "owner", b
  end

  #Returns a businesses for a user. The return type is an array of Business models.
  def businesses
    Business.find(get_business_ids)
  end

  #returns the user business_ids (Array of Strings)
  def get_business_ids
    Business.find_roles(nil, self).map{|b| b.resource_id.to_s}.to_a
  end
end

Comment: If this is Rails 4, you need to permit these new parameters, see: http://stackoverflow.com/a/17736187/614819

You'll also need some controller code to create the new business, so you'll need to overwrite Devise's registration controller.
Comment: Are you overriding Devise's `RegistrationController` at all? You'll need to do that to permit the attributes per @zgohr's recommendation. You'll also need to use [`accepts_nested_attributes_for`](http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html) to create the writers for the `business` attributes. Here's an article that might be helpful: http://www.railsexperiments.com/using-strong-parameters-with-nested-forms/
Answer: Try override Devise's registration controller:
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def create
    # save business here
  end
end

And then tell devise to use customized controller:
# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}


Copying Directories in Python

Question: I am trying to copy a directory from a location to other location and i have written code for that. On executing the IDE is giving me an exception.
import sys
import os
from Tkinter import *
from tkCommonDialog import Dialog
import shutil
import tkFileDialog
import win32com.client

win = Tk()
win.title("Copying the Dorectory to specified location")
win.geometry("600x600+200+50")
win.resizable()
class Copy:

    def __init__(self,Obj):

        la = Label(win, text = "Source Directory is",font = "verdana 12 italic bold", width = 20,fg = "Red", bg = "WHITE", )
        la.grid(row=1, column =1)
        abc = "tk_chooseDirectory"
        bu = Button(text="Source", font = "Verdana 12 italic", command= abc )
        bu.grid(row =1 , column =3)

        la1 = Label(win, text = "DestibationDirectory is",font = "verdana 12 italic bold", width = 20,fg = "Red", bg = "WHITE", )
        la1.grid(row=2, column =1)
        abc1 = "tk_chooseDirectory"
        bu1 = Button(text="Destination", font = "Verdana 12 italic", command=abc1)
        bu1.grid(row =2 , column =3)

        def start():
            shutil.copy(abc, abc1)
        bu2 = Button(text="Copy", font= "Verdana 12 bold", command =start)
        bu2.grid(row =3, column =2)

obj = Copy(win)
win.mainloop()

This is my code and the exception that I am facing is
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "C:\Documents and Settings\Bharath Gupta\Desktop\task.py", line 38, in start
    shutil.copy(abc, abc1)
  File "C:\Python27\lib\shutil.py", line 116, in copy
    copyfile(src, dst)
  File "C:\Python27\lib\shutil.py", line 68, in copyfile
    raise Error("`%s` and `%s` are the same file" % (src, dst))
Error: `tk_chooseDirectory` and `tk_chooseDirectory` are the same file

Please some one help me to get rid of the exception.
Comment: Use `shutil.copytree` to copy entire directories.
Comment: Friend Finally I got the ans to my Quesn;;; Thats very simple we should call the variable with the class name specification like """classname.variablename"""
Answer: Look at the code you have, with a few added comments by me.
class Copy:
    def __init__(self,Obj):
        la = Label(win, text = "Source Directory is",font = "verdana 12 italic bold", width = 20,fg = "Red", bg = "WHITE", )
        la.grid(row=1, column =1)
        #SET abc HERE
        abc = "tk_chooseDirectory"
        bu = Button(text="Source", font = "Verdana 12 italic", command= abc )
        bu.grid(row =1 , column =3)

        la1 = Label(win, text = "DestibationDirectory is",font = "verdana 12 italic bold", width = 20,fg = "Red", bg = "WHITE", )
        la1.grid(row=2, column =1)
        #SET abc1 HERE
        abc1 = "tk_chooseDirectory"
        bu1 = Button(text="Destination", font = "Verdana 12 italic", command=abc1)
        bu1.grid(row =2 , column =3)

        def start():
            #RUN WITH abc AND abc1
            shutil.copy(abc, abc1)

But you never change the values of those variables. Since you initialize them to the same thing. Your copy command is trying to copy something to itself. (Which is what the error says:

Error: tk_chooseDirectory and tk_chooseDirectory are the same file

You need a way to enter in the two directories you want to use so that shutil.copy() will do what you want.
Comment: unholysampler@ can u please elaborate the ans. tk_chooseDirectory is used to select the directories.
Comment: @BharathGupta: The button uses that as the callback function. The problem is that callback just opens the dialog and allows you to select a directory. It __does not__ save that result into into the variable you happened to use to initialize the button.
Comment: Thats so nice of u dude.And now how could I store the path that I select using the tk_ChooseDirectory.
Comment: @BharathGupta: Write a method that calls `tk_ChooseDirectory` and saves the result into an instance variable. Use that as the callback method.
Comment: Friend Finally I got the ans to my Quesn;;; Thats very simple we should call the variable with the class name specification like """classname.variablename" ""
Answer:
Please some one help me to get rid of the exception.

A sure-fire way to get rid of exceptions is this pattern:
try:
    #shutil naughtiness
except:
    pass

...but that one's sure to draw your colleagues' ire.
It looks like in your particular case the source and destination are the very same.  It seems like the most appropriate thing to do in this case is to handle the exception.  Especially since this is only one of many failure modes of the copy.  You should escalate each of them to the user, since the user should know how to resolve it.
You're in the enviable position that your code is likely well-equipped to handle the exception.  Try
try:
    shutil.copy(abc, abc1)
except Error, e:
    tkMessageBox.showwarning(
        "Copying file",
        "Error while copying\n(%s)" % e.msg
    )

Comment: try:
    shutil.copy(abc, abc1)
except :
    tkMessageBox.showwarning(
        "Copying file",
        "Error while copying\n(%s)"
    )

Dude this is the change that I have done.On running the file it is giving me an error and what should i do to copy my directory to other.

Please please help me in this aspect
Comment: Dude, the user should see the error and take corrective action.  The exception handler above does this.  The user will see "tk_chooseDirectory and tk_chooseDirectory are the same file" and realize, "Oops!  I can't copy a file onto itself.  That's silly."
Comment: @Brain Chain. This is right but now If i wanna copy., How could I progress and whats the method to do.Please give me a clear idea. Thanks
Comment: Friend Finally I got the ans to my Quesn;;; Thats very simple we should call the variable with the class name specification like """classname.variablename""
Answer: import sys
import os
import tkMessageBox
from Tkinter import *
from tkCommonDialog import Dialog
import shutil
import tkFileDialog
import win32com.client

win = Tk()
win.title("Copying the Directory to specified location")
win.geometry("600x600+200+50")
win.resizable()

class Copy(object):

    def __init__(self):
        def srce():

            self.src = tkFileDialog.askdirectory(title="The source folder is ")
            textboxsrc.delete(0, END)
            textboxsrc.insert(0, self.src)
            print self.src
            return self.src

        textboxsrc = Entry(win, width="70")
        textboxsrc.insert(0, 'Enter master file name')
        textboxsrc.pack()
        textboxsrc.place(relx=0.40, rely=0.06, anchor=CENTER)
        bu = Button(text="Source", font="Verdana 12 italic bold", bg="Purple", fg="white", command=srce)
        bu.pack(fill=X, expand=YES)
        bu.place(relx=0.85, rely=0.06, anchor=CENTER)

        def dest():
            self.des = tkFileDialog.askdirectory(title="TheDestination folder is ")
            textboxdes.delete(0, END)
            textboxdes.insert(0, self.des)
            print self.des
            return self.des

        textboxdes = Entry(win, width="70")
        textboxdes.insert(0, 'Enter master file name')
        textboxdes.pack()
        textboxdes.place(relx=0.40, rely=0.13, anchor=CENTER)
        bu1 = Button(text="Destination", font="Verdana 12 italic", bg="Purple", fg="white", command=dest)
        bu1.pack(fill=X, expand=YES)
        bu1.place(relx=0.85, rely=0.13, anchor=CENTER)

        def start():

            try:
                shutil.copytree(self.src, self.des)
            except :
                tkMessageBox.showwarning("Copying file", "Error while copying\n(%s)")

        bn = Button(text="Copy", font="Verdana 12 italic", bg="Purple", fg="white", command=start)
        bn.pack(fill=X, expand=YES)
        bn.place(relx=0.50, rely=0.25, anchor=CENTER)

obj = Copy()
#obj.source(win)
#obj.destination(win)
win.mainloop()

Copying Directories in Python


Excel file corrupt when copied from src to target in Eclipse IDE

Question: I have a strange issue with eclipse. When I put a .xls file in the src/test/resources path it is copied by eclipse to the target path.
However, the file in the target path is not the same anymore. I cannot open it in MS Excel anymore and when I compare the two files, I see some binary differences. How can this happen?
PS: my eclipse environment is generated with maven.
Comment: Have you tried to exclude ressource from filtering ? http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
Answer: Thanks to the above answers we found out how to deal with the problem:
    <plugin>
      <artifactId>maven-resources-plugin</artifactId>
      <version>2.5</version>
      <configuration>
        <encoding>UTF-8</encoding>
        <nonFilteredFileExtensions>
          <nonFilteredFileExtension>xls</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
      </configuration>
    </plugin>

Comment: Thanks for the hint, I didn't know these options :)
Answer: I had the same issue, and it was cause by the Maven resources plugin which filtered and altered my Excel files.
To prevent this to happen, add something like this (see the Maven doc) :
<build>
       <resources>
           <resource>
               <filtering>true</filtering>
               <directory>src/test/resources</directory>
               <excludes>
                   <exclude>**/*.xls</exclude>
               </excludes>
         </resource>
...

UPDATE : Copy in resources, but don't filter
<resources>
      <resource>
        <directory>src/test/resources</directory>
        <filtering>true</filtering>
        <excludes>
          <exclude>**/*.xls</exclude>
        </excludes>
      </resource>
      <resource>
        <directory>src/test/resources</directory>
        <filtering>false</filtering>
        <includes>
          <include>**/*.xls</include>
        </includes>
      </resource>
      ...
    </resources>

Comment: with this snippet the xls file will not be copied. However, we need the file, but not corrupted
Comment: Ant build script have similar issues, when you apply a filter it has to read the file, this assumes you are using a text file and the files will be copied as text and not as bytes resulting in corruption
Comment: @nico_ekito - Please would you clarify your answer, its unclear what has been updated, and what is the actual answer.  thanks.
Comment: I think you have the include and exclude mixed up. The `filtering=true` resource should _exclude_ excel files, and the `filtering=false` resource should _include_ excel files.
Comment: The same concept applies to `maven-assembly-plugin`. Excel files should be in a separate `fileSet` tag. Worked for me.
Comment: This saved my day!


Spark scala with dependencies in one single jar

Question: I have a Scala Spark application for which I want to create jar with dependencies using maven.
I am using maven-assembly-plugin
<plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

but when I am running my app with Spark-submit command, I am still getting java.lang.NoClassDefFoundError. When I am running it with --jars option and provide path for dependencies jar, It is running fine. Please let me know if I am missing something. Thanks
Comment: Are you using the jar called 'jar-with-dependencies'? (We never know) What are the missing dependencies, Can you show your dependencies?
Comment: Sorry. my bad. I have given the dependency scope as 'provided' by mistake. So after removing the scope, My jar is working fine. Thanks
Answer: The configuration looks good.
Try to delete previous application jars and run 'mvn package' command to create a new one.


Python program bombs out after finishing

Question: I'm getting a strange Python error. I'm executing a file that looks like this.
if __name__ == '__main__':
    MyClass().main()
    print('Done 1')
    print('Done 2')

The preceding runs successfully.  But when I change it to this, I get the strange result.
if __name__ == '__main__':
    myObject = MyClass()
    myObject.main()
    print('Done 1')
    print('Done 2')

The output looks like this.
Done 1
Done 2
Exception ignored in: <function Viewer.__del__ at 0x0000021569EF72F0>
Traceback (most recent call last):
  File "C:\...\lib\site-packages\gym\envs\classic_control\rendering.py", line 143, in __del__
  File "C:\...\lib\site-packages\gym\envs\classic_control\rendering.py", line 62, in close
  File "C:\...\lib\site-packages\pyglet\window\win32\__init__.py", line 305, in close
  File "C:\...\lib\site-packages\pyglet\window\__init__.py", line 770, in close
ImportError: sys.meta_path is None, Python is likely shutting down

Process finished with exit code 0

There is a blank line after the final print line. The same thing happens when the final line does not have an end-of-line marker.
I get the same result whether I run it from within PyCharm using the run command or from the terminal.
As you can probably tell from the error lines, the program generates an animation. (It's the cart-pole problem from OpenAI gym.)
Since the program completes before the error, it's not a disaster. But I'd like to understand what's happening.
Thanks.
Comment: Can you provide the code for MyClass or a minimum case which reproduces this bug - https://stackoverflow.com/help/mcve ?
Comment: @alfasin. Adding `env.close()` as the last line in `main` solved the problem. Thanks. Interestingly, the cart-pole environment terminates an episode only when the cart or pole go out of bounds. Otherwise one can `step` forever. So if the program that calls `env.step()` terminates the episode after some number of steps, the environment is left hanging in what it thinks is the middle of an episode.
Comment: Try to add `env.close()` to your code, for more details see: https://github.com/openai/gym/issues/893#issuecomment-369519156
Comment: does adding `import gc; gc.collect()` after the print statements prevent the output?
Answer: Python provides a __del__ dunder method for classes that will be called as the instances are garbage collected, if they're garbage collected.
When it's used, the __del__ method typically performs some sort of cleanup.
Due to the fact that it's fairly easy to inadvertently prevent an object from being collected, reliance on the __del__ to perform cleanup (instead of say, a context manager's __exit__ or an explicit .close() method) is generally advised against.
Your error highlights a different reason for avoiding relying on __del__, however: that during shutdown __del__ will be called but possibly after other things that it relies on are freed.
The proposed workarounds on the github issue linked in the comments should be instructive, as they all ensure that the cleanup is done at a time where the things that that cleanup relies on (e.g. sys.meta_path) are still in defined/not yet freed, e.g.:
try:
    del env
except ImportError:
    pass

and
env = gym.make('CartPole-v0')
...
env.env.close()

and (likely, but much less efficient or clear)
import gc; gc.collect()

Comment: Thanks for the explanation. For those interested in why it came up in this context, please also see my comment on the original question.


Read field value from $variables in hook_preprocess_html()

Question: I want to get a field value from a node that I can use in the html--front.html.twig template file.
I can create a new variable, for example with $variables['custom_twig_variable'] = 'Some important value';.
Then in the template file, I would simply get that value with {{ custom_twig_variable }}.
I don't know how to get the field value from $variables, the argument passed to the theme hook, whose content is the following one.
Array (
  [user] => Drupal\Core\Session\AccountProxy Object (
    [requestStack:protected] => Symfony\Component\HttpFoundation\RequestStack Object (
      [requests:Symfony\Component\HttpFoundation\RequestStack:private] => Array (
        [0] => Symfony\Component\HttpFoundation\Request Object (
          [attributes] => Symfony\Component\HttpFoundation\ParameterBag Object (
            [parameters:protected] => Array (
              [_system_path] => node/4
              [_controller] => \Drupal\node\Controller\NodeViewController::view
              [_title_callback] => \Drupal\node\Controller\NodeViewController::title
              [node] => Drupal\node\Entity\Node Object (
                [values:protected] => Array (
                  [vid] => Array (
                      [x-default] => 4
                  )
                  [field_background_color] => Array (
                    [x-default] => Array (
                      [0] => Array (
                        [value] => ff00ff
                      )
                    )
                  )
                )
              )
            )
          )
        )
      )
    )
  )
)

How do I get the value of field_background_color?
Answer: So your field is on the node?
Then you need to get the node object first.
<?php
if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {

}

Once you have that, you can read your field, assuming it is a text field, like this: $node->field_background_color->value. Make sure to always check if you really have a $node object as done in the snippet above when you're in the global context. You will only have on on node/N, but not on other pages.
There are many questions already about how to access field values, and there are great presentations as well.
Comment: True, that is helpful but you then still have to know how to access the value. I've already seen too much code that is then working with the array structure returned from that, when working with the node object is much easier.
Answer: Simply iterate the $variables['view']->result array and get every field value you want.
foreach ($variables['view']->result as $key=>$result){
    $field = $result->_entity->get('field_name')->getValue();
    $variables['rows'][$key]['var_name'] = $field[0]['value'];
}

In this line $variables['rows'][$key]['var_name'] = $field[0]['value']; you save the data into the row-variable where you can access it later in your twig-template with {{row.var_name}}
Answer: You have entity values at hand
$element = $variables['element'];
if ( $entity = $element['#object'] ) {
  dump ($entity);
  exit;
}


S3 Bucket CORS configuration not accepted

Question: People of the internet, I need your help. I'm trying to put this code in my S3 butcket CORS and I get this error: Expected params.CORSConfiguration.CORSRules to be an Array
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "PUT",
            "POST",
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    }
]

Comment: https://s3-presigned-url.workshop.aws/preparation/cors_config.html
Answer: Your JSON is not valid. If you test this with an online (or other) validator, you'll see an error in your AllowedMethods, specifically that the final value in that array has a trailing comma (valid JavaScript, but invalid JSON).
Change the policy to this:
[{
    "AllowedHeaders": [
        "*"
    ],
    "AllowedMethods": [
        "GET",
        "PUT",
        "POST"
    ],
    "AllowedOrigins": [
        "*"
    ],
    "ExposeHeaders": [],
    "MaxAgeSeconds": 3000
}]

Comment: thank you! my bad, I guess I just need to learn read the error messages. The message is clear, they were already telling me its an Invalid JSON


Web API - Como validar o modelo a partir do DataAnnotation.Remote()?

Question: Tenho o seguinte modelo (DTO):
public class PessoaAcesso : Pessoa
{
    [Remote("LoginUnico", "Pessoa", ErrorMessage = "Esse Login já existe! Escolha outro.")]
    public virtual string Login { get; set; }
    ...
}

No meu ApiController (WebAPI) implementei o método "LoginUnico" para testes:
public JsonResult<bool> LoginUnico(string login)
{
    return Json(false);
}

Porém ao fazer a requisição via POST não está acionando o método. Era para ele rejeitar a inserção da nova pessoa, porém está aceitando.
Quem já tenha implementado o Remote() no WebAPI pode me orientar.
Comment: Já anotou `[HttpPost]` na `Action` antes de testar?
Answer: Anote seu método com [HttpPost]:
[HttpPost]
public JsonResult<bool> LoginUnico(string login)
{
    return Json(false);
}


When to create schema while working with config entity?

Question: We have a custom form mymoduleForm.php that is used to perform some logic by calling mymodule_preprocess_node(). We were able to add addCacheableDependency() and now the mymodule_preprocess_node hook is able to pull the latest changes even after making several changes and clearing cache.
We did not create a mymodule.schema.yml as this configuration is not used for translation or any other way then to store some value in the some_field field.
Although it appears to be working just fine without the mymodule.schema.yml file, we were wondering if it is needed. We need some guidance on whether or not this is a situation where the mymodule.schema.yml is needed (or if it always needed).
mymoduleForm.php
class mymoduleForm extends ConfigFormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (!$this->entity->isNew()) {
        \Drupal::service('renderer')->addCacheableDependency($form, $this->entity);
      }

    $config = $this->config('mymodule.settings');

    $form['some_field'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Some field title'),
      '#description' => $this->t('some description'),
      '#default_value' => $config->get('some_field'),
    ];

    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('mymodule.settings'),
      ->set('some_field', $form_state->getValue('some_fields'))
      ->save();
  }
}

mymodule_preprocess_node
function mymodule_preprocess_node(&$variables) {
  $config = \Drupal::config('mymodule.settings');
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')->addCacheableDependency($variables, $config);
  $config_value = $config->get('some_field');

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}

This is a follow up question from How to clear cache for config entity after making changes?
Answer: Short answer: you should always have one, but you can avoid it if you really want (see point 3 below).

What are schema files used for?

The primary use case schema files were introduced for is multilingual support. We need to have a tool to identify all translatable strings in your shipped configuration so when you ship with your own settings as well as default Views, additional user roles, menu items, etc. we can offer those up for translation as part of your module/theme release on http://localize.drupal.org. The nesting levels and types would be enough for this use case.
We also use schemas to provide actual translation forms for configuration based on your data. This use case is where types gain more importance and labels become crucial. The core Configuration translation module uses schemas to generate translation forms and save translations. The two most important built-in translatable types are 'label' for one-line text input and 'text' for multiline text input.
Using the knowledge embedded in the configuration schemas about what is stored of a configuration entity, the default persistence implementation for configuration entities requires a configuration schema for the configuration entity, so the right properties are exported with the types defined. Although it is better to provide configuration schemas, if you really don't want, implement the toArray() method in your configuration entity implementation to not require schema for saving configuration entities of your type.
Last but not least configuration schema is also used to automatically typecast values to their expected types. This ensures that although PHP and web forms in general favor strings over all other types, the right types are used when saving configuration. That is important so when deploying configuration, only actual changes will show up in the difference, no random type changes.

From Configuration schema/metadata
Comment: using the link you provided we have created `config/install/mymodule.settings.yml` and `/config/schema/mymodule.schema.yml` as well.


Gente, queria agrupar UF do Brasil em regiões no R, já criei uma coluna de dummies pra cada, mas n sei como eu posso agrupá-las em uma só coluna

Question: Ex:
O que eu já fiz é isso:
MICRODADOS.ENEM.2020$Norte= ifelse(MICRODADOS.ENEM.2020$SG_UF_PROVA =="RR"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="AP"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="PA"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="AM"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="AC"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="RO"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="TO",1,0)

MICRODADOS.ENEM.2020$Nordeste= ifelse(MICRODADOS.ENEM.2020$SG_UF_PROVA =="MA"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="PI"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="CE"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="RN"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="PB"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="PE"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="AL"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="SE"
                                   |MICRODADOS.ENEM.2020$SG_UF_PROVA =="BA",1,0)

Mas n sei como eu agrupo em uma coluna só as regiões, separados por números
EX:
COLUNA: REGIÃO
Norte: todos os estados detém o número 1
Nordeste: número 2
Sul: número 3 ..........
Answer: Não precisa das variáveis dummie. Pode criar vetores com as siglas das UFs e usar indexação condicional. Como não postou uma amostra dos seus dados, vou usar um exemplo genérico:
set.seed(873)
dados <- data.frame(UF = sample(LETTERS[1:8], 16, TRUE))

norte <- LETTERS[1:2]
sul <- LETTERS[3:4]
leste <- LETTERS[5:6]
oeste <- LETTERS[7:8]

dados$regiao[dados$UF %in% norte] <- 1
dados$regiao[dados$UF %in% sul] <- 2
dados$regiao[dados$UF %in% leste] <- 3
dados$regiao[dados$UF %in% oeste] <- 4

head(dados)
#>   UF regiao
#> 1  C      2
#> 2  H      4
#> 3  A      1
#> 4  F      3
#> 5  G      4
#> 6  D      2

Se possui uma tabela com as siglas e os códigos (p.e. obtida pelo SIDRA), pode criar um dicionário de substituição:
regioes <- data.frame(UF = LETTERS[1:8], cod_reg = rep(1:4, each = 2))

regioes
#>   UF cod_reg
#> 1  A       1
#> 2  B       1
#> 3  C       2
#> 4  D       2
#> 5  E       3
#> 6  F       3
#> 7  G       4
#> 8  H       4

dic.regioes <- setNames(regioes$cod_reg, regioes$UF)

dados$regiao <- dic.regioes[dados$UF]

Answer: Você pode importar ou criar uma tabela com os nomes ou valores que deseja utilizar (UF, região) e depois unir essa tabela com os dados que está processando.
Por exemplo:
Carregar a tabela com microdados do ENEM 2020
library(data.table)

tb <- fread("../MICRODADOS_ENEM_2020.csv", nrows = 10, select = "SG_UF_PROVA")

Carregando uma tabela com UF, Estado e Região do Brasil
tb2 <- fread("../Estados_Brasil.csv", select = c("UF", "Estado", "Região"))

Transformando a Variável "Região" em número e incluindo o dado na coluna "Região2":
tb2[, Região2 := c("Norte" = 1L,
                   "Nordeste" = 2L,
                   "Sudeste" = 3L,
                   "Sul" = 4L,
                   "Centro-Oeste" = 5L)[Região] ]

Unir as duas tabelas:
tb3 = tb2[tb, on = c(UF = "SG_UF_PROVA")] # usando as colunas "SG_UF_PROVA" da tabela "tb" e "UF" da tabela "tb2" (ambas contem o dado da UF)

Resultado:
> head(tb3)
   UF              Estado   Região Região2
1: PA                Pará    Norte       1
2: RN Rio Grande do Norte Nordeste       2
3: BA               Bahia Nordeste       2
4: SP           São Paulo  Sudeste       3
5: MG        Minas Gerais  Sudeste       3
6: RS   Rio Grande do Sul      Sul       4
>

Tabelas usadas no exemplo:

> dput(tb)
structure(list(SG_UF_PROVA = c("PA", "RN", "BA", "SP", "MG",
"RS", "PE", "SP", "PB", "CE")), row.names = c(NA, -10L), class = c("data.table",
"data.frame"))

> dput(tb2)
structure(list(UF = c("RO", "AC", "AM", "RR", "PA", "AP", "TO",
"MA", "PI", "CE", "RN", "PB", "PE", "AL", "SE", "BA", "MG", "ES",
"RJ", "SP", "PR", "SC", "RS", "MS", "MT", "GO", "DF"), Estado = c("Rondônia",
"Acre", "Amazonas", "Roraima", "Pará", "Amapá", "Tocantins",
"Maranhão", "Piauí", "Ceará", "Rio Grande do Norte", "Paraíba",
"Pernambuco", "Alagoas", "Sergipe", "Bahia", "Minas Gerais",
"Espírito Santo", "Rio de Janeiro", "São Paulo", "Paraná",
"Santa Catarina", "Rio Grande do Sul", "Mato Grosso do Sul",
"Mato Grosso", "Goiás", "Distrito Federal"), Região = c("Norte",
"Norte", "Norte", "Norte", "Norte", "Norte", "Norte", "Nordeste",
"Nordeste", "Nordeste", "Nordeste", "Nordeste", "Nordeste", "Nordeste",
"Nordeste", "Nordeste", "Sudeste", "Sudeste", "Sudeste", "Sudeste",
"Sul", "Sul", "Sul", "Centro-Oeste", "Centro-Oeste", "Centro-Oeste",
"Centro-Oeste"), Região2 = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 5L,
5L, 5L, 5L)), row.names = c(NA, -27L), class = c("data.table",
                                                 "data.frame"))


Migrate process plugin entity_lookup: value_key: field with multiple values

Question: The field "field_erp_code" has multiple values, but it seems that migrate only looks at delta 0 of that field. Can this be done by with the entity_lookup plugin?
 field_product_category:
    plugin: entity_lookup
    source: Product category
    entity_type: taxonomy_term
    bundle_key: vid
    bundle: product_category
    value_key: field_erp_code

Answer: The entity_lookup plugin from the migrate_plus module already supports multi-valued fields. But you can specify manually the operator: IN if necessary.
See \Drupal\migrate_plus\Plugin\migrate\process\EntityLookup.
Try to debug this plugin and see what comes as the value.


Bootstrap-table text truncate

Question: I'm currently using Bootstrap-table (http://bootstrap-table.wenzhixin.net.cn/) with the bootstrap-editable extension (https://github.com/wenzhixin/bootstrap-table/tree/master/src/extensions/editable) to create a table with editable fields. I have noticed that when a string contains qoutes for example: this is a "test" the string is being truncated on the first ". I have noticed that the text is correctly saved in the database, the JSON contains the full text (" not escaped).
How can I solve this?
Answer: You need to set the text-overflow property to clip or initial for the cell where your text is being truncated.
This will help https://www.w3schools.com/cssref/css3_pr_text-overflow.asp
Comment: This seems applicable if the text is too long for the given space.  This however does not seem to be the case in my particular case (there are much longer texts that are correctly shown). Or am I missing something?
Comment: JSON splits the segment by finding the next " symbol (I'm not 100% sure). Check your response in the browser console and compare with your output. I think whenever it finds a " symbol, it takes it as the end of that value. Use single quote instead of double quote.
Comment: Based on preliminary tests seems escaping the " character seems the solution to my problem.  Thanks.

Bootstrap-table text truncate


Python Selenium cannot click submit button

Question: A quick question. How do I click on the following button link using selenium in python? The button does not have any ID or value
Login == $0

I receive below mentioned error:
Unable to locate element: //input[@type="submit" and @title="login"]

Thanks!
Comment: you can use `driver.find_element_by_class('classname123').click()`
Answer: You can use search by link text to handle exact element:
login = driver.find_element_by_link_text('Login')

Answer: The element is , not <input>, doesn't have type attribute and it has text Login, not title login
//a[contains(., "Login")]

Comment: Thanks! This works. The firefox browser opens and click the button. Is this also possible at the background? (underwater) Or only by physical acces?
Comment: @Jessekraal Have a look at [headless browser](http://toolsqa.com/selenium-webdriver/headless-browser-testing-selenium-webdriver/). It can be used for testing without opening actual browser (I never worked with them though).
Answer: What you have shared is  and your error is in <input> as your xpath saying
use following to click on that link
.//a[text()='Login']

or
.//a[@class='classname123'][text()='Login']

Answer: Try this way.
//a[contains(text(), 'Login')]

OR
Try this way using class attribute of a tag.
//a[@class='classname123']


git pathspec: Combine "glob" and "exclude" to exclude directories anywhere in the tree?

Question: I would like to run git ls-files with a pathspec that will exclude any directory named foo and all of its children, anywhere it appears in my repository.
The git glossary makes it seem like the glob and exclude "magic words" are compatible, and that a pathspec of the form
:(exclude,glob):**/foo

will achieve my goal. But, when I run
git ls-files -- . ':(exclude,glob):**/foo' | grep foo

I see a lot of foo entries, that I had hoped to filter with that pathspec, appear in the output.
Are these options incompatible? If so, what is the correct way to git ls-files and filter out subdirectories that appear anywhere but match a specific name? I would prefer to do this in one step, and not pipe the output of git ls-files to another process for subsequent filtering.
Answer: The pathspec should be ':(exclude,glob)**/foo/**'.
The : after ) is not necessary. Otherwise, it is interpreted as the first letter of the pattern, which is not what you expect.
The 2nd ** refers to the files recursively or not recursively under foo.
Comment: Brilliant, thanks! One of my mistakes was assuming that it used `.gitignore` style formatting, where `**/foo` does seem to filter out `foo` anywhere in the tree.


Why was Max Verstappen not required to start on his Q2 tyres in the Hungary GP?

Question: This article (in Dutch) cites Max Verstappen deliberately choosing to start today's (July 31st, 2022) Hungary Grand Prix on soft tyres, rather than hard ones:

"Met de harde band zou dat nog veel moeilijker zijn geweest", vertelde de regerend wereldkampioen op de persconferentie. "Ik heb toen meteen gezegd: no way dat wij op hard gaan beginnen."

My translation:

"It would have been much more difficult with the hard tyres", told the reigning world champion at the press conference. "I immediately said: no way we're starting on hard."

Why was he able to choose on which tyre to start? I thought drivers which made the third qualifying stage (Q3) were required to start on the tyres with which they made their fastest lap in Q2. Max Verstappen had engine issues in Q3 and his engine was replaced, did that give him a way out?
Answer: The (Q2 tyre) rule was dropped for 2022: https://www.autosport.com/f1/news/f1-regulations-update-confirms-removal-of-q2-tyre-rule/8313153/

The FIA has confirmed Formula 1 drivers qualifying inside the top 10 will no longer be required to start the race on their Q2 tyre from the 2022 season.


How to prove: if $a$ is an even integer, $\gcd(a^3 - 1, a + 1) = 1$

Question: I have very little idea of how to tackle this question. I know if $a$ is even, $a = 2L$, for some $L$ in the integer set.
Comment: Hint:  $a^3-1=(a-1)(a^2+a+1)$ and, since $a$ is odd, $(a+1,a-1)=1$
Comment: but a is even in the problem.
and i knew to use the difference of cubes, but i don't see where that gets me
Comment: Sorry, I meant to say "since $a$ is even" in my comment.  But, with that correction:  just note that $(a+1,a^2+a+1)=(a+1,a^2)$.
Comment: The posted solution spells this out (and avoids the blunder I made).
Comment: Lulu thank you so much for your help this evening! I really appreciate it!
Comment: This is all the charm of accepting an answer right away but... note that the Euclidean division $$a^3-1=(a+1)(a^2-a+1)-2$$ shows that $\gcd(a^3-1,a+1)=\gcd(2,a+1)\in\{1,2\}$, and I am sure that you can see why the gcd is $1$ when $a$ is even (as in your question) and $2$ when $a$ is odd.
Answer: Actually,
since $a$ is even,
$\gcd(a + 1, a - 1) = 1$.
Since
$a^3-1
=(a-1)(a^2+a+1)
$,
$\gcd(a^3-1, a+1)
=\gcd(a^2+a+1, a+1)
=\gcd(a^2, a+1)
=1
$.
Comment: thank you so much! both you and @lulu have helped me a great deal!
Comment: It's nice to upvote or accept.
Comment: sorry, first time on the site. just did both!
Comment: forgive my ignorance, but in my haste i overlooked the final conclusion.
how does one ascertain that gcd(a^2, a+1) = 1?
Comment: Because $gcd(a, a+1) = 1$.
Comment: thank you so much, Mr. Cohen!


class level validation rules across multiple properties

Question: I have properties of a class that I want to apply some validation rules to.
I want to create a custom validator that:
- checks to see if the number and/or the address is present
- and if neither are present then return a message "This is required"
Currently I have:
<code>[CustomValidation(typeof(Course), "NumberOrAddressValidator")]
public class Information {
    public string Number { get; set; }
    public string Address { get; set; }
}
public static ValidationResult PhoneOrWebAddressRequiredValidator(string name, ValidationContext context)
        {
            if (Course.WebAddress == null)
            {
                return "Phone or web address is required";
            }
            else if(Course.PhoneNumber == null)
            {
                return "Phone or web address is required";
            }
            else
            {
                return ValidationResult.Success;
            }

        }
</code>
Am I thinking about this correctly? I am a bit stuck on understanding what "return ValidationResult.Success" exactly does. And currently it is throwing an error on returning a string (the message I want to return).
Any tips and help would be appreciated!
Answer: As per my understanding you should go for Expressive-Annotation instead of making custom validation. Install NuGet Package by running in PMC
PM> Install-Package ExpressiveAnnotations -Version 2.9.5
Your code will look like.
<code> public class Information
{
    [RequiredIf("Address==null", ErrorMessage = "Number or Address is Required")]
    public string Number { get; set; }
    [RequiredIf("Number==null", ErrorMessage = "Number or Address is Required")]
    public string Address { get; set; }
}
</code>
Comment: Thanks @shahid but in this example, I want to use a custom validator as I am practicing that.


LookupError: No installed app with label 'core'

Question: Inicialmente o projeto usava django 1.7 mas estou migrando ele para django 1.10.3, mas quando tento usar o migrate informa esse erro  de que o 'core' não esta instalado, infelizmente não existe um aplicativo core no meu programa ! a unica coisa com esse nome e uma pasta com alguns aplicativos dentro, e eu simplesmente colocava o caminho deles, mas acho que isso não e aceito em django 1.10.3, qual seria o novo método de fazer isso ? ou me livrar desse erro ?
Edit: Erro
<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 148, in get_app_config
    return self.app_configs[app_label]
KeyError: 'core'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)

  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 342, in execute
    self.check()
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 374, in check
    include_deployment_checks=include_deployment_checks,
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/migrate.py", line 62, in _run_checks
    issues.extend(super(Command, self)._run_checks(**kwargs))
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 361, in _run_checks
    return checks.run_checks(**kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/checks.py", line 16, in check_user_model
    cls = apps.get_model(settings.AUTH_USER_MODEL)
  File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 195, in get_model
    return self.get_app_config(app_label).get_model(model_name.lower())
  File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 155, in get_app_config
    raise LookupError(message)
LookupError: No installed app with label 'core'.
</code>
Answer: Você precisa consultar a documentacao da versao 1.10 tem migrate (acredito que nao;. se for o caso tente utilizar o SOUTH e veja se ele é compativel com a versao 1.10.
Caso nada disso de certo voce vai ter que fazer do jeito antigo (Django antes do South/Migrate) a migracao do banco.
Comment: O problema não esta no migrate e sim no fato que alguma coisa mudou no django 1.10  e essa coisa tem alguma ligação com o core do próprio django, pois não existe nenhum app meu chamado core
Comment: Cola o erro aqui pra gente ve
Comment: Pergunta editada com a saída gerada
Comment: Eu consegui resolver o problema, e basicamente foi um erro meu nas configurações do projeto onde estava tentando acessar um user criado por mim com um caminho diferente, mas obrigado mesmo por ter tentado ajudar


rational roots of a cubic

Question: If $a$ and $b$ are rational numbers, is there any if and only if condition on them, so that $x^3+ax+b=0$ will have no rational roots? The answer gives a condition that splitting field of the same polynomial over Q is of degree exactly 3. Thanks!!
Comment: Is your last sentence true? What about the polynomial  $x^3+2$?.
Answer: You can apply the rational root test. And the conclusion is not necessarily trule. For example $x^3+2$ has no rational roots but the degree of the splitting field has degree 6.
Comment: Sorry, but the rational root test, I believe works only for integer coefficients. But here I am allowing any rational values for them. I hope we both are referring to the same rational root test. http://en.wikipedia.org/wiki/Rational_root_theorem
Comment: No just the absence of rational roots is not enough. An iff condition for that is, it has to have three distinct real irrational roots. I know an iff condition on a and b for three distinct real roots, just wanted one more condition that ensures that roots all are irrational.
Comment: @SameerKulkarni: 1 and 2 are integers.
Comment: > Robjohn Yeah they are integers. But the rational root test was suggested for the first line of my question. I asked for a test that works for any rational a and b. And as for the polynomial $x^3+2$ I have given the clarification above.
Comment: @SameerKulkarni: I thought that Luis was only applying the rational root test to $x^3+2$ to show that although it has no rational roots, its splitting field was not degree 3.
Comment: Any polynomial over $\mathbb{Q}$ can be factored as $f=cf_0(x)$ where $c\in \mathbb{Q}$, and $f_0(x)$ is a primitive polynomial over $\mathbb{Z}$. Then apply the rational root on $f_0(x)$.
Comment: @robjohn That is what I wanted to show.

rational roots of a cubic


How Do I Handle Ampersands in Django URLs?

Question: I have a Django site that uses item names to create viewer-friendly URLs.  For instance:
/item/DeluxeWidget/

I have an item that has an ampersand in the name:
/item/Red & Blue Widget/

The ampersand throws things off.  If I use {{ widget.name|fix_ampersands }}, the ampersand will be escaped as & but it still isn't picked up in the URL pattern:
url(r"^widget/(?P<name>[0-9a-zA-Z&,. -]+)/$", 'site.views.widget' ),

In the view I use the captured name to do
Widget.objects.get(name=name)

What's the right combination of escaping, patterns, or filters to handle an ampersand in a URL?  I also expect to run into names with apostrophes in them.  Is there anything I should do to handle those too?
Comment: So the short answer is "don't".  Ampersands don't really belong in URLs anyhow.  Thank you for the suggestions -- it seems that SlugField is the ideal tool for what I'm trying to do.
Answer: Consider using a SlugField which can automatically be filled with a cleaned up version of another field suitable for use in URLs.
Comment: Yup - probably simpler for the OP instead of changing URL structure +1
Answer: Generally, you're best off not doing that, and following an SO kind of pattern - let's use this page for an example (http://stackoverflow.com/questions/13212960/how-do-i-handle-ampersands-in-django-urls)
Then you can do:
url(r"^widget/(?P<widget_id>[0-9]+)/(?P<widget_name>(.*?)/$", 'site.views.widget' ),

Then:

{{ widget.name|fix_ampersands }} becomes {{ widget.name|slugify }}
Widget.objects.get(name=name) becomes Widget.objects.get(pk=widget_id)


Propriedade left não funciona em position fixed

Question: Estou tentando fazer com que uma div fique fixa no rodapé da página, no canto direito, mas não encostado no fim da página, deste modo usei, como de costume:
width:50px;
height:100px;
background:#fff;
position:absolute;
bottom:0;
left:10;

Mas a div não recebeu a propriedade. Fui em inspecionar elemento no browser e sob o "left:10;" está um aviso "Invalid property value".
Alguém sabe me dizer algo sobre isso?
Comment: Você tem que indicar a unidade `px` ou `pt` etc.
Comment: Por que funciona com o "bottom:0;" sem a unidade, e não funciona com o left e com o right?
Comment: Pode ser uma limitação do browser.
Answer: No canto direito, não encostado.
width:50px;
height:100px;
background:#fff;
position:absolute;
bottom:0;
right:10px;

Comment: Neste caso eu vou usar position:fixed, tem alguma diferença?
Comment: O elemento apenas vai ficar fixo na tela em relação a tela do computador com `position: fixed`. Com `position: absolute` o elemento fica com a posição referente ao primeiro elemento pai com `position: relative` ou o elemento `html`.
Answer: Funciona desde que o elemento pai esteja com position: relative;


Understanding Deep Neural Network for Youtube Recommendation Paper

Question: I am trying to understand the paper - deep neural network for youtube recommendation. They divided their approach into two phases - candidate generation and ranking.
Candidate generation diagram below:

I understand that the video embeddings are learned jointly with all other model parameters. That means embedded video watches and embedded search tokens are trained along with the candidate generation model.
If you look at the softmax box, they are getting class probabilities and video vectors vj. This is really confusing. How can you extract two different outputs from softmax? Or rather I should say how do you extract video vectors vj from this model?
Please suggest.
Comment: My understanding is that the softmax is a humongous multiclass classification that identifies/ranks some video ids. You then go ahead and take the embedding of those videos and use them for NN Search. What I'm confused about is the `user vecotr u`, any thoughts on that?
Answer: The video vectors $v_j$ are simply the video embeddings; based on what I see, the input into the softmax for the video indexed $j$ for a particular user $u$ is simply $u \cdot v_j$ over the distribution $V$ of all videos. That is, the final layer is performing the operation
$$\text{softmax}(\mathbf{v}_U); \quad\mathbf{v}_U = [u^\top v_0, u^\top v_1, \dots u^\top v_{|V|}]$$
So similarly to classifiers based on embedding methods, I'm making an educated guess that at some point, you will need to make that explicit $u \cdot v_j$ computation during the forward pass, so at that point, you should be able to get $v_j$ explicitly.


How much extra sea water is needed?

Question: We might call this the "Noah's Ark" calculation, but in the movie Waterworld (1995) they have the icecaps melting and take poetic license making the ~$220$ feet or so of sea water (one estimate I've seen – of how much the ocean would rise if all ice was melted) into approximately $27,000$ feet deep of water.  (Everest is $29,035$ feet and the island in the movie looked to be maybe ~$2,000$, so let's make it a nice even $27,000$ estimate.)
Given the circumference of the earth at sea level as it is today, and increasing the radius out $27,000$ feet, and making as many assumptions as needed (like the volume of all land and structures above sea level today) what is the cubic foot measurement of the additional water needed?
Answer: It is a reasonable assumption to model the earth as an oblate spheroid. An oblate spheroid has two radii, the major axis $a$ and the minor axis $b$, and has volume $\frac{4}{3}\pi a^2b$.
According to Wikipedia, for the Earth we have $a \approx 6378.13$ km and $b \approx 6356.75$ km, giving a volume of approximately $1.083204 * 10^{12}$ km$^3$.
$27000$ feet $\approx 8.23$km, and Everest is pretty near the equator, so the "flooded Earth" would have $a_f \approx 6386.46$ km.
Presumably the "flooded Earth" would have a similar flattening ($= \frac{a-b}{a}$) to the normal Earth, giving $b_f \approx 6365.05$ km.
This gives a volume of the flooded Earth of approximately $1.087454 * 10^{12}$ km$^3$.
The difference between the volumes, i.e. the volume of water, is $0.00425 * 10^{12}$ km$^3 = 4.25$ billion cubic kilometers $\approx 1.5 * 10^{20}$ cubic feet.
Comment: This makes some sense only all of the earth was just see. Obviously, some quantity such as the altitude distribution must come into the equation.
Comment: Frankly, I picked this one based on "oblate spheroid", and I guess someone could reduce via "altitude distribution" if one wanted to.  Thanks to both answers (at time of bounty expiration), although I think you're not supposed to say thanks.
Answer: Since $27000$ feet ($\approx 8200$ meters) is negligible against the radius of the Earth. So we can simply approximate the additional water volume as surface times height, i.e.
$$\tag1 V\approx 8200\,\mathrm m\times 5.1\cdot 10^8\,\mathrm{km}^2\approx4.2\cdot 10^9\mathrm{km}^3.$$
That is: If all is at Sea level. If - as other extreme - we assume that all land masses ($<30\,\%$) are above even the new see level, the estimate gets lowered accordingly to
$$\tag2 V=0.7\times 4.2\cdot 10^9\mathrm{km}^3\approx 2.9\cdot 10^9\mathrm{km}^3.$$
The first assumption is certainly closer to the reality than the second (relatively few parts of the land masses reach even half the Everest height), i.e. the result should be pretty much closer to $(1)$ than to $(2)$.
Then again, didn't Mr Costner dive down to a sunken city? Even if he can breathe with his gills, it would take four kilometers to reach even a high-levelled city like La Paz from the water surface.
Comment: Yes.  What *surely* must have happened is the ice caps melting causes massive weight redistribution and tectonic reconfiguration such that all exposed land subsides, and all the sea trenches are filled and current sea levels +220' would: a:) cover the earth all except for at least one Island, b.) make it such that he could reasonably dive to Denver (the underwater city in the movie), and c.) this would explain why there is no real weather in the movie.  A relatively shallow sea worldwide, and no mountains, you'd have no major currents\storms.  It could happen....  ; )

How much extra sea water is needed?


If $M$ isn't Noetherian, $M$ has a submodule maximal with respect to being not finitely generated.

Question: I'm answering this question:

Let $M$  be a module. Show that if  $M$ is not Noetherian then $M$ has a submodule $N$ such that $N$ is not finitely generated but $A$ is finitely generated whenever $N < A ≤ M$.

The solution starts as follows (I'm following a given solution):
Let $Y$ be the set of non-finitely-generated submodules of $M$. If $(N_α)$ is a chain in $Y$ then $Q= \bigcup_αN_α $ is in $Y$, else $Q$ is f.g., which implies $Q=N_α$ for some $α$, whence $N_α$  is f.g., contradiction.
I don't understand why if $Q$ is f.g., then $Q=N_α$ for some $α$? Am I missing some fact?
Thanks!
Comment: each generator of Q will be in some N_α. consider chain
Comment: @user26857 if $M$ is not finitely generated, take $N=M$ (there is no such $A$ as in the second part of the claim so this works).
Comment: @Simone indeed: the formulation is logically correct, but ever so slightly tricky.
Answer: By definition of union, an element $x\in M$ belongs to $\bigcup_\alpha N_\alpha$ if and only if it belongs to some $N_\alpha$.
If $Q=\bigcup_\alpha N_\alpha$ is f.g., then choose a finite family $\{x_1,\dots,x_n\}$ of generators of $Q$. For any $i\in\{1,\dots,n\}$, there exists $N_i\in\{N_\alpha\}_\alpha$ such that $x_i\in N_i$. Since your modules are linearly ordered, you can find a permutation $\sigma:\{1,\dots,n\}\to\{1,\dots, n\}$ such that
$$N_{\sigma(1)}\leq\ldots\leq N_{\sigma(n)}.$$
This shows that $x_1,\dots,x_n\in N_{\sigma(n)}$, so that $Q\subseteq N_{\sigma(n)}$.
On the other hand, it is clear that $N_{\sigma(n)}\subseteq Q$, hence $Q=N_{\sigma(n)}\in\{N_\alpha\}_\alpha$.
Comment: @user26857 well, in the question they are taking a chain... which means that the modules are already ordered. Why don't you want to assume their labels are ordered? I see no restriction in that...
Answer: A chain $(N_\alpha)_{\alpha\in A}$ of submodules always has the property that, given a finite subset $\{x_1,x_2,\dots,x_n\}$ of $Q$, then there exists $\alpha$ such that $\{x_1,x_2,\dots,x_n\}\subseteq N_\alpha$.
This is clear for $n=1$; suppose it is for subsets having $n$ elements. Suppose $\{x_1,x_2,\dots,x_n,x_{n+1}\}\subseteq Q$ and take $\alpha$ and $\beta$ such that $\{x_1,x_2,\dots,x_n\}\subseteq N_\alpha$ and $x_{n+1}\in N_\beta$.
Since we're given a chain, either $N_\alpha\subseteq N_\beta$ or $N_\beta\subseteq N_\alpha$. In the first case $\{x_1,x_2,\dots,x_n,x_{n+1}\}\subseteq N_\beta$, in the second case $\{x_1,x_2,\dots,x_n,x_{n+1}\}\subseteq N_\alpha$.
This in particular proves that $Q$ is a submodule, because we just need to consider two element subsets of $Q$.

You want to apply Zorn's lemma, so you want to show that any chain of nonfinitely generated submodules has an upper bound; the union is a good candidate, of course.
So, let $(N_\alpha)_{\alpha\in A}$ be a chain in the family $\mathcal{Y}$ of nonfinitely generated submodules of $M$ and set $Q=\bigcup_{\alpha\in A}N_\alpha$.
If $Q$ were finitely generated by $\{x_1,x_2,\dots,x_n\}$ and $\{x_1,x_2,\dots,x_n\}\subseteq N_\alpha$, then $Q\subseteq N_\alpha$, so $Q=N_\alpha$.
This is a contradiction to the hypothesis that $N_\alpha$ is not finitely generated.


StructureMap Plugins - easier way?

Question: Let's say you have an interface of IModel that takes a pair of generics ...
public interface IModel<TOne, TTwo>
{
     TOne ConvertToOne(TTwo two);
     TTwo ConvertToTwo(TOne one);
}

and a class that implements this
public class OneTwo : IModel<SomethingOne, SomethingTwo>
{
   SomethingOne ConvertToOne(SomethingTwo two)
   { //zomg! nothing exciting!
   }

   ...
}

Nothing overly fancy.  In my mapping configs, I have a list that looks kind of like this ...
For<IModel<SomethingOne, SomethingTwo>>().Use<OneTwo>();
For<IModel<SomeOne, SomeTwo>>().Use<AnotherClass>();

and so on.  Based on DRY, I feel like this is the hard way to do this (there's 7 of them now, soon to be 20 or so).  Anyway to do this "more better"?
Answer: You could try this... it might work.
ObjectFactory.Initialize(x =>
{
    x.Scan(scan =>
    {
        scan.AssemblyContainingType<Something>();
        scan.ConnectImplementationsToTypesClosing(typeof(IModel<,>));
    }
}

StructureMap Plugins - easier way?


Sine-wave Phase shift

Question: This is more of a doubt rather than question. Just correct me if I am wrong, tks
So i have this question, (not exactly maths but my doubt is related to calculation understanding)

The question here is the phase shift column when they say 1/(4f) are they saying (1/4)*360? which ofcourse mean 90 degrees.. I deduce this cause it is a sine wave am I right? that is my question and doubt.
Answer: f here means frequency, or rather 2pif is frequency according to the bottom of the table. So, f=440 for concert A, which is 440 Hz=cycles per second, or 2pi*440 times the frequency of a normal sine wave (which has period 2pi, not 1).
EDIT: I don't know QAM exactly, but I know what's going on with the waves.
I think the frequency is fixed in the original signal. So the phase shifts are just fractions of the original frequency. Look at the points $(\frac{n\pi}{4}, sin(\frac{n\pi}{2}))$ on a sine wave (see Wolfram Alpha), then try and change the frequency of the sine wave and see what happens. If you double the frequency, the phase shifts should also be multiplied $sin(2\pi t+\pi /2) \rightarrow sin(2 \pi ft+\pi f/2)$. So if you always shift by $\frac{n}{4f},$ your phase shift will be the absolute time shift of $\frac{n}{4}$, no matter the original frequency. Look up radians to degrees conversions.
If that's what you're expecting, good. Otherwise there's some missing information.
Comment: are you familiar with QAM? cause now your answer is even more confusing, updated with the full question, i just want to know if it is 90 degrees or 180 or 270 pls chk..tks
Comment: No, but I'll try to decipher. By period 1, I think they mean after 1 second, since they adjusted the units to Hz.
Comment: So, yeah, they mean a quarter of a second shift. The waves all seem to have a frequency of 1 Hz, so the shifts are (0, 1/4, 3/4, 0, 1/2, 1/2, 3/4, 1/2).
Comment: yes that is what I tot as well... tks

Sine-wave Phase shift


Where is links__system_main_menu defined?

Question: I searched for links__system_main_menu, but just find usages of this theme. Where is it defined?
Answer: Drupal 7 core doesn't actually define this function.
links__system_main_menu is a theme hook pattern of the form [base hook]__[context]. When links are themed with theme('links__system_main_menu', $vars), theme() will search for and use theme_links__system_main_menu() if it has been defined. If not, it will use theme_links().
See theme() for the official documentation of this behavior. Chapter 3 of Drupal 7 Module Development does an excellent job of explaining this and provides several examples.
BTW, the same principle applies to template files. If, for example, we call theme('node__article__1', $vars), theme() will search for a node--article--1.tpl.php file, and then for node--article.tpl.php, finally falling back to node.tpl.php if neither of them are defined.
Answer: theme_links__system_main_menu() is not currently defined from Drupal, but Drupal will use MYTHEME_links__system_main_menu(), if you define it in your theme.
function MYTHEME_links__system_main_menu($variables) {
  $html = "
\n";
  $html .= "
\n";

  foreach ($variables['links'] as $link) {
    $html .= "
".l($link['title'], $link['path'], $link)."
";
  }

  $html .= "
\n";
  $html .= "
\n";

  return $html;
}

You can find some more info on http://drupal.org/node/1033442#comment-5076932.


how to show links inside a block

Question: function custom_block_view($delta = '') {
$brands = $brand->getChildrenCategories();
      foreach ($brands as $node) { #print_r($node);
        $items[] = array(
            'data' => t($url = Mage::getUrl($brand->getUrlPath()).'.html')
            #'data' => t($node['name'])
        );
      }

$block['content'] .= theme('item_list', array(
          'items' => $items
              ));

    }

I use this code to display items in a block. I want this to be a link but was not able to achieve it. The output is shown below:
Comment: Please use l() function instead of t().
Answer: You need to use the l() function in place of t() (which is a string translation function):
$url = Mage::getUrl($brand->getUrlPath()).'.html';
$link = l('Link Title', $url);

If the URL is external you'll also want to provide that information in the $options parameter:
$link = l('Link Title', $url, array('external' => TRUE));

Comment: i really feel intimidated.It was so simple i couldn't find it while googling. :(. Thanks Clive

how to show links inside a block


TextBox ScrollToHorizontalOffset will not scroll after text is long enough

Question: I have a textbox (textBox1 as an example) to which i'm periodically appending a character (every second or so). I wish to make it so that when the text gets too long to fit in the textbox the overflow will actually go towards the left of the textbox even when it's not focused instead of the normal behaviour which is to the right, this way the last character will always be shown.
The way I've done it is when I'm adding the character i'm also doing:
textBox1.ScrollToHorizontalOffset(textBox1.GetRectFromCharacterIndex(textBox1.Text.Length).Right);

This works nicely until the length of the text gets long enough. After this point scrolling will just stop and the current left overflow will remain, but new overflow will go to the right of the textbox.
For testing I'm writing the current text's length and textBox1.GetRectFromCharacterIndex(textBox1.Text.Length).Right to console on every update:
...
Length: 22
Rect.Right: 81.99
Length: 23
Rect.Right: 85.4
Length: 24
Rect.Right: 88.81
Length: 25
Rect.Right: 91.41
Length: 26
Rect.Right: 91.41
Length: 27
Rect.Right: 91.4099999999999
Length: 28
Rect.Right: 91.4099999999999
Length: 29
Rect.Right: 91.4099999999999
Length: 30
Rect.Right: 91.4099999999999
...
Length: 47
Rect.Right: 91.4099999999999
Length: 48
Rect.Right: 91.4099999999999
Length: 49
Rect.Right: 91.4099999999999
Length: 50
Rect.Right: 91.4099999999999
Length: 51
Rect.Right: 91.4099999999999
Length: 52
Rect.Right: 92.88
Length: 53
Rect.Right: 94.8199999999999
Length: 54
Rect.Right: 96.29
Length: 55
Rect.Right: 98.2299999999999
Length: 56
Rect.Right: 99.7
Length: 57
Rect.Right: 101.64
Before Text.Length is 25 the textbox is still wide enough to fit everything. After this point the text doesn't fit anymore and the scrolling works up until the length is 52.
Answer: That behaviour is odd -- I reproduced the same.
I got the effect for which you are looking by instead using
textbox1.ScrollToHorizontalOffset(double.MaxValue);

Since you want to scroll all the way right, there is no harm in passing a value greater than the actual location of the character.
Answer: All of the above did not work reliably for me. While doing something else, I stumbled across this approach (using selection highlight). TB is the TextBox, ofs is the character index for the desired offset.
TB.Focus();   //must be used
TB.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
TB.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left;
TB.Select(0, ofs);   //select up through desired offset
TB.Select(0, 0);     //turn off selection

...hope this helps!


Can you coma-delimit an "Access-Control-Allow-Origin" header?

Question: I am trying to solve a CORS problem. We have an endpoint that supplies hmtl to two different domains. Most things I have read seem to say that you can either add a single domain to allow access, or use a wildcard. I don't want to use a wild card so can I just add
<code><httpProtocol>
 <customHeaders>
   <add name="Access-Control-Allow-Origin" value="first.domain.net,second.domain.net" />
 </customHeaders>
</code>

under the system.webserver section in my web.config?
Comment: If you want to support multiple domains, you need to do it in code and pay attention to the request's Origin header.  If it's one of your allowed domains, you send that back as the ACAO header; if it isn't, then you don't.  You won't be able to do this with configuration.
Answer: No, only a single Origin may be specified, see MDN's documentation of the header.


Mysql: Date Comparisons and a Join

Question: I'm trying to run a query to pull available rooms and it joins a reservation table to see available rooms for a given period(start and end date).  I'm drawing a blank here and I think this is a pretty simple query, I just can't think of the best way to create it.
What I have so far that needs to be fixed
   SELECT *
     FROM room
LEFT JOIN reservation ON room.id = reservation.room_id
    WHERE reservation.id is null or
          :startdate > reservation.enddate or
          :enddate   < reservation.startdate

My above query will return results for rooms with multiple reservations that may satisfy the where clause even though there could be reservation within the date range.
Answer: I would do this using a not exists predicate which I find intuitive:
SELECT *
FROM room
WHERE NOT EXISTS (
    SELECT *
    FROM reservation
    WHERE room.id = room_id
    AND
      :startdate < enddate
    AND
      startdate < :enddate)

The logic says return all rooms for which there doesn't exists any related reservations between the given dates.
Comment: actually, your right, after testing I realized it works.  Thanks for your input.
Comment: I didn't think to use the "not exists" predicate but this query will still return a room that has multiple reservations and one satisfies the where clause even though a reservation might conflict with the given start and end dates.
Comment: @Ralph Oh right, seems I have the logic wrong... hang on
Comment: I do appreciate the effort but this will still return results that shouldn't be returned.  According to your query and mine, If there is a reservation within the date range and also another reservation in the future that satisfies the where clause, it will still list the room as being available now.
Comment: @Ralph Could you gives some example? The logic seem sound to me and when I test it all rooms that have reservations that overlap with the range are excluded. See this example: http://www.sqlfiddle.com/#!6/a64b2/2

Mysql: Date Comparisons and a Join


libGDX GWT compile error that appears to be related to com.badlogic.gdx.utils.AtomicQueue

Question: I have created a little game using libGDX and I try to compile the html project using GWT compile.
The error I'm getting is the following:
<code>No source code is available for type com.badlogic.gdx.utils.AtomicQueue<T>; did you forget to inherit a required module?
</code>
Any ideas?
Comment: Maybe also Push this to libgdx issues
Answer: AtomicQueue is not compatible with GWT, you'll have to use another type of queue or not target GWT.


Spring not loading controller and no console errors

Question: I have an existing webapp written in Struts 1.2 and i'm trying to use Spring 3-Rest to expose functionality as web services.
I've run into a basic problem that I am unable to wrap my head around
This is my web.xml stripped of all struts stuff.
   <?xml version="1.0" encoding="UTF-8"?>
   <display-name>Test</display-name>
   <servlet>
    <servlet-name>app</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
     <servlet-name>app</servlet-name>
     <url-pattern>/*</url-pattern>
    </servlet-mapping>

My app-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <mvc:annotation-driven/>
    <context:component-scan base-package="com.base.rest">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/JSP/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

</beans:beans>

I've got a basic controller in com.base.rest
package com.base.rest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class DummyController {

    @RequestMapping(value="/dummy",method=RequestMethod.GET)
    public String doSomething(){
        System.out.println("Dummy");
        return "hello";
    }
}

I've got hello.jsp in WebRoot/JSP folder that just prints Dummy
When deployed on tomcat 7, I get this
INFO: Initializing Spring FrameworkServlet 'app'
without any error on the console.
I have removed all conflicting jars from build path and just have the spring dist and commons-logging-1.1
I get a 404 when accessing server/Test/dummy
Can anyone point out what stupid mistake I am doing?
Answer: Change your dispatcher servlet mapping to this and give it a try.
<servlet-mapping>
 <servlet-name>app</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>

Also, in the InternalResourceViewResolver declaration the
<beans:property name="prefix" value="/JSP/" />

The value should point to the  WEB-INF/JSP location.


A question on total variation of signed measures

Question: This is a variant on a problem from Royden's Real Analysis:
Let $\nu$ be a signed measure on a measurable space $\left\langle X,\mathcal{M}\right\rangle$, and let $$\Sigma:=\left\{{\left.\sum_{k=1}^{n}{\left|\nu{\left(E_k\right)}\right|}\ \right|}\ E_k\in\mathcal{M}\hspace{4pt}\forall k=1,2,\dots,n;n\in\mathbb{N}\right\}.$$  We define the total variation of $\nu$, denoted by $|\nu|$, as follows:  given the Jordan decomposition $\nu=\nu^+-\nu^-$, $|\nu|:=\nu^++\nu^-$.  I'm trying to prove that $|\nu|(X)=\sup\left(\Sigma\right)$.  I have $\mathrm{LHS}\leq\mathrm{RHS}$:  using a Hahn decomposition $X=A\sqcup B$ with $A\hspace{4pt}\nu$-positive and $B\hspace{4pt}\nu$-negative, I've proven that $|\nu|(X)=|\nu(A)|+|\nu(B)|\in\Sigma$, and hence $|\nu|(X)\leq\sup\left(\Sigma\right)$.  I'm not sure quite how to prove the opposite inequality.  I've tried to show that $|\nu|(X)$ majorizes $\Sigma$, but not gotten anywhere with it.  Any suggestions would be appreciated.
Comment: how we define $\nu^+$ and $\nu^-$? I'm asking this because in my book we define $\nu^+(E) \overset{def}{=} \dfrac{|\nu|(E)+\nu(E)}{2}$ and $\nu^-(E) \overset{def}{=} \dfrac{|\nu|(E)-\nu(E)}{2}$ for all $E \in \mathcal{M}$ and we defined $|\nu|$ as $|\nu|(E)=\displaystyle\sup \sum_{k=1}^{\infty} |\nu(E_n)|$ where supremum is by all decomposition of $E=\bigsqcup_{n=1}^{\infty}E_n$ where $E_n \in \mathcal{M}.$
And your way is opposite, but I can't see how you  define $\nu^+$ and $\nu^-$
Comment: Let $X=A\sqcup B$ be a Hahn decomposition of $X$, where $A$ is a maximal $\nu$-positive set. We define $\nu^+:=\nu|_A,\nu^-:=-\nu|_B$.
Comment: So, really, we define $\nu^+(E):=\nu\left(E\cap A\right)$ and $\nu^-(E):=-\nu\left(E\cap B\right)$ in the above Hahn decomposition.
Answer: I've figured out the opposite inequality:
let $\left\{E_k\right\}_{k=1}^{n}$ be an arbitrary sequence of measurable sets, and assume without loss of generality that $E_i\cap E_j=\emptyset\hspace{4pt}\forall i\ne j$.  Let $X=A\sqcup B$ be a Hahn decomposition of $X$ as above, with $A$ $\nu$-positive and $B$ $\nu$-negative.  Then $\forall k=1,2,\dots,n$, we have that $ E_k=\left(E_k\cap A\right)\sqcup\left(E_k\cap B\right)$.  Hence $\sum_{k=1}^{n}{\left|\nu\left(E_k\right)\right|}=\sum_{k=1}^{n}{\left|\nu\left(E_k\cap A\right)+\nu\left(E_k\cap B\right)\right|}\leq\sum_{k=1}^{n}{\left|\nu\left(E_k\cap A\right)\right|}+\sum_{k=1}^{n}{\left|\nu\left(E_k\cap B\right)\right|}=\sum_{k=1}^{n}{\nu^+\left(E_k\cap A\right)}+\sum_{k=1}^{n}{\nu^-\left(E_k\cap B\right)}$.  Now $\bigcup_{k=1}^{n}{\left(E_k\cap A\right)}\subseteq A$ and $\nu^+\left[\bigcup_{k=1}^{n}{\left(E_k\cap A\right)}\right]=\sum_{k=1}^{n}{\nu^+\left(E_k\cap A\right)}$, so by monotonicity, $\nu^+\left[\bigcup_{k=1}^{n}{\left(E_k\cap A\right)}\right]=\sum_{k=1}^{n}{\nu^+\left(E_k\cap A\right)}\leq\nu^+(A)$.  Similarly, $\nu^-\left[\bigcup_{k=1}^{n}{\left(E_k\cap B\right)}\right]=\sum_{k=1}^{n}{\nu^-\left(E_k\cap B\right)}\leq\nu^-(B)$.  Hence we have $\sum_{k=1}^{n}{\left|\nu\left(E_k\right)\right|}\leq\nu^+(A)+\nu^-(B)$.  But $\nu^+(A)+\nu^-(B)=\left|\nu\right|(X)$, so we have that $\sum_{k=1}^{n}{\left|\nu\left(E_k\right)\right|}\leq\left|\nu\right|(X)$.  Hence $\left|\nu\right|(X)$ is an upper bound for $S$.  $\therefore\left|\nu\right|(X)\geq\sup(S)$, as the supremum is the least upper bound.  $\therefore\left|\nu\right|(X)=\sup(S)$.  $\blacksquare$