text:
Q: Is the ground state of a QFT always a pure state? And excited states are mixed? I am studying entanglement entropy.
It's fullfilled for any local quantum system that the entanglement entropy of a region $A$ in a highly mixed state is extensvie,
$$ S_A \sim \frac{\text{Vol}(A)}{\epsilon^d} $$
where $\epsilon$ is the length between sites (or the UV cutoff for a regularized QFT). This is because
$$S_A=\log[\text{dim}(\mathcal{H}_A)]$$
where $\mathcal{H}_A$ is the Hilbert space of the degrees of freedom in $A$, and the dimension scales as the number of degrees of freedom per site by the number of the sites, $\sim \exp(\text{Vol}(A)/\epsilon^d)$.
On the other hand, for a pure state the entanglement entropy is not extensive, since $S_A=S_B$, where $B$ is the complement of $A$. In fact it is proven that it follows an 'area law'.
An usual intuituve argument for this area law is that to compute the entanglement entropy we count the pairs entangled in both sides of the boundary of $A$. Since the theory is local, the most entangled pairs will be those who lay at $\sim\epsilon$ of the boundary, while the further sites won't count for the entropy. So this way we have that the EE must scale as $\text{Vol}(\partial A)$.
My problem is that I don't know if I am understanding why are we counting all the states un $A$ in one case and only the states near to the boundary in the other.
The reason I found is that in the case of the pure state we are talking about the vaccum, the system is in the ground state of energy and a site can only see what is near around it, since the interactions are local.
But if we excite the system (for example, if we consider a thermal state $\rho = e^{-\beta H}/\text{tr }e^{-\beta H}$, which is a mixed state), the system has enough energy to go beyond the local behavior and then we need to consider all the sites for the EE.
Am I right with that?

A:
It's fullfilled for any local quantum system that the entanglement entropy of a region A in a mixed state is extensvie,

Could you give a reference, please?
The entanglement entropy measures not just the entanglement but also the classical entropy. It is a measure of entanglement, only if you start with a pure state and then trace over some subsystem. (It's been a while since I read the literature on this, but)IIRC, when people talk about mixed (thermal) states, there is a classical/thermal entropy of your mixed state that scales extensively -- while the entanglement (described using some measure other than the naive entanglement entropy) might scale differently. IMHO, I would expect that to scale with an area law, just like you said. The entanglement entropy is a sum of those two, and it looks like the "leading" behaviour is extensive.

On the other hand, for a pure state the entanglement entropy is not extensive, since SA=SB, where B is the complement of A. In fact it is proven that it follows an 'area law'.

I don't see how one can say this for a generic pure state. This is believed to hold (strong evidence adding up) only for ground states of local field theories.
Unless you have a homogeneous (unbroken translational symmetry) and isotropic+boost-invariant (unbroken Lorentz symmetry), there are a lot of qualifiers before you talk about scaling of entanglement entropy. EG: where your region sits, it's shape, the frame you're sitting in and then its size. The vacuum of a relativistic field theory respects all these symmetries and hence, is convenient to consider.
For generic pure states (eg: localized lump as an excitation on top of the vacuum) the area scaling will of course be affected when the boundary of your "expanding region" crosses the lump. So you cannot talk about a general monotonic "scaling behaviour" for such states, even if they're pure.
Thus, to my understanding, it is difficult to make any definitive statements about the zoo of excited (albeit pure) states. Once can always consider one particular state and compute entanglement for that case, but I don't see how that will generalize to statements about other states.


text:
Q: Maven Company POM name I want to set up a (master/parent) company pom that will be used for projects. Now what is the most common name approuch for this?
Name the artifact after the company name or is using an artifact like "pom" also good?
<groupId>com.company</groupId>
<artifactId>company</artifactId>
<version>1.0</version>

<groupId>com.company</groupId>
<artifactId>pom</artifactId>
<version>1.0</version>

Because you have to make a seperated VCS for it also. And when you go for the first option (company/company) that repository can't be used for anything else. Or making a branch (named: pom) will solve this? Maybe it's just better to make a new repo for the pom?
https://github.com/company/company.git
https://github.com/company/pom.git

A: A couple of points here:

*

*don't call it a 'master', master is a common shortening for 'aggegration-pom'. What you want is a parent.

*It is good practice to:

*

*include the word -parent in your parent name

*use the realm/scope of the parent in the name (company in your case)

*also: the artifactId should be understandable by itself

*give single version numbers (1 or 10 or 15 instead of 1.0) because you will seldom if ever use a bugfix version

*use a single repository for your parent (yes, it is quite empty). But if it has a separate lifecycle, it should have a separate repository.

so, don't call it pom or company, because both is misleading:
<groupId>com.company</groupId>
<artifactId>company-parent</artifactId>
<version>1</version>

If your company does other projects besides maven projects, it might also make sense to name the repository (not the artifactId) company-maven-parent.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RecyclerView : One OnClickListener over various items? I'm using a RecyclerView with 2 holder types (Title and Item) to display the activity's content. The quantity of Items per Title is undefined.
Just like this :
Title
-Item
-Item

Title
-Item

Title
-Item
-Item
-Item

I'm looking for a clue. How can I set an OnClickListener on each group (Title + Items), so that the "OnClick gray wave effect" browse the entire selected group without interruption?

A: I believe that to achieve this you will need to put the whole group inside a single row (Title + n Items) and handle the views programatically. You can give the parent layout android:background="?android:attr/selectableItemBackground" to achieve the ripple effect when clicked (Be sure to give it an onClickListener or at least set android:clickable="true").
What you can do is, inside each Title view, you can add your items in a RecyclerView inside a NestedScrollView and disable its scrolling using recyclerView.setNestedScrollingEnabled(false), so it will give you the same result.

A: if you want OnClickListener in each items or put them in Linearlayout and give it id  you need to create interface and implement it in the screen you want to show the recycleview adapter  and use it in adapter
public interface OnLevelClick {

void onTitleClick(int pos);
void onItem(int pos);
}
    OnLevelClick onLevelClick;
    public LevelAdapters(Activity activity, ArrayList<Items>
    arrayListItems, OnLevelClick onLevelClick) {
    this.arrayListItems = arrayListItems;
    this.onLevelClick = onLevelClick;
    this.activity =activity;

}

     @Override
   public void onBindViewHolder(final MyViewHolder holder, final int
   position) {
      holder.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
           onLevelClick.onTitleClick(position);

           }
          ////   or
              holder.linear.setOnClickListener(new
             View.OnClickListener() {
            @Override
            public void onClick(View view) {
           onLevelClick.onTitleClick(position);

           }

in the activity implement
       Activity implements OnLevelClick{
    levelAdapter = new
     LevelAdapters(getActivity(),savedLevelList,this);
    reLevel.setAdapter(levelAdapter);
          @Override
    public void onNumClick(int pos) {

     Log.d("Title",arraylist.get(po0s).getTitle());

    }

}


text:
Q: Flex Channel Security Error while logging into two different domains from single app i need to connect to two different domains from a single flex application.
the problem is the domain other than the current hosted domain is unable to login.
letz say i hosted the application at LOCAL server. im able to login to the local server .
From the existing application i need a login to the MAIN server too. The problem comes up here.
flash security is not allowing login to MAIN server.
in crossdomain we allow-access-from MAIN server. but i want access to the MAIN server from LOCAL server.
is ther nything i need to put extra in crossdomain.xml ?
plz i need a solution!!
ThnQ
Sris

A: You need to put a crossdomain.xml on your "MAIN" server and allow-access-from "LOCAL"; you don't need to put a crossdomain.xml on the server where your SWF is hosted. The cross domain file is intended to be placed on a 3rd party server to indicate that SWFs hosted from particular domains have permission to access its services.
Another short explanation is here:
http://www.flexafterdark.com/docs/Flash-CrossDomain


text:
Q: Mudar cor do título da TabPage Alguém sabe como mudar a cor do titulo ta TabPage em C#?
Não a cor do texto da página inteira, só a do titulo da página (da Tab).

A: No Evento abaixo, incluir o seguinte codigo.
private void TAB_DrawItem(object sender, DrawItemEventArgs e)
{
    TabPage CurrentTab = TAB.TabPages[e.Index];
    Rectangle ItemRect = TAB.GetTabRect(e.Index);
    SolidBrush FillBrush = new SolidBrush(Color.White);
    SolidBrush TextBrush = new SolidBrush(Color.Black);
    StringFormat sf = new StringFormat();
    sf.Alignment = StringAlignment.Center;
    sf.LineAlignment = StringAlignment.Center;

    //If we are currently painting the Selected TabItem we'll
    //change the brush colors and inflate the rectangle.
    if (System.Convert.ToBoolean(e.State & DrawItemState.Selected))
    {
        FillBrush.Color = Color.Red;
        TextBrush.Color = Color.White;
        ItemRect.Inflate(2, 2);
    }

    //Set up rotation for left and right aligned tabs
    if (TAB.Alignment == TabAlignment.Left || TAB.Alignment == TabAlignment.Right)
    {
        float RotateAngle = 90;
        if (TAB.Alignment == TabAlignment.Left)
            RotateAngle = 270;
        PointF cp = new PointF(ItemRect.Left + (ItemRect.Width / 2), ItemRect.Top + (ItemRect.Height / 2));
        e.Graphics.TranslateTransform(cp.X, cp.Y);
        e.Graphics.RotateTransform(RotateAngle);
        ItemRect = new Rectangle(-(ItemRect.Height / 2), -(ItemRect.Width / 2), ItemRect.Height, ItemRect.Width);
    }

    //Next we'll paint the TabItem with our Fill Brush
    e.Graphics.FillRectangle(FillBrush, ItemRect);

    //Now draw the text.
    e.Graphics.DrawString(CurrentTab.Text, e.Font, TextBrush, (RectangleF)ItemRect, sf);

    //Reset any Graphics rotation
    e.Graphics.ResetTransform();

    //Finally, we should Dispose of our brushes.
    FillBrush.Dispose();
    TextBrush.Dispose();
}


text:
Q: how do you stub a local variable in an rspec controller test I've just implemented OmniAuth (using Ryan Bates' Screencast http://asciicasts.com/episodes/235-omniauth-part-1) and am writing Rspec tests for the functionality and have ran into trouble testing the authentifications#create action. I'm at quite a loss as to how to test this one -- in particular how to stub the local variable omniauth. No matter what I try I keep can't get any tests to work.
Taking a cut down version of the action, how would you test that a new is called on User for example

#cut down version of the authentifications controller code I am attempting to test

  def create
    omniauth = request.env["omniauth.auth"]
    authentification = Authentification.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
    ....
    user = User.new
    ....
  end

#example test

    it "should create a new user" do
        subject.stub_chain(:request,:env) {{"omniauth.auth" => {'provider' =>1, 'uid' => 2}}}
        User.should_receive(:new)
        post :create
      end

A: I Did that :
class SessionsController < ApplicationController
  def create
    @user = User.find_by_auth_hash(auth_hash)
  end

  def auth_hash
    request.env['omniauth.auth']
  end
end

describe SessionsController do
  it 'should allow login' do
    controller.stub!(:auth_hash).and_return({'provider' => 'twitter', 'uid' => '1234'})
    get :create, :provider => 'twitter'
    assigns(:user).should_not be_nil
  end
end

Hope that helps.


text:
Q: AngularJS adding Directive dynamically to DOM with JavaScript I am developing a small chat application using Angular 1.x and Socket.io. There is a list showing available people for chatting on the screen. When clicked on a person, in the controller a chat function called. I pass the required person info (id, socket_id etc.). Then I create a chat box like facebook chat box with directive dynamically and add to dom. Directive has an isolated scope. This is code to add directive to DOM when clicked on a person:
temp = {
'name' : driver.name,
'surname' : driver.surname,
'image' : driver.image
};
var divElement = angular.element(document.querySelector('.chat-container'));
var appendHtml = $compile('<chat-box receiver="' + temp +
       '"  id="' + driver.id + '" visible="true"></chat-box>')($scope);
divElement.append(appendHtml);

And the directive code:
.directive('chatBox', function($timeout) {
    chatboxes = [];
    return {
        restrict : 'EA',
        templateUrl : 'templates/chat.box.tpl.html',
        replace : true,
        scope : {
            receiver : '@',
            visible : '@',
            id : '@'
        },
        link: function(scope, element, attrs) {

        },
        controller : function($scope) {

            $scope.close = function() {
                $scope.visible = false;
            }
        }
    }
})

*

*Problem: I am facing problem getting object data (receiver = temp) in the directive and apply to view. How can I send an object data and handle in directive properly?

*Problem: After creating a chat box for a person, I want to prevent creating a second chat for the same person. How can I handle this?

A: In AngularJS, avoid raw DOM manipulation. DOM manipulation should be done only by directives:
<div class="chat-container">
   <chat-box ng-show="$ctrl.visible"
             receiver="$ctrl.temp"
             id="{{$ctrl.driver.id}}"
             on-close="$ctrl.visible = false">
   </chat-box>'
</div>

In the directive use one-time < binding to put objects in the isolate scope and use expression & binding to communicate a close event from the directive:
app.directive('chatBox', function() {
    return {
        restrict : 'EA',
        templateUrl : 'templates/chat.box.tpl.html',
        scope : {
            receiver : '<',
            onClose : '&',
            id : '@'
        },
        link: function(scope, element, attrs) {

        },
        controller : function($scope) {

            $scope.close = function() {
                $scope.onClose();
            }
        }
    }
})

In this case the visibility of the element is controlled by the ng-show directive.


text:
Q: How to compare the Date object in javascript I am trying to use the =>, =<, == comparison operators on the date object to determine if a document was created in the past 3 days then display new next to the title if true.
Right now I have:
var createdDate = new Date((ctx.CurrentItem.Created));
var threeDaysAgo = new Date((new Date()).valueOf() - 1000*60*60*24*3);

if (createdDate.valueOf() >= threeDaysAgo.valueOf())
                        {
                          then display *new*
                        }

In this case I turned the date into milliseconds to compare, but it doesnt work. Ive tried formatting the date in multiple different ways and then comparing... still doesnt work. I've also tried using .getTime(), and it doesnt work. When I change >= to <= then it displays new for all documents, even those created 10 years ago, so atleast I know the code is correct inside the if statement.
Thanks for the help!

A: Try like this:
var createdDate = new Date('2021-07-25T03:24:00');
var treeDaysAgo = new Date();
treeDaysAgo.setDate(treeDaysAgo.getDate() - 3);

After this this will evaluate to true:
createdDate >= treeDaysAgo

And if you change createDate to earlier, it will evaluate to false.
Maybe you have ctx.CurrentItem.Created in a format that is not suitable for Date construction.

A: The same issue was disscussed here: https://sharepoint.stackexchange.com/questions/166784/how-can-i-convert-the-format-ctx-currentitem-created

You could change the string with:
var datestring="2015/10/20 PM 06:09";
var dateparts=datestring.split(' ');//array
if(dateparts[1].length===2){//am or pm in second array element?
  dateparts.push(dateparts[1]);//move it to the end
  dateparts.splice(1,1);//take out the am/pm in the middle
}
var mydate=dateparts.join(' ');//make it one string
console.log(mydate);
console.log(new Date(mydate).toString());
console.log(new Date(mydate).toISOString());


text:
Q: Dynamic method name First of all sorry for the title, but i had no clue how i should name it.
Let's say i have it like that:
$lang = new lang;
$lang->setLanguage('en');
$string = $lang->get('Willkommen');

This would output Welcome for example.
But what i want is this:
$lang = new lang;
$lang->setLanguage->en
$string = $lang->get->Willkommen

As you thought, this should also output Welcome.
In order words, i want the same result, but without having to pass arguments to the instance.
I searched a long time now, but could not find out how i could do that.

A: Sounds like you're looking for the __get magic method.
class lang {
    var $language = 'en';

    function __get($prop) {
        if ($prop == 'Willkommen') {
            if ($this->language == 'en') return 'Welcome';
            else if ($this->language == 'fr') return 'Bonjour';
        }
    }

    function __set($prop, $val) {
        if ($prop == 'language') $this->language = $val;
    }
}

$lang = new lang();
echo $lang->Willkommen; // Prints "Welcome"
$lang->language = 'fr';
echo $lang->Willkommen; // Prints "Bonjour"

A: In php, dynamic access is with {} :
$key = 'Willkommen';
$lang->{$key};


text:
Q: Turn Circle by a specific angle (openGL) I like to turn the circle drawn with this class member:
void Scene1::Circle(float x_, float y_, float z_, float r){
    xx=r*cos(359 * PI/180.0f);
    xy=r*sin(359 * PI/180.0f);
    glBegin(GL_QUADS);
    for(int j = 0; j < 360; j++)
    {
        glVertex3d(xx+x_,xy+y_,z_);
        glVertex3d(x_,y_,z_);
        xx= r * cos(j * PI/180.0f);
        xy= r * sin(j * PI/180.0f);
        glVertex3d(xx+x_,xy+y_,z_);
        glVertex3d(x_,y_,z_);
    }
    glEnd();
}

by a specific angle. if i use
glRotatef()

it is somehow not working. I'd like the Circle to always show his surface to the cam, i want to use it as some sort of Comic-Sphere.
Can anyone Help me?

A: What you want to implement is a so called bill board. This is most easily achieved by setting the upper left 3×3 of the modelview matrix to identity.
If you insist on sticking with OpenGL matrix functions, use glGetFloatv(GL_MODELVIEW_MATRIX, m) to retrieve it, change the upper left 3×3 elements to identity and use glLoadMatrix(m) to put it back into OpenGL. Surround it with glPushMatrix, glPopMatrix to keep the effect local.


text:
Q: Energy transfer through damping When a damper is attached to a bridge, its tuned to the bridges natural frequency. I dont get how will that allow for maximum transfer of energy? And also how will heavily damped systems prevent energy from going back to the system? I thought energy is just lost with damping.

A: I'm not a structural engineer, but as I understand it, catastrophic collapses of bridges were often due to loading that caused the bridge to oscillate at its natural frequency. Dampers tuned to the natural frequency allow the oscillation energy to be safely dissipated as heat. The dissipated heat will not naturally flow back to the structure causing it to again oscillate (in violation of the second law of thermodynamics).
ADDENDUM
This responds to your follow up questions.
but I don't get how is energy transferred to the damper in the first place?
In a similar way as a shock absorber in the suspension of a car works. Without the shock absorber, the car would bounce up and down on its suspension springs at the natural frequency of the springs. The shock absorber is basically a cylinder with hydraulic fluid and the fluid absorbs the oscillation energy.
plus what has natural frequency to do with the amount of energy thats transferred?
Let's say the bridge is subjected to very strong, but intermittent, cross winds. The bridge may begin to oscillate if the frequency of the winds matches the natural oscillation frequency of the bridge structure. That's the only frequency that will cause the bridge to fail. So it only makes sense to design the damper so that it absorbs energy at that natural oscillating frequency. If the damper is too "stiff", it will not give at all and simply be another rigid part of the bridge structure.  If the damper is too "soft", it will simply oscillate along with the bridge and not dissipate any energy.
Hope this helps.

A: Disclaimer: I'm not a structural engineer, so in practice this may be different for bridges specifically.  This is more about the general nature of vibrations and damping.
When designing mass-spring damper systems (which you could model the bridge as a complex version of) the natural frequency of the system is a critical factor.  The damper system is designed to dissipate high amounts of energy at the natural frequency of the bridge.  This is because at the natural frequency, an undamped system, or a system with inadequate damping, will continue to increase in the amplitude of oscillations.  A very famous example is the Tacoma Narrows Bridge, where the wind travelling across the bridge oscillated it at the resonant frequency, and the damping in place was insufficient to dissipate enough energy.
Essentially, in each period of the periodic motion, if the dampers are unable to dissipate more energy than is added to the system, the total energy of the oscillations will continue to increase until something bad happens (like a bridge collapse).
The purpose of the dampers is to prevent the energy from staying in the bridge system, and instead dissipates it as other forms of energy (generally heat, possibly some sound).  The energy isn't completely gone, it just needs to be taken away from the bridge oscillations, so that the potential energy of the bridge due to oscillations doesn't resonate out of control.
Also note that I talked about "the" resonant frequency of the bridge; but in practice it would have multiple resonant frequencies; and possibly some resonances between parts that also need to be accounted for.  Treating the bridge like a simple mass-spring-damper system (as I've done here) is a good first approximation; but in practice it is more complex.


text:
Q: Get a key's value if another key has a certain value I'm trying to get data from an api that returns multiple items when called like the following
[{"rate":2.5,"price":123,"userAsset":{"userId":123,"userAssetId":123,"asset":{"assetId":notrelevant}},"isBeingPurchased":notrelevant},
{"rate":2.5,"price":123,"userAsset":{"userId":123,"userAssetId":123,"asset":{"assetId":notrelevant}},"isBeingPurchased":notrelevant}]

i want to get userId, userAssetId and price for items with a rate that has a value in a certain range
I tried doing something like this:
import numpy as np
import requests
# Get the info from the API
r = requests.get('https://myapi.com/shop')
# Convert the info to a dictionary
data = r.json()

# Get the rates from the dictionary

for value in data:
    rates = print(value['rate'])
    print(rates)

    # Get the info needed later for certain items with a specific rate
    for rates in np.arange(0.1, 2):
        user_asset_id = value['userAsset']['userAssetId']
        user_id = value['userAsset']['userId']
        relative_price = value['price']
        print(user_asset_id, user_id, relative_price)

However, this doesn't work and prints out all the userAssetId, userId and price instead of the ones with a specific rate value. I figured it's because of a problem with the for-loops but i don't know how to fix it


text:
Q: Is it considered bad practice in java for a package to contain both classes and sub-packages? Is it considered a bad practice in java to have a structure where some package/s contain both classes and sub packages? i.e :
com/
  domain/
     SomeClass.java
     AnotherClass.java
     model/
       Model1.java
       Model2.java
     somePackage/
        SomePackageClass.java

The other option being SomeClass.java and AnotherClass.java contained in third package

A: No it's normal structure and not a bad practice. You have different levels in the tree structure. If the class logically is best suited in the parent package then leave it there. If these two classes share a common role that differs them from the others then you can move them to a separate package.


text:
Q: Embed Tomcat with App in One Fat Jar I was hoping to combine/embed Tomcat and my web app as onejar aka fat jar but I'm not sure if its possible. Its possible with Jetty using the Maven Shade plugin and Winstone but I tried something similar with Tomcat 7 and could not get it to load properly. The goal is to be able to do something like: java -jar mywebapp.jar.
The problem is that Tomcat wants to load things from the file system and not from the classpath. That is you can embed Tomcat but it will expect your WAR files to be available as files.
I tried many of the techniques on previous SO Posts for embedding Tomcat 6 & 7. While I can get it embedded and started it can't access my app.
I guess one option is having the JAR on boot unzip itself so that AppBase and DocBase are files on the file system. I haven't tried that yet but will.
There is a duplicate of the question here that I finally found: Self-contained war file with Tomcat embedded? (please vote to close as duplicate)

A: I have no idea how I kept missing this but the Tomcat Maven Plugin now supports make an executable WAR:
http://tomcat.apache.org/maven-plugin-2.0/executable-war-jar.html
UPDATE if you need Tomcat 8 you need a special configuration. You must use the 2.0 version of the plugin as the 2.2 Tomcat 7 plugin will not work and you will need the third party plugin tomcat8-war-runner. Below I have attached the maven configuration you will need which also allow you to select the correct version of Tomcat 8 you want (tomcat.version property).
The Tomcat8 maven plugin is in a messy state and still hasn't been released (please go vote on jira and complain to them to finish it).
Finally one major caveat with this maven plugin approach is that the plugin pseudo embeds. That is your app will not be running in the same classloader as Tomcat and is actually deployed during initialization. There are pros and cons to this approach.
Spring Boot and this example from Oracle on the other hand will run Tomcat in the same classloader as your app (that is it is truly embedded I think).
    <plugin>
      <groupId>org.apache.tomcat.maven</groupId>
      <artifactId>tomcat7-maven-plugin</artifactId>
      <version>2.0</version>
      <configuration>
        <port>${tomcat.port}</port>
        <path>/</path>
      </configuration>
      <executions>
        <execution>
          <id>tomcat-run</id>
          <goals>
            <goal>exec-war-only</goal>
          </goals>
          <phase>package</phase>
          <configuration>
            <path>/</path>
            <port>${tomcat.port}</port>
            <attachArtifactClassifierType>war</attachArtifactClassifierType>
            <mainClass>org.apache.tomcat.maven.runner.Tomcat8RunnerCli</mainClass>
            <extraDependencies>
              <extraDependency>
                <groupId>com.nitorcreations</groupId>
                <artifactId>tomcat8-war-runner</artifactId>
                <version>1.0</version>
              </extraDependency>
            </extraDependencies>
          </configuration>
        </execution>
      </executions>
      <dependencies>
        <dependency>
          <groupId>org.apache.tomcat.embed</groupId>
          <artifactId>tomcat-embed-core</artifactId>
          <version>${tomcat.version}</version>
        </dependency>
        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-util</artifactId>
          <version>${tomcat.version}</version>
        </dependency>
        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-coyote</artifactId>
          <version>${tomcat.version}</version>
        </dependency>
        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-api</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-jdbc</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-dbcp</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-servlet-api</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-jsp-api</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-jasper</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-jasper-el</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-el-api</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-catalina</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-tribes</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-catalina-ha</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-annotations-api</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-juli</artifactId>
          <version>${tomcat.version}</version>
        </dependency>

        <dependency>
          <groupId>org.apache.tomcat.embed</groupId>
          <artifactId>tomcat-embed-logging-juli</artifactId>
          <version>${tomcat.version}</version>
        </dependency>
        <dependency>
          <groupId>org.apache.tomcat.embed</groupId>
          <artifactId>tomcat-embed-logging-log4j</artifactId>
          <version>${tomcat.version}</version>
        </dependency>
      </dependencies>
    </plugin>

A: I did a tutorial on embedded Tomcat JARs and wanted to create as small of a POM file as possible that would create an executable JAR. I didn't want any environment variables or superfluous dependencies - just the bare bones. Here's what I came up with:
POM configuation for Tomcat plugin
<?xml version="1.0" encoding="UTF-8"?>
<project>

  <!-- create an executable jar file example -->
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mcnz.maven</groupId>
  <artifactId>javawebapp</artifactId>
  <version>1.0-embedded</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

   <!-- Maven embedded Tomcat server example -->
   <build>
      <finalName>javawebapp</finalName>
      <pluginManagement>
           <plugins>
            <plugin>
               <groupId>org.apache.tomcat.maven</groupId>
               <artifactId>tomcat7-maven-plugin</artifactId>
               <version>2.1</version>
               <configuration>
                 <!-- context root for Java web apps -->
                 <path>/tutorial</path>
                 <!-- name of executable jar file -->
                 <finalName>executable.jar</finalName>
               </configuration>
            </plugin>
         </plugins>
      </pluginManagement>
   </build>
   <!-- end of embedded Tomcat server tutorial -->

</project>

Running the tomcat7 plugin with Maven
The maven command co create the embedded jar is as follows:
$ mvn clean install tomcat7:exec-war-only

Here is the project structure that maven creates when the command is run:

Running the JAR
And then I use the following command to run the JAR:
$ java -jar executable.jar

More information
Those are the basics. I posted a video on how to create an embedded Tomcat JAR as well for anyone interested in seeing all of the steps from start to finish.


text:
Q: Opening up part of a secured application without compromising the entire application There's a subset of users which will not have access to the system I'm implementing in the beginning but I need a mechanism for them to capture data for one specific part of the process.
An authorized user creates the original record for a Person with some basic details i.e. First name, last name etc.
I then create a 'DataRequest' record which has a unique guid and the external user is sent an email with a path which is effectively http://sampleapplication/Person/Complete?guid=xxxx
The external user adds additional details like Date of Birth, Eye colour etc, submits and saves to the DB. The DataRequest for that guid is then expired and cannot be accessed again.
The Complete action doesn't have any authorization as these external users do not have user accounts.
My preference is to force these users to use the system but at this stage I'm not sure it's practical.
Is this a bad practice?
Should I be implementing some additional security on this like a one time password / passcode contained in the email? Are there alternative approaches I should consider?

A: There's nothing wrong with opening up a section of your site to the public. Tons of websites have secured and unsecured sections. However, there's also nothing saying that you have to expose your secure site at all. You can create another site that merely has access to that change those records and make that site alone, public.
As far as securing the information of the user, passcodes by email are the invention of some developer somewhere with limited mental ability or a severe lack of sleep. If the link is only available by email (not discoverable by search engines and not easily guessable), then anyone with the link will also have the passcode, making the passcode to access the link redundant.
You should however log when the email is used to finish the record and then disallow further uses.


text:
Q: Use iPhone Camera's QR Code Scanner on Web App I have implemented a couple different QR code readers on my website to use with a mobile device.  None of them work as well as the iPhone native camera.
I'd love to use the native camera app to scan QR codes. However, when opening the camera through HTML Media Capture like
<input type="file" accept="image/*;capture=camera">

the native QR scanner isn't active.  My guess is that because the camera is opening to create a file, there's no need for the QR scanner to load.
Is there a way to:
1) click a link to exit the browser and open the native camera app on the iPhone?
or
2) get the QR scanner to be included in the camera when opening the camera with the HTML Media Capture or another method?

A: I think that it is not possible to do that. You should use a library that could detect QR code from a file/image that the user will take


text:
Q: Am I allowed to have one button with two actions in one for-loop? Is there any reason I shouldn't do this? I'm fairly new at programming iPhone so I just want to check that its not making my memory footprint really high for some reason or anything like that.
I'm creating buttons in a loop (one for each letter in a phrase) and then there may be up to about 100 instances of this code running simultaneously so if there's a problem with it it could be a big problem.
Thanks for the advice!
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:l];
CGRect buttonRect = CGRectMake(11+charact*20, -40 + line*50, 18, 21);
aButton.frame = buttonRect;

[aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aButton addTarget:self action:@selector(thisButton:) forControlEvents:UIControlEventTouchUpInside];

[aButton setTitle:@" " forState:UIControlStateNormal];
[gameScroll addSubview:aButton];

A: You're registering 2 different selectors for same events type. What will happen - the second one will override the first one. What is the point of this? May be you have a typo in your code sample, but anyway, you can register different selectors for different events. And if you're creating your buttons in the loop it's not a problem, since each time it will register a different object for this target. Your function will look like this probably:
- (void) buttonClicked:(id) sender
{
   // your code
}

where the sender is the object, which sends the selector to a target. In this case your button.
As for them running simultaneously... Do they run on different threads? Usually GUI runs only on main thread, so it will not happen simultaneously if this is a concern.
Hope it answers your question

A: It is meaningful to have multiple actions for different types of control events.
For same control event, those different actions would get invoked. Are you going to do same task in those different actions?
If you want to do different task in those different actions, cannot you do the same using some condition in the only one same action?


text:
Q: Computers on preexisting Windows 2008 domain accepting accounts from Samba3/4 domain I have a web application written in PHP where I would like to allow existing users to log into Windows computers, too. Re-hash of their passwords is doable (by requesting them to change the password). And to solve desync of passwords, I intend to have webapp authenticate users primarily against the domain.
I don't want to give webapp users accounts on the existing domain, which we can call example.local. Instead, I want to provide them accounts on a new domain, let's call it webapp.example.local.
From some research I have done, setting up a Samba4 domain and joining computers into this webapp.example.local domain would be one way to allow webapp users to log in. But, the computers should be members of the example.local domain.
How can I get computers that are members of and are authenticating against Windows 2008-based example.local to also authenticate users against webapp.example.local?
Magic keywords seem to be "trust relationship", "forest", etc, but at this point I haven't found a concrete example on how to establish this trust.

A: I'm not an expert on Samba4, so I cannot evaluate the limits of your design at that point. But from the AD point of view, what you want can be achieved using two separate domains and stablishing the trust relationship between both domains, so you are right on this point.
IMHO if you want two different domains, one for production (example.local) and another for resource management (webapp.example.local), bearing in mind that those two domains are hosted by different techologies (Native Microsoft AD and SAMBA4) should be better to set them in a non-contiguous DNS namespace, like example.local for production and resources.local for resource management. It's just a personal preference for AD management and not a real technical limitation.
Nevertheless I hope you could find usefull these two next links:
TechNet: Understanding Trust Types
TechNet: Creating External Trusts
Hope it helps!


text:
Q: Is there a file for ip neigh show I am looking for the file containing the output of ip neigh show command. I need the file as I can't invoke command and redirect as per requirement. The closest thing I found is the file /proc/net/arp. It contains almost the same IP-MAC entries but in a different format. Do there exist any file containing the same info which is displayed by ip neigh show?

A: According to the source code, ip neigh show output is based on rtnetlink messages from the kernel.
See netlink(7) man page for an example on how to operate a (rt)netlink socket, and the above-mentioned rtnetlink(7) man page for the necessary constants. I guess you'd want a RTM_GETNEIGH message.


text:
Q: field or property \"CreatablesInfo\" does not exist I´m developing a Sharepoint 2013 on premise webservice and I consult many lists but in one list I have a error: field or property \"CreatablesInfo\" does not exist.
Error is in context.ExecuteQuery() according visual studio 2013
            CamlQuery query = new CamlQuery();
            query.ViewXml = "<View>" +
                                "<Query>" +
                                    "<Where>" +
                                        "<And>" +
                                            "<IsNull>" +
                                                "<FieldRef Name='ID_x0020_Aplicacion' />" +
                                            "</IsNull>" +
                                            "<Gt>" +
                                                "<FieldRef Name='Created' />" +
                                                "<Value Type=DateTime>2016-11-30T12:00:00Z</Value>" +
                                            "</Gt>" +
                                        "</And>" +
                                    "</Where>" +
                                "</Query>" +
                            "</View>";
            ListItemCollection itemCollection = list.GetItems(query);
            context.Load(itemCollection);
            context.ExecuteQuery();

Note: list, context and same code work perfectly with other lists.


text:
Q: Testing file uploads with codeception Problem:
No data and files are coming through to the Silex application when a request is made from codeception test using the REST module with PhpBrowser driver.
    // ApiTester $I
    $I->wantTo('Submit files');

    // prepare:
    $data = ['key' => 'value'];
    $files = [
        'file_key' => 'path/to/file.doc',
        'file2_key' => 'path/to/file2.doc'
    ];

    // act:
    $I->haveHttpHeader('Content-Type', 'multipart/form-data');
    $I->sendPOST('/attachments/', $data, $files);

Current response
 I have http header "Content-Type","multipart/form-data"
 I send post "/attachments/",{"key":"value"},{"file_key":"/path/to/file/...}
  [Request] POST http://localhost/attachments/ {"key":"value"}
  [Request Headers] {"Content-Type":"multipart/form-data"}
  [Page] http://localhost/attachments/
  [Response] 400
  [Request Cookies] []
  [Response Headers] {"Date":["Tue, 25 Oct 2016 09:15:31 GMT"],"Server":["Apache/2.4.10 (Debian)"],"Cache-Control":["no-cache"],"Access-Control-Allow-Origin":["*"],"Access-Control-Allow-Headers":["Content-Type, Authorization"],"Access-Control-Allow-Methods":["GET,PATCH,PUT,POST,HEAD,DELETE,OPTIONS"],"Content-Length":["1235"],"Connection":["close"],"Content-Type":["application/json"]}
  [Response] {"status":400,"meta":{"time":"2016-10-25 09:15:31"},"title":"Invalid Request","errors":"No data received","details":{"error_class":"Symfony\Component\HttpKernel\Exception\BadRequestHttpException"

Tried:

*

*changing the Content-Type header

*changing files array passed to sendPOST to an array of:

*

*file paths file objects ( UploadedFile )

*file arrays

The test works with Silex driver, but that won't be an option on the CI server. Also we've checked with Postman and the API route works as intended, files are sent and all good.

A: The actual problems:

*

*$I->haveHttpHeader('Content-Type', 'multipart/form-data'); overwrites the Content-Type as it should be set by the http library (in phpbrowser is guzzle) to include the boundary, it's related to this.

*Also be mindful that the $I->header does not reset after each request, to unset it use $I->deleteHeader('Content-Type');
Solution

*

*Don't set the 'Content-Type' headers when sending files.


text:
Q: Microservices, REST, event sourcing and data consistency I'm planning a model for microservices using event sourcing. To achieve a high scalability and high throughput handling capacity, I'll use Kafka as a message broker for the microservices.
At this point, I have questions about the implementation of the model to be able to have the benefits of Kafka topic and partition. There are some requirements that my model needs to fit:

*

*Microservices must ingest data from the message broker (POST/PATCH/PUT/DELETE)

*Data consistency is mandatory, if entity A needs previous existence of entity B, then must exists only records of entity A that points to valid records of entity B

*The microservices can't couple their domains (refering to DDD)

*The system must handle high thrgoughput of read and writes operations

Well, with this requirements in mind, I've endend up with a model that:

*

*Use an Elasticsearch database that have the current valid state

*All write requests are received by a "Microservice Gateway" that:

*

*Validate the request and the new state that is requested

*Produce a write operation in the message broker

*Receives state change events from the message broker

*Responds to requester with the new state changed

*All write operations are consumed by a "Microservice Processor" that:

*

*Handles all the business logic and data denormalization

*Updates the state in the Elasticsearch database

*Produce a state change event in the message broker

*All read requests are handled by the "Microservice Gateway" that:

*

*Searchs at the Elasticsearch database for the requested resource's records

*Responds to the requester with the results

My questions:

*

*This model does some coupling of the domains? The Gateway is validating subresources ID's to ensure data consistency in one Elasticsearch database (the case of A pointing to B).

*I don't know if this model fits reports requests, there are some complex reports that process a lot of data with input parameters from the user and from his point of view, the operation must be "synchronous" (request/response REST)

*Is the validation of requests/new state a part of the business logic (related to DDD)? If so, my model is incorret to separate them into two microservices?

EDIT
My new proposal for my client:

*

*Instead of having a gateway acting as a part of the microservice, let gateway only for: routing (microservice registry), balancing and auth stuffs (calling a dedicated microservice for authentication/authorization)

*The microservices hold their own data/database, consistency is ensured by event sourcing architeture

*Reports: if it's about one domain, can be a resource at the microservice that holds the data, if more than one domain is required, another microservice will provide the report

A:
This model does some coupling of the domains? The Gateway is validating subresources ID's to ensure data consistency in one Elasticsearch database (the case of A pointing to B).

You answered your own question with the following sentence:

All read requests are handled by the "Microservice Gateway"

If that is true your system does not have a domain separation at all. In fact you have a god-Gateway that needs to know about all domains.
A gateway should be constrained to very dedicated purposes that the domain specific services cannot fulfill (e.g. security, routing/proxy, load balancing, consolidation, resilience, etc.).

I don't know if this model fits reports requests, there are some complex reports that process a lot of data with input parameters from the user and from his point of view, the operation must be "synchronous" (request/response REST)

I would see reports as a separate service that ideally uses the existing services to get whatever information is required. Depending on your domain and requirements you may want to have some dedicated non-public endpoints at your services for this or you may want to access the database directly (e.g. with specialized queries on graph databases).

Is the validation of requests/new state a part of the business logic (related to DDD)? If so, my model is incorret to separate them into two microservices?

It depends on the type of validation. For validating correctness from a domain point of view you need the corresponding service. If you want to validate other things other parts of your system could be responsible (logging, authorization, thwarting malicious attempts, ...)
*For your edit:

*

*Instead of having a gateway acting as a part of the microservice, let gateway only for: routing (microservice discovery), balancing and auth stuffs (calling a dedicated microservice for authentication/authorization)

Few things about this:

*

*Typically you don't do the actual service discovery on the API gateway. Instead it should be a function of the cluster orchestration (see how kubernetes does it for you). The gateway would just use the service registry to proxy correctly (for example use the right DNS entries).

*The microservices architectural style was invented to allow very large organizations to scale fast growing server applications. It does have drawbacks, especially when setting up for smaller projects that need to have results quickly. Most people from those larger organizations would tell you to start with a monolithic initially and separate out when teams grow too big (by drawing component boundaries you can prepare for that separation in initial development). Even with a "monolithic" service you can still have a modern build/test/deployment infrastructure with CICD and the service can still have horizontal scalability. Since I don't know your domain / project size I just wanted to give that as a general thought.


text:
Q: почему сайт выдает ошибку, если по выводу у меня все правильно? при запуске данного кода, на сайте не пропускает по решению

A: Потому что в этом задании вам нужно написать функцию, которая возвращает результат. А ваша функция ничего не возвращает, а только выводит на печать.
Замените оба print на return и будет вам счастье.


text:
Q: PHP & SQL inserting into a database table error I'm slowly progressing through PHP and SQL and have stumbled upon a small error, when trying to send a string into an SQL database. What I'm trying to do is insert a users's detail into one table (which currently works) and send the user name along with 5 blank entries into another table. The table examscore fields are username, exam, exam1, exam2, exam3, exam4 (it is these exam fields that I require blank for now).
The problem is that I receive the following message:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\xampp\htdocs\E-LearningWebsite\addcustomertodb.php on line 11 (which line that starts $query1)
If possible could anyone explain what this error means and what i have done wrong?
<?php
require "dbconn.php";

$username = $_GET['username'];
$email = $_GET['email'];
$pass = $_GET['password'];

$query = "INSERT INTO customer VALUES ('".$username."','".$email."','".$pass."')";

$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";

$results = mysql_query($query) or die (mysql_error());

$results1 = mysql_query($query1) or die (mysql_error());

?>

Kind regards Andy

A: change
$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";

to
$query1 = "INSERT INTO examscores VALUES ('".$username."','','','','','')";

ps. you are inviting SQL injections but that is a different story...

A: The goggles! They do nothing! The sql injection vulnerabilities! And it's only Monday!
Why not just
$query ="INSERT INTO customer VALUES ('$username', '$email', '$pass');";
$query1 = "INSERT INTO examscores VALUES ('$username', '', '', '', etc...);";

PHP will happily replace $vars inside "" quoted strings for you. There's absolutely not need for all the concatentation you're doing. Any decent code editor will still highlight the vars for you.

A: you are missing dots to concatenate your strings
$query1 = "INSERT INTO examscores VALUES ('".$username."','"."','"."','"."','"."','"."')";

furthermore you dont need to have different strings
and still further more you dont need to include every column if you are not inserting them

A: Your immediate problem causing the errors is the missing .s from query1 from between the double-doublequotes,  (or you should just delete the double-doublequotes altogether. Or even the unneeded columns...).
But there are way bigger issues in your code:

*

*SQL injection: your code is vulnerable. You should at least escape th variables coming from the user...

*mysql_* deprecation: as of PHP 5.5, these functions will be deprecated. Use either Mysqli or even ebtter PDO.


text:
Q: Web API return csv file I need to get a csv file from web api controller. I can not get "Save As" dialog to show up. Only text output shows up on the page. I tried both, calling Export from jquery and also plain old html
Controller:
[System.Web.Http.HttpGet]
public HttpResponseMessage Export()
{
    StringBuilder sb = new StringBuilder();
    IEnumerable<CustomerDiscount> list = this.subscriberRepository.GetSubscribers();

    foreach (CustomerDiscount item in list)
    {
        sb.AppendFormat(
            "{0};{1};{2};",
            item.CustomerName,
            item.CustomerNumber,
            Environment.NewLine);
    }

    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(sb.ToString());
    writer.Flush();
    stream.Position = 0;

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("text/csv");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
    return result;
}

EDIT:
added this line:
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };

still doesn't work
I call it like this:
Export

and also tried it like this:
$("#export").click(function () {
    $.post("/Relay/Billing/Export", { type: $("#discountType").val() })
      .done(function (data) {
      });
});

Still no Save As box

A: I do not know whether this is proper protocol but this is how I did it before. So you have a web page from which you will invoke an API that will response with the file and it should be handled by browser's save as dialog.
The HTML:
<!DOCTYPE html>

    <title></title>

    Export

The action:
public HttpResponseMessage Get(int id)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write("Hello, World!");
    writer.Flush();
    stream.Position = 0;

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
    return result;
}

This is working for me in both Chrome and Firefox latest.

A: You cannot have a download dialog if you call your API from an AJAX call. Either make it a regular link (for APIs using GET) or, if you need it to be a POST, have it to post to a new window using a regular form with target="_blank".
So, either click here, or
<form method="post" target="_blank" action="/Relay/Billing/Export">
<input id="discountType" name="type"/>
<input type="submit">Export</input>
</form>


text:
Q: Example of a certain vector space Let $k$ be a field. I am looking for an example of infinite dimensional $k$-vector space $V$ such that $V\cong V\oplus V$. Also kindly let me know in brief how you've thought about it . Thanks in advance!

A: As Rhys Steele mentioned, two vector spaces over $k$ are isomorphic iff they have the same dimension. For an infinite dimensional $k$-vector space $V$, $\dim(V) + \dim(V)= \dim(V)$ holds (see this question). Therefore $V \cong V \oplus V$.
Let's pick our favourite infinite-dimensional vector space and do this. Mine is $k[X]$, the vector space of polynomials in one variable over $k$.
If you add it with itself, you obtain $k[X] \oplus k[Y] \cong k[X,Y]$, the vector space of polynomials in two variables. All those vector spaces have dimension $\mathbb N$, so they are abstractly isomorphic. But where is the isomorphism? $k[X]$ and $k[X,Y]$ look very different, don't they?
We can choose a basis of $k[X]$ (e.g. the monomial basis) and $k[X,Y]$ (e.g. the basis of all monomial products $1,X,Y,XY,X^2,Y^2,XY^2,X^2Y\dots$). Choosing any bijection between those two basis (which exists, since $\mathbb N \times \mathbb N$ and $\mathbb N$ have the same cardinality, i.e. are both countably infinite) provides a vector space isomorphism, by linear extension.
You might feel a bit cheated now. Aren't $k[X]$ and $k[X,Y]$ different things? They are the same as vector spaces though. The difference is the additional structure on those two vector spaces, since you can multiply polynomials. The multiplication turns $k[X]$ and $k[X,Y]$ into algebras (even graded algebras), and the isomorphism above won't preserve this structure. If you want to fix this, you obtain an example which feels more natural:
Let $V=k[X_1,\dots,X_n,\ldots] = \bigoplus_{i=1}^\infty k[X_i]$ the vector space of polynomials with coefficients in $k$ and countably infinitely many unknowns. Like before, if you take the direct sum of $V$ with itself, you just "double" the unknowns. So $V\oplus V$ is the vector space over twice as many unknowns (which could be called $X_1,X_2,X_3,\ldots$ and $Y_1,Y_2,Y_3,\ldots$). But that's still the same amount of unknowns. A bijection of the set $\{\,X_1,X_2,X_3,\ldots\}$ and $\{\,X_1,Y_1,X_2,Y_2,X_3,Y_3,\ldots\,\}$ gives rise to an algebra-isomorphism (which is in particular a linear isomorphism).


text:
Q: Continuity/differentiability at a point and in some neighbourhood of the point For a function $f: U \to \mathbb{R}$ where $U$ is a subset of $\mathbb{R}$, it seems like that it being continuous at a point doesn't imply that there is a neighbourhood of the point where it can be continuous. Similarly, it seems like that it being differentiable at a point doesn't imply that there is a neighbourhood of the point where it can be differentiable. I was wondering if there are some counterexamples to confirm the above?
Added:
What are some necessary and/or sufficient conditions for continuity/differentiability at a point and in some neighbourhood of the point to be equivalent?
Can the case of continuity be generalized to mappings between topological spaces?
Thanks and regards!

A: Define $f$ by putting $f(x) = 1$ if $x$ is rational and $f(x) = 0$ if $x$ is irrational. Let $g(x) = x \cdot f(x)$ and let $h(x) = x^2 \cdot f(x).$
$g$ is continuous at $x=0$ and $g$ is not continuous at each $x \neq 0.$
$h$ is differentiable at $x=0$ and $h$ is not differentiable at each $x \neq 0.$
(In fact, $g$ is also not differentiable at $x=0$ and $h$ is not continuous at each $x \neq 0$.)

A: Any function $f$ on $[-1,1]$ with $|f(x)| \le x^2$ is differentiable at $0$.  You could e.g. take $f(x) = x^2$ when $x$ is rational and $-x^2$ when $x$ is irrational.


text:
Q: Add-in error due to slow script on Windows We have a pretty heavy React Component sometimes loads about 2000 items in our Excel Addin. On Mac and Chrome, the component works fine with no error. But in windows, Add-in Error will show up and clear the Add-in page completely.
Digging further into this, we are able to repro it with IE11. IE will issue Script not responding error while loading the slow component. I profiled it, and saw lots of DOM operations. I wonder why same code runs so much slower on IE. And we are also trying to work around the issue by optimizing our component.

A: From the docs:

Important: When you develop an add-in for any Office host application,
  reference the JavaScript API for Office from inside the  section
  of the page. This ensures that the API is fully initialized prior to
  any body elements. Office hosts require that add-ins initialize within
  5 seconds of activation. If your add-in doesn't activate within this
  threshold, it will be declared unresponsive and an error message will
  be displayed to the user.

In order to ensure add-ins perform well, Office gives you 5 seconds to complete the initialization of your add-in. That said, there are some natural timing variances between platforms and browsers. This is why if you're butting up against 5 seconds (which it sounds like you are), you may not see this error surface across the board.
In general, the most important consideration is when different components get wired up on your page. You need to ensure that Office.js gets loaded and initialized before all others. This allows you to easily slip into that 5 second window even if your add-in spends an additional 10 seconds spinning up content (although please, for the sake of your users, don't take 10 seconds!).
A couple of helpful tips:

*

*Make sure Office.js is referenced in your  and not at the end of your . Generally web apps want JS referenced last so the DOM is populated first. This case however is an exception to that rule. Reference is early and before almost anything else loads.

*Put you Office.initialize() or the js library that contains it within your  tag as well. This will ensure it wires up the add-in before anything else gets loaded.

*Consider delaying styles from loading until later. Google has a great example of this @ Optimize CSS Delivery.


text:
Q: Converter imagem para base64 com IonicFramework Existe alguma biblioteca que permita converter imagens para base64 com o Ionic Framework?
Tentei utilizar o angular-base64-upload, funcionou com o angular, porém no Ionic não obtive sucesso.
Se alguém conhecer alguma biblioteca ficaria muito agradecido, ou mesmo alguma forma nativa de fazer a conversão.
Observações:

*

*Quero pegar a imagem carregada tanto da camera com o plugin do Cordova, como também da galeria de imagens do Android.

A: Neste caso você usa um plugin do ngCordova chamado câmera porém com alguns atributos diferentes no qual esta abaixo.
$scope.abrirGaleria = function () {
    var options = {
      quality: 50,
      destinationType: Camera.DestinationType.DATA_URL,
      sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
      allowEdit: true,
      encodingType: Camera.EncodingType.JPEG,
      targetWidth: 100,
      targetHeight: 100,
      popoverOptions: CameraPopoverOptions,
      saveToPhotoAlbum: false
    };

    $cordovaCamera.getPicture(options).then(function(imageData) {
      var image = document.getElementById('myImage');
      image.src = "data:image/jpeg;base64," + imageData;
    }, function(err) {
      // error
    });
  }


text:
Q: Avoid closing OpenCv windows Is there any way to disable or hide the X button from a cv2.window, or at least of changing its behaviour so nothing happens with the window when clicked?
PS: I am using Windows 10, Python 3.6 and OpenCV 4.3.0

A: you can add a loop to display the window you use and to add condition of the key to the waitKey that you approve to close the window (like esc)
while video.isOpened(): #Starting a loop to play the video continuously
    ret, frame = video.read()

    if not ret:
        break

    cv2.imshow('Video Player',frame) # Display the video

    k = cv2.waitKey(0) & 0xFF

    if k == 27:    # Use Esc key to exit the program
        break


text:
Q: Swapping the Motherboard of Dell N5010 I have a Dell N5010 laptop. It had an integrated graphics card in it which went bad. So, I had to get my motherboard swapped for a new one. The swapping was done by a local repair shop.
I am now having doubts about the motherboard that they put and am thinking if a new motherboard was indeed put or they just soldered back a new video card. So I want to clarify somethings. I have following questions:-

*

*Does BIOS come attached with the motherboard or can it be used again like CPU. And if it comes attached then would the motherboard change lead to a change in the service tag of my laptop ?

*Is there any other way I can check whether they really did the swap or not ?
If it helps, I do remember my previous service tag.
Thanks in advance.

A: Your laptop is based on Intel Core CPU, so it has GPU integrated in the CPU, not on motherboard. Your motherboard was probably left untouched, they have just replaced CPU.

A: You could ask the service centre which has done this hob for you about whether they change a MB or what did they change/do. You have a right to ask and know. Don't let them be a black box.


text:
Q: Does ProGuard work in reverse mode? It seems that by default ProGuard obfuscates everything and you have to add keep statements if you want something to exclude. Can it work in reverse mode? I want ProGuard to obfuscate only specific files and leave everything else untouched.

A: You can achieve this adding the following rule:
-keep class !your.class.to.obfuscate,
            !your.other.class.to.obfuscate,
            !....,
            ** { *; }

This will keep everything (classes,methods,fields) apart from the classes that you excluded. The excluded classes will be obfuscated.


text:
Q: Use font Times LT (Linotype) in LaTeX I've searched for an answer to the following question, but I have not found a precise answer (or at least not an answer that worked for me). So this is it. I do have the original Times font (in Type 1 format) from Linotype, font name TimesLT. I would like to use them in LaTeX. I use PCTeX and I installed the fonts using the  Font List dialog box. I tried to use the package times, and similarly to use
  \renewcommand{\rmdefault}{ptm}

Nonetheless, the fonts used are actually the substitute Nimbus.
I guess that the problem is in the 'LT' suffix in the font name, but I have no idea on how to change it. I am not particularly expert in Tex (nor in programming in general), so the more detailed the answers the more appreciated they would be.

A: I believe you'd be satisfied w/ just using
\usepackage{mathptmx}

There shouldn't be a reason to not accept the clone font which is used.
If you had OpenType version of Times LT, then you could use a TeX variant which directly supports it and install the fonts so that they may be accessed.
If you have access to XeTeX or LuaTeX, this is simple:
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Times LT Std}
\begin{document}
This is Times by Stanley Morison.
\end{document}

If not, you'll need to consult the documentation for PCTeX and see what it says about font installation and follow those instructions.
You should also check the instructions which pre-date OpenType, in particular the fontinst manual and Philipp Lehman's Font Installation Guide http://www.ctan.org/tex-archive/info/Type1fonts/fontinstallationguide/


text:
Q: Dynamically updating datamaps fill color not working using variable as country key I'm having weird problems with datamaps updateCloropleth function. I followed this example :
https://github.com/markmarkoh/datamaps/releases/tag/v0.2.2
Here is an example of my problem. When I do this:
map.updateChoropleth({
    "AFG": colorx
});

The color updates. However, when I do this:
var countryx = "AFG";
map.updateChoropleth({
    countryx: colorx
});

It doesn't work.
I've checked that countryx == "AFG" returns true, so it's definitely the same value. The variable colorx can be passed fine, but passing the variable countryx as a key seems to break the function.
Any ideas how or why this is happening?

A: You can try this:
var colorx = 100;
var countryx = "AFG";
var countryColor = {};

countryColor["AFG"] = colorx;

map.updateChoropleth(countryColor);

See this thread - basically your problem stems from the fact that these two statements are the same:
var obj = {"countryx": colorx}
var obj = {countryx: colorx}


text:
Q: Why does the blackboard letters of the amsfont msbm have strange chardx values? The font msbm which can be found under fonts/source/public/amsfonts/symbols in texlive has strange chardx width values set. If I run mf "\mode=localfont; input msbm10" I get the file msbm10.600gf. If I then run gftype msbm10.600gf I get a symbolic dump of the font data.
This is GFtype, Version 3.1 (TeX Live 2017/Debian) Options selected: Mnemonic output = false; pixel output = false. ' METAFONT output
2020.07.01:2334'

35: beginning of char 0

224: beginning of char 1

Further down in the file we have the width information for each character.
Postamble starts at byte 30141.
design size = 10485760 (10pt)
check sum = -2001332536
hppp = 544093 (8.3022)
vppp = 544093 (8.3022)
min m = -5, max m = 194
min n = -39, max n = 75
Character 0: dx 4259840 (65), width 815562 (64.57289), loc 35
Character 1: dx 4259840 (65), width 815562 (64.57289), loc 224
Character 2: dx 4259840 (65), width 815562 (64.57289), loc 413

dx is what metafont calls chardx, first comes the scaled value and then in parenthesis is the pixel value. The Metafont Book describes it as such:
"chardx" and "chardy" represent horizontal and vertical escapement in units of pixels. (Some typesetting systems use both of these device-dependent amounts to change their current position on a page, just after typesetting each character. Other systems, like the dvi software associated with TeX, assume that "chardy"=0 but use "chardx" as the horizontal escapement whenever a horizontal movement by "chardx" does not cause the subsequent position to drift too far from the device-independent position defined by accumulated "charwd" values.
Next comes the width of the character which Metafont calls charwd it is in units of the design size scaled by 2^20. In the parenthesis following is the value converted to pixels. Normally the chardx pixel value should be the same as the charwd pixel value but rounded to an integer, but the font designer can tweak the chardx value to better suit a low resolution device, however you would expect them to not deviate by more than one pixel. In the blackboard letters in msbm they deviate by a large amount which can be seen in the following. Blackboard letter A is character 65 and Z is character 90, and the lowercase k is character 124.
Character 61: dx 5439488 (83), width 1048579 (83.02225), loc 13792
Character 62: dx 4259840 (65), width 815562 (64.57289), loc 14616
Character 63: dx 4259840 (65), width 815562 (64.57289), loc 14815
Character 64: dx 3014656 (46), width 582544 (46.12347), loc 15066
Character 65: dx 2424832 (37), width 757307 (59.96051), loc 20334
Character 66: dx 2490368 (38), width 699053 (55.34819), loc 20637
Character 67: dx 2555904 (39), width 757307 (59.96051), loc 21048
Character 68: dx 2621440 (40), width 757307 (59.96051), loc 21349
Character 69: dx 2686976 (41), width 699053 (55.34819), loc 21770
Character 70: dx 2752512 (42), width 640798 (50.7358), loc 22133
Character 71: dx 2818048 (43), width 815562 (64.57289), loc 22456
Character 72: dx 2883584 (44), width 815562 (64.57289), loc 22823
Character 73: dx 2949120 (45), width 407781 (32.28645), loc 23254
Character 74: dx 3014656 (46), width 524290 (41.51115), loc 23477
Character 75: dx 3080192 (47), width 815562 (64.57289), loc 23762
Character 76: dx 3145728 (48), width 699053 (55.34819), loc 24161
Character 77: dx 3211264 (49), width 990325 (78.40993), loc 24430
Character 78: dx 3276800 (50), width 757307 (59.96051), loc 25021
Character 79: dx 3342336 (51), width 815562 (64.57289), loc 25408
Character 80: dx 3407872 (52), width 640798 (50.7358), loc 25843
Character 81: dx 3473408 (53), width 815562 (64.57289), loc 26154
Character 82: dx 3538944 (54), width 757307 (59.96051), loc 26641
Character 83: dx 3604480 (55), width 582544 (46.12347), loc 27060
Character 84: dx 3670016 (56), width 699053 (55.34819), loc 27377
Character 85: dx 3735552 (57), width 757307 (59.96051), loc 27676
Character 86: dx 3801088 (58), width 757307 (59.96051), loc 28021
Character 87: dx 3866624 (59), width 1048579 (83.02225), loc 28336
Character 88: dx 3932160 (60), width 757307 (59.96051), loc 28901
Character 89: dx 3997696 (61), width 757307 (59.96051), loc 29218
Character 90: dx 4063232 (62), width 699053 (55.34819), loc 29503
Character 91: dx 10289152 (157), width 1980650 (156.81985), loc 15333

Character 123: dx 3604480 (55), width 699053 (55.34819), loc 19590
Character 124: dx 4128768 (63), width 582544 (46.12347), loc 29810
Character 125: dx 2949120 (45), width 566525 (44.85516), loc 19769
Character 126: dx 2949120 (45), width 566525 (44.85516), loc 20014
Character 127: dx 2359296 (36), width 450016 (35.63045), loc 20245
The file had 123 characters altogether.

Not only do the chardx values not match the charwd values for these letters, they follow an increasing sequence and do not seem to have much to do with the actual width of the character. Furthermore, if I generate the font in proof mode by running mf "\mode=proof; input msbm10" followed by gftodvi msbm10.2602gf and then open msbm10.dvi the blackboard letters in the font show a strange looking grid while the other characters do not.


text:
Q: Create new assoc object in $.each I think this JavaScript should work, but it does not seem to. What can I do to fix it.
I am also open to other ways to do this. All I want to do is return a JSON string of the variable names (cn, sc, fn) and their values (eg. var cn = $('#deFNIN').val(); -- so: "cn":"MacDonalds","sc":"Mac" )
jsFiddle
HTML:

<input id="deCoNameIN" type="text" value="MacDonalds" />

<input id="deShortCoIN" type="text" value="Macs" />

<input id="deFNIN" type="text" value="Fred" />

js/jQ:

var objFields = {
    'cn': { 'id':'deCoNameIN',  'required':'True',  'title':'Company Name'},
    'sc': { 'id':'deShortCoIN', 'required':'True',  'title':'Short Co name' },
    'fn': { 'id':'deFNIN',      'required':'false', 'title':'Contact first name' },
};
var arrDistinfo = [];

$.each(objFields,function(_, varname){
    tmp = $("#"+varname.id).val().trim();
    alert('Varname: ' +_+'   Val: '+tmp);
    arrDistinfo.push({_ : tmp});
});

var xx = JSON.stringify(arrDistinfo);
alert(xx);

The desired output should look like this:
["cn":"Macdonalds", "cs":"Macs", "fn":"Fred"]

A: You can't use variables like object keys like that (in your case, {_ : tmp} is the same as {"_" : tmp}), you need the array notation:

var objFields = {
  'cn': {
    'id': 'deCoNameIN',
    'required': 'True',
    'title': 'Company Name'
  },
  'sc': {
    'id': 'deShortCoIN',
    'required': 'True',
    'title': 'Short Co name'
  },
  'fn': {
    'id': 'deFNIN',
    'required': 'false',
    'title': 'Contact first name'
  },
};
var arrDistinfo = [];

$.each(objFields, function(_, varname) {
  tmp = $("#" + varname.id).val().trim();
  alert('Varname: ' + _ + '   Val: ' + tmp);
  var obj = {};
  obj[_] = tmp;
  arrDistinfo.push(obj);
});

var xx = JSON.stringify(arrDistinfo);
alert(xx);

<input id="deCoNameIN" type="text" value="MacDonalds" />

<input id="deShortCoIN" type="text" value="Macs" />

<input id="deFNIN" type="text" value="Fred" />

UPDATE
To get that specific format, you'd need to make it a string, because JS doesn't has such array-like structure.

var objFields = {
  'cn': {
    'id': 'deCoNameIN',
    'required': 'True',
    'title': 'Company Name'
  },
  'sc': {
    'id': 'deShortCoIN',
    'required': 'True',
    'title': 'Short Co name'
  },
  'fn': {
    'id': 'deFNIN',
    'required': 'false',
    'title': 'Contact first name'
  },
};
var arrDistinfo = {};

$.each(objFields, function(_, varname) {
  tmp = $("#" + varname.id).val().trim();
  arrDistinfo[_] = tmp;
});

var output = [];
for (var i in arrDistinfo) {
  output.push('"' + i + '":"' + arrDistinfo[i] + '"');
}

alert('[' + output.join(', ') + ']');

    <input id="deCoNameIN" type="text" value="MacDonalds" />

    <input id="deShortCoIN" type="text" value="Macs" />

    <input id="deFNIN" type="text" value="Fred" />


text:
Q: Transform/ Project a geometry from one SRID to another I have a database table which currently holds geometric data in SRID 27700 (British National Grid). While retrieving the data however I need to transform it to SRID 4326 (WGS84). Is there any way to apply a function such as ST_Transform found in PostGIS to my data in order to get the result I need?
NOTE: The solution needs to be able to be implemented using T-SQL and not stored procedures etc. I have to be able to construct a statement and have it saved in a table as a string field for retrieval later. This is because my solution is database agnostic.
The way I am currently doing this in Oracle is as follows:
select CLUSTER_ID,
       NUM_POINTS,
       FEATURE_PK,
       A.CELL_CENTROID.SDO_POINT.X,
       A.CELL_CENTROID.SDO_POINT.Y,
       A.CLUSTER_CENTROID.SDO_POINT.X,
       A.CLUSTER_CENTROID.SDO_POINT.Y,
       TO_CHAR (A.CLUSTER_EXTENT.GET_WKT ()),
       TO_CHAR (A.CELL_GEOM.GET_WKT ()),
       A.CLUSTER_EXTENT.SDO_SRID
from (SELECT CLUSTER_ID,
             NUM_POINTS,
             FEATURE_PK,
             SDO_CS.transform (CLUSTER_CENTROID, 4326) cluster_centroid,
             CLUSTER_EXTENT,
             SDO_CS.transform (CELL_CENTROID, 4326) cell_centroid,
             CELL_GEOM FROM :0) a
where sdo_filter( A.CELL_GEOM,
                  SDO_CS.transform(mdsys.sdo_geometry(2003, :1, NULL, mdsys.sdo_elem_info_array(1,1003,3),mdsys.sdo_ordinate_array(:2, :3, :4, :5)),81989)) = 'TRUE'

In PostgreSQL using PostGIS I am doing it like this:
select CLUSTER_ID,
       NUM_POINTS,
       FEATURE_PK, ST_X(a.CELL_CENTROID),
       ST_Y(a.CELL_CENTROID),
       ST_X(ST_TRANSFORM(a.CLUSTER_CENTROID, 4326)),
       ST_Y(ST_TRANSFORM(a.CLUSTER_CENTROID, 4326)),
       ST_AsText(a.CLUSTER_EXTENT),
       ST_AsText(a.CELL_GEOM),
       ST_SRID(a.CLUSTER_EXTENT)
FROM (SELECT CLUSTER_ID,
      NUM_POINTS,
      FEATURE_PK,
      ST_TRANSFORM(ST_SetSRID(CLUSTER_CENTROID, 27700), 4326) cluster_centroid,
      CLUSTER_EXTENT,
      ST_TRANSFORM(ST_SetSRID(CELL_CENTROID, 27700), 4326) cell_centroid,
      CELL_GEOM
from :0) AS a
where ST_Intersects(ST_Transform(ST_SetSRID(a.CELL_GEOM, 27700), :1), ST_Transform(ST_GeomFromText('POLYGON(('||:2||' '||:3||', '||:4||' '||:3||', '||:4||' '||:5||', '||:2||' '||:5||', '||:2||' '||:3||'))', 4326), :1))

A: Unfortunately, this simply isn't possible.  SQL Server Spatial Tools provides a few reprojection functions, but they are only for a very few number of projections (and not the one you require).
There is an example from SQL server tools -- https://bitbucket.org/geographika/sql-server-spatial-tools/src/5ca44b55d3f3/SQL%20Scripts/projection_example.sql -- but it won't help you because they don't support the projection you are talking about.
So, you'll need to adopt a different solution -- either pre-process the data to add a new column with projected values, or reproject in your code.

A: You could wrap something like DotNetCoords in a SQL CLR function to do this.
See here:- http://www.doogal.co.uk/dotnetcoords.php
I've wrapped it in a CLR function to convert coordinates from Easting/Northing to Lat/Long which I think is what you are asking for. Once the CLR function is implemented it is a pure SQL solution (i.e. you can run it all in a Stored Procedure or View).
EDIT: I will post some sample code up here when I get to work tomorrow, hopefully it will help.
EDIT: You'll need to download the source code from http://www.doogal.co.uk/dotnetcoords.php and you will need Visual Studio to open and modify it. Documentation for the library is here http://www.doogal.co.uk/Help/Index.html
What you can do then is you can add a new class to the source files similar to this:-
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using DotNetCoords;
using Microsoft.SqlServer.Server;

/// <summary>
/// Sql Server CLR functions for the DotNetCoords library.
/// </summary>
public class CLRFunctions
{

    /// <summary>
    /// Coordinateses the enumerable.
    /// </summary>
    /// <param name="Easting">The easting.</param>
    /// <param name="Northing">The northing.</param>
    /// <returns></returns>
    private static IEnumerable<OSRef> CoordinatesEnumerable(double Easting, double Northing)
    {
        return new List<OSRef> { new OSRef(Easting,Northing) };
    }

    /// <summary>
    /// Toes the lat long.
    /// </summary>
    /// <param name="Easting">The easting.</param>
    /// <param name="Northing">The northing.</param>
    /// <returns></returns>
    [SqlFunction(FillRowMethodName = "FillRow")]
    public static IEnumerable ToLatLong(double Easting, double Northing)
    {
        return CoordinatesEnumerable(Easting, Northing);
    }

    /// <summary>
    /// Fills the row.
    /// </summary>
    /// <param name="obj">The obj.</param>
    /// <param name="Lat">The lat.</param>
    /// <param name="Long">The long.</param>
    private static void FillRow(Object obj, out SqlDouble Lat, out SqlDouble Long)
    {
        OSRef Coordinates = (OSRef)obj;
        LatLng latlong = Coordinates.ToLatLng();
        latlong.ToWGS84();
        Lat = new SqlDouble(latlong.Latitude);
        Long = new SqlDouble(latlong.Longitude);
    }

}

You will then need to build and import the assembly into SQL Server (replace paths with your own locations) (for some reason I cannot get the assembly to install when PERMISSION_SET is 'SAFE' so I would sort this first before installing in a production environment).
CREATE ASSEMBLY DotNetCoords
FROM N'C:\Projects\DotNetCoords\bin\Debug\DotNetCoords.dll'
WITH PERMISSION_SET = UNSAFE
GO

You'll then need to create a SQL Server function to interface to the CLR function:-
CREATE FUNCTION dbo.ToLatLong(@Easting float, @Northing float)
RETURNS TABLE
(Latitude float null, Longitude float null) with execute as caller
AS
EXTERNAL NAME [DotNetCoords].[CLRFunctions].[ToLatLong]

This is the CLR function installed then.
You should then be able to call the function direct from SQL Server to do your conversion (I have mixed up the numbers in this post too keep anonymity so they might not make sense here but the function does work fine).
/*------------------------
SELECT Latitude, Longitude FROM dbo.ToLatLong(327262, 357394)
------------------------*/
Latitude            Longitude
52.13413530182533       -9.34267170569508

(1 row(s) affected)

To use it in a resultset you need to use the CROSS APPLY clause:-
/*------------------------
SELECT TOP 2    a.[Column 0] AS osaddessp,
                            a.[Column 9] AS east,
                            a.[Column 10] AS north,
                            c.[Latitude] AS lat,
                            c.[Longitude] AS long
FROM    MyTable AS a CROSS APPLY ToLatLong (a.[Column 9], a.[Column 10]) AS c;
------------------------*/
osaddessp       east    north   lat         long
100134385607    327862  334794  52.3434530182533    -2.19342342569508
100123433149    780268  353406  52.3453417606796    -3.19252323679263

(10 row(s) affected)


text:
Q: No man-page or info-page for type command I tried to find information about type command using man pages and info
$ man type
No manual entry for type
info type

I think this is info menu page.

Is it just happening to me?? Why did Ubuntu developers remove type command manual page. Did they ever make a manual page for type command?

A: If you enter type type you find that
type is a shell builtin

So its documentation is in man bash. You can't get the instructions from man type but you can instead get them from (many thanks to @Rinzwind ) help type and in the same format as a man page with the -m option and by piping the output into less
help -m type | less

man bash is very long, and may be easier to read here, specifically the section on bash builtin commands.
Here is the entry for type, which tells us what kind of command a command is:

type
type [-afptP] [name …]

For each name, indicate how it would be interpreted if used as a command name.
  If the -t option is used, type prints a single word which is one of >'alias', 'function', 'builtin', 'file' or 'keyword', if name is an
  alias, shell function, shell builtin, disk file, or shell reserved
  word, respectively. If the name is not found, then nothing is printed,
  and type returns a failure status.
If the -p option is used, type either returns the name of the disk file that would be executed, or nothing if -t would not return 'file'.
The -P option forces a path search for each name, even if -t would not return 'file'.
If a command is hashed, -p and -P print the hashed value, which is not necessarily the file that appears first in $PATH.
If the -a option is used, type returns all of the places that contain an executable named file. This includes aliases and functions,
  if and only if the -p option is not also used.
If the -f option is used, type does not attempt to find shell functions, as with the command builtin.
The return status is zero if all of the names are found, non-zero if any are not found.

Examples:
$ type echo
echo is a shell builtin
$ type ls
ls is aliased to `ls --color=auto'
$ type sort
sort is /usr/bin/sort
$ type python
python is hashed (/usr/bin/python)

This answer gives a really clever way to make the man command work for shell builtin commands by adding a function to your ~/.bashrc


text:
Q: Why Atmega328P has no PortA This is a general question regarding Atmega328P.
While I was reading the datasheet of Atmega328P, I see that it has Ports B, C, and D.
So, I'm surprised to see that there is no PortA.
Is there a specific reason for it?
Datasheet for Atmega328P: http://www.atmel.com/Images/doc8161.pdf

A: When a chip manufacturer designs a family of chips they will often start with an all singing, all dancing design with all the bells and whistles.  They will then create cut-down versions of the chip by removing portions of the design, or sometimes just not connecting pins up.
The internals of the 328P will be based on a larger chip which does have a port A (as well as other ports).  The removal of port A as opposed to another port would have had two considerations:

*

*What functions are shared with which port, and which can we do away with

*How easy would it be to move any extra functions to other pins

*How easy would it be to remove the port from the design

I would surmise that port A had few extra functions shared with its pins, and the port was simple to remove from the design and leave the chip suitable for use in a low pin count package.
And yes, the port A reference in the ADC section should read port C.

A: It does, but isn't clearly mentioned in the datasheet. Port A is the ADC 'port'.
It shares most of the pins of Port C (some packages have two extra ADC pins though). I think Atmel uses the Port C moniker for the 'digital' inputs on those pins, and Port A for the analog input. I agree it is confusing.
From page 251 of the datasheet:
"The ADC is connected to an 8-channel Analog Multiplexer which allows eight single-ended voltage inputs constructed from the pins of Port A."
As such, my guess is that Port A represents the internal 8 connections to the ADC.
I just had a look at the Atmega16 Datasheet (http://www.atmel.com/Images/doc2466.pdf). This does have Port A dedicated to the ADC. As such, I think the CPU core is similar but the external pins are multiplexed. I guess for the Atmega8 series they should have dropped the Port A moniker completely to avoid confusion, or maybe they did and the ADC chapter in the datasheet is a typo as you mentioned in the comments.


text:
Q: LTC4041: Reduce inductor audiable noise I'm using the LTC4041 as a UPS for Raspberry Pi. When a power failure is detected, the RPi shuts down immediately (a python script is running!). When the RPi is turned off, the current consumption drops from ~1.5A to several milliamps. This is in line with expectations. However, I can hear noise from the L14 inductor (Prod.: XAL5030-222MEB).
How to reduce the audible noise of an inductor when the load current is low? Below is a spectrogram from audible L14 noise. A microphone was used for the recording.


text:
Q: Secure My ASP .NET Code For Presentation? I have a web application , for presentation to my client they ask me to install it on their local server so they can test it , here is my question !?
Is there any way so i can publish uniquely for that server , i did put some limitation but many features in my app are open , so they can make a disk image from server and use it anywhere else ,
Is there any method to use so my web application check if this server is same server ( by hardware id or anything i don't have any idea ) then start to work !
I saw many codes but they are win forms for generating unique hid , but how can i connect done it with asp .net
EDIT
Could u take a look at this also ,
i am using system.management class
is this reliable i mean are they unique ?
  private string GetUniqueID()
    {
        string cpuInfo = string.Empty;
        ManagementClass mc = new ManagementClass("win32_processor");
        ManagementObjectCollection moc = mc.GetInstances();

        foreach (ManagementObject mo in moc)
        {
            if (cpuInfo == "")
            {
                //Get only the first CPU's ID
                cpuInfo = mo.Properties["processorID"].Value.ToString();
                break;
            }
        }
        ManagementObject dsk = new ManagementObject(@"win32_logicaldisk.deviceid=""" + "C" + @":""");
        dsk.Get();
        string volumeSerial = dsk["VolumeSerialNumber"].ToString();

        string HardWareUniqueID = volumeSerial + cpuInfo;

        return HardWareUniqueID;
    }

Appreciate your answers,
Thanks in advance

A: If you want to avoid having it "phone home" an alternative is to generate some kind of certificate and place it on the machine.  Use a private key that only you know to encrypt the machine name and/or IP.  Then have your app use your public key to decrypt it to verify that it is allowed to run on this server.  Nobody who doesn't know your private key will be able to create valid certificates.

A: You hae a few choices...

*

*Lock your web site to the single IP address you install it on. To make your life easier, check for that IP in a common page base class.  (Note, you could also write HTTP handlers, but the base-class approach is easier.)

*Put a 'phone home' call in the app that checks with your server every time it's started up. That way you can check if they have moved it or if multiple instances are running.

*Use the built-in licensing features of .NET (the same one third-party developers use for controls, etc.)

*The easiest... just put in a time-bomb that lets them test it for a few weeks, then automatically blocks access.  Be smart though... persist the last-checked time so you can tell if they've rolled back their clock trying to get more usage.
Just make sure to distribute a web application, not a web project so you can distribute your code as a compiled bumary rather than having to ship the code-behind files.  That will keep prying eyes out, but does make deployment more a pain since you always have to recompile with every change (as opposed to on-demand compiling.)

A: I would put in a time bomb. It's trivial to implement. Also, your client's won't think that you don't trust them. A fixed evaluation period in the application is extremely common.

A: Provide them a VMware image without any user-access just allow them to open the website externally via HTTP in their web browser.


text:
Q: how to kick people in discord C# I have some code meant to kick people on discord
 namespace bot.Core.Commands
 {
    public class Kick : ModuleBase<SocketCommandContext>
    {
        [Command("kick"), Summary("")]
        public async Task kick(IGuildUser User, string reason = "no reason")
        {
            User.KickAsync(reason);
        }
    }
 }

            int argpos = 0;
        if (!(Message.HasStringPrefix("$", ref argpos) || Message.HasMentionPrefix(Client.CurrentUser, ref argpos))) return;

        var result = await Commandss.ExecuteAsync(context, argpos);
        if(!result.IsSuccess)
        {
            await context.Channel.SendMessageAsync("Command not found or has failed, Commands can also only be ran by an administrator");
        }

however it ALWAYS throws Command not found or has failed, Commands can also only be ran by an administrator. can anybody shed some insight as to why?
all other commands work just fine except for this one. thanks in advance
I am using windows on c# vs 2017
also its not the permissions

A: You need to add [Remainder] before the declaration of reason in the command parameters.
 namespace bot.Core.Commands
 {
    public class Kick : ModuleBase<SocketCommandContext>
    {
        [Command("kick"), Summary("Kicks a user from the guild.")]
        public async Task KickCommand(IGuildUser user, [Remainder] string reason = "no reason")
        {
            user.KickAsync(reason);
        }
    }
 }

Otherwise, in a command such as:
"$kick @Username Sending NSFW Pics"

Everything after "Sending" would be considered as extra parameters and not part of reason, so the command would fail since it only accepts two parameters. Adding [Remainder] tells the command to look at everything that is typed afterwards as part of the same parameter.
That said, the command should work if you don't specify a reason. Is this true? And have you tried kicking without recording a reason? (Just user.KickAsync())


text:
Q: How to show an animation before loading Angular app? I want to add a 2 second animation(SVG animation) screen, before my angular app shows up. So, each time someone goes to the url, the first 2 seconds will be of the animation, and then the Angular app will show up. Is this possible? I'd really appreciate any help in this, thanks and have a great day!
Here's the code for the animation :
The svg code in html:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 700 680" width="700" height="680"><defs><clipPath id="_clipPath_wuO8YUgcuSMrLnSCtxnoIiXwy9UN2HRc"><rect width="700" height="680"/></clipPath></defs><g clip-path="url(#_clipPath_wuO8YUgcuSMrLnSCtxnoIiXwy9UN2HRc)"><g opacity="0.4"><path class="path1" d=" M 0 71.043 L 257.59 659.127 L 466.578 153.666 L 245.439 153.666" fill="none" vector-effect="non-scaling-stroke" stroke-width="8" stroke="#c6c6c6" stroke-linejoin="miter" stroke-linecap="butt" stroke-miterlimit="10"/></g></g></svg>

And the css:
.path1{
    stroke-width:6;
    stroke-dasharray : 500;
    stroke-dashoffset : 1410.1248779296875;
    animation:test 6s linear alternate infinite;
}

@keyframes test{
    from{
        stroke-dashoffset:2351.569580078125;
    }

    to{
        stroke-dashoffset:0;
    }
}

A: A simply solution would be to wait for 2 seconds in app component before proceeding
app.component.html
<ng-container *ngIf="animated">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 700 680" width="700" height="680"><defs><clipPath id="_clipPath_wuO8YUgcuSMrLnSCtxnoIiXwy9UN2HRc"><rect width="700" height="680"/></clipPath></defs><g clip-path="url(#_clipPath_wuO8YUgcuSMrLnSCtxnoIiXwy9UN2HRc)"><g opacity="0.4"><path class="path1" d=" M 0 71.043 L 257.59 659.127 L 466.578 153.666 L 245.439 153.666" fill="none" vector-effect="non-scaling-stroke" stroke-width="8" stroke="#c6c6c6" stroke-linejoin="miter" stroke-linecap="butt" stroke-miterlimit="10"/></g></g></svg>
</ng-container>

<ng-container *ngIf="!animated">
<router-outlet></router-outlet>
</ng-container>

app.component.ts
export class AppComponent {

 animated = true;

  constructor() {
    setTimeout(() => {    // <<<---    using ()=> syntax
      this.animated = false;
      });
     }, 2000);
  }
}


text:
Q: Why is gcd(c,d)=1 for $M \in SL_2(\mathbb(Z))$ I have an idea but I am not entirely sure if it is right.
Since $M \in SL_2(Z)$, $ad-bc=1$. Can we use Bézout's Lemma here to get the proposition? I know it only says that it is for ad+bc=ggt(a,b), but maybe it could be possible to choose appropriate $a,b \in \mathbb{Z}$ to get the lemma for ad-bc=1 too? Thanks for your help

A: What happens if $c$ and $d$ have a factor in common, say $m$? Specifically, assume $c=km$ and $d=lm$. Then $$ad-bc=alm-bkm=m(al-bk)$$Can that last expression equal $1$ if $m>1$?

A: You do not need Bezout. It is enough to review the equation $ad-bc=1$ over $\mathbb{Z}$. If $m=gcd(c,d)$, then $m\mid c$ and $m\mid d$ by definition, so that
the equation implies $m\mid 1$. Hence $m=1$.