text:
Q: Celery Cloudamqp creates new connection for each task I am currently using nitrous.io running Django with Celery and then Cloudamqp as my broker with the free plan (max 3 connections). I'm able to connect just fine and start up a periodic task just fine.
When I run
    celery -A proj worker  -l info

2 connections are created immediately on Cloudamqp and I am able to manually create multiple tasks on a 3rd connection and all is well. However, when I run celery beat with
    celery -A proj worker -B -l info

all 3 connections are used and if celery beat creates 1 or more new tasks, another 4th connection will be created thus going over the maximum connections allowed.
I've tried and currently have set
    BROKER_POOL_LIMIT = 1

but that doesn't seem to limit the connections
I've also tried
    celery -A proj worker -B -l info
    celery -A proj worker -B -l info -c 1
    celery -A proj worker -B -l info --autoscale=1,1  -c 1

with no luck.
Why is there 2 connections made immediately that are doing nothing?
Is there someway limit the initial celery connections to 0 or 1 or have the tasks share/run on the celery beat connection?

A: While it does not actually limit connections, another user found that disabling the connection pool reduced the number of connections in practice:
https://stackoverflow.com/a/23563018/1867779
BROKER_POOL_LIMIT = 0
The Redis and Mongo backends have their own connection limit parameters.

*

*http://docs.celeryproject.org/en/master/configuration.html#celery-redis-max-connections

*http://docs.celeryproject.org/en/master/configuration.html#celery-mongodb-backend-settings (using the max_pool_size parameter)

The AMQP backend does not have such a setting.

*

*http://docs.celeryproject.org/en/master/configuration.html#amqp-backend-settings
Given that, I'm not sure what BROKER_POOL_LIMIT is meant to do, but I'd really like to see CELERY_AMQP_MAX_CONNECTIONS.
Here's a related, unanswered question: How can I minimise connections with django-celery when using CloudAMQP through dotcloud?


text:
Q: For the electric field inside a uniformly charged sphere, why are external charges outside the Gaussian surface not taken into account for the field? Consider a uniformly charged sphere with a charge Q. To find the electric field outside the sphere, a Gaussian surface of radius say 'r' (such that r ≥ R) can be imagined, and the result found is that the electric field is the same as if all the charge of the sphere was concentrated at the center of the sphere. In other words, the field is proportional to the charge inside the Gaussian surface, which is the charge of the sphere, and that's intuitive
However, now suppose that we are interested on the electric field inside the sphere. Using Gauss' Law, the argument that is usually made is that, if a Gaussian surface of radius 'r' is drawn (such that r ≤ R), then the electric field at any point on the Gaussian surface is proportional to the charge inside that Gaussian surface (which is the fraction of the charge of the sphere (Q) enclosed by the Gaussian surface). However, something doesn't make sense to me. What I don't understand is the following: why does only the charges inside this Gaussian surface contribute to the electric field at the surface and the charges outside of the surface which are still part of the real physical sphere are ignored?
The result of the electric field at that surface would only make sense to me if the actual sphere was of the radius of the Gaussian surface. The reason I say that is that, consider thinking about the sphere as protons. Then, the protons enclosed by the Gaussian surface cause a radially outward electric field on the Gaussian surface, and the result of this would be the result obtained using Gauss' Law: the electric field inside a sphere of radius R at a radius r ≤ R is proportional to the charge inside the Gaussian sphere of radius r. However, the problem that I have is that the charges outside this Gaussian sphere of radius 'r' also cause and electric field (remembering that positive charges create an electric field radially outwards), but on the opposite direction, diminishing the field caused by the charges inside the Gaussian sphere (this would be on the point of the Gaussian sphere closest to the positive charges on the outside of the Gaussian sphere). But also, these positive charges cause an additive electric field on the other side of the Gaussian sphere: that is, a positive charge outside the Gaussian sphere causes an electric field towards the center of the real sphere at the point on the Gaussian sphere closest to the positive charge, and at the farthest point (opposite point on the Gaussian sphere), it causes an electric field outwards contributing to the radially outwards electric field. The same would apply for every positive charge surrounding the Gaussian surface, such that they cause an electric field on the Gaussian surface towards the inside of the sphere at one point of the surface, and towards the outside of the sphere at the opposite point on the surface, making the magnitude of the electric field constant obviously at every point. However the electric field that is caused by these external (to the Gaussian sphere) positive charges that goes radially outwards is diminished by the square of the distance from the positive charge to the Gaussian surface, and therefore, the effects of a positive charge at one side of the sphere are not cancelled by a positive charge on the opposite side of the sphere, and the electric field on the Gaussian surface would depend also on the charges external to the Gaussian surface.
To explain myself I did this diagram:

The charges along the y-axis of the sphere are depicted with the electric fields that they release. The charges inside the Gaussian surface cause the radially outwards electric field, that's ok. But the charges in between the distances r and R cause also electric fields. The positive charge outside the Gaussian sphere located above would cause an inwards electric field on the point closest to it, and an outwards electric field on the point farthest from it. The positive charge outside the Gaussian sphere located below would also cause the same, an inwards electric field closest to it and an outwards electric field at the point farthest from it. One would say that the inwards electric field produced by the proton above is cancelled by the outwards electric field produced by the proton below, but this would not be true of course because the outwards electric field would be diminished by the square of the distance.
I don't know if I explained myself correctly, if not, please let me know. The summarized question would be then: why are the external charges to a Gaussian surface inside a solid sphere not considered?
Thanks in advance.

A: Gauss's law says that the electric flux through a closed surface is determined by the charge enclosed by the surface. In other words, there is no flux due to  charges outside the surface, even though charges outside do contribute to the electric field on the surface. It's not that the flux due to outside charges is cancelled by the effect of other charges. Rather, each charge outside the surface contributes some flux into the surface and some flux out of the surface, and when we add these contributions we get a net flux of zero.
In general, this doesn't tell us that we can find the electric field on the surface by only considering the charges inside the surface, since in general the electric field will change from one point to another. However, with enough symmetry there will be simple relationship between the flux and the electric field components, and this lets us find the electric field in terms of the charge inside the surface.
For the case of a uniform sphere of charge, we have spherical symmetry, so we know the electric field is the constant on a spherical gaussian surface concentric with the sphere. This means we can say
\begin{align}
\Phi_E = \int E_r\,dA = E_r A
\end{align}
so the electric field is completely determined by the flux and hence by the charge enclosed.

A: Newton's Shell Theorem states that the gravitational force exerted by a spherical shell of uniform density upon a mass interior to that shell is 0.
Coulomb's law is analogous to Newton's law of gravitational attraction.
$$F = k\frac{q_1q_2}{r^2}$$
vs
$$F = G\frac{m_1m_2}{r^2}$$
So, the force exerted by a spherical shell of uniform charge density upon a charge interior to that shell will also be zero.
Thus, the electric field inside a spherical shell of uniform charge density at a given point interior to that shell will have the same magnitude as if the shell a uniformly $0$ charge density.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scrapy : Crawlspider not working on rule linkextractor
I tried several times but the CrawlSpider works fine if I inserted links within start_urls using parse as define method:

    start_urls = ["https://rent.591.com.tw/home/search/rsList?is_new_list=1&type=1&kind=0&searchtype=1&region=1&firstRow=0&totalRows=9672",
"https://rent.591.com.tw/home/search/rsList?is_new_list=1&type=1&kind=0&searchtype=1&region=1&firstRow=30&totalRows=9672",
"https://rent.591.com.tw/home/search/rsList?is_new_list=1&type=1&kind=0&searchtype=1&region=1&firstRow=60&totalRows=9672",
"https://rent.591.com.tw/home/search/rsList?is_new_list=1&type=1&kind=0&searchtype=1&region=1&firstRow=90&totalRows=9672",    ]

But while using LinkExtractor the crawler comes out as none referer all the times

> 2018-02-04 22:36:18 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)

>2018-02-04 22:36:18 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023

>2018-02-04 22:36:19 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://rent.591.com.tw/robots.txt> (referer: None)

>2018-02-04 22:36:24 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://rent.591.com.tw/home/search/rsList?is_new_list=1&type=1&kind=0&searchtype=1&region=1&firstRow=0&totalRows=9672> (referer: None)

What might be the specific issue? I already work on this for all day.
  Is LinkExtractor won't work with JSON response and java request? Or is the Rule setting doesn't fit the following?

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from bs4 import BeautifulSoup
import json

class crawler(CrawlSpider):
name = "test1"
allowed_domains = ["rent.591.com.tw"]
start_urls = ["https://rent.591.com.tw/home/search/rsList?is_new_list=1&type=1&kind=0&searchtype=1&region=1&firstRow=0&totalRows=9672"]

rules = [Rule(LinkExtractor(allow=('/search/rsList?is_new_list=1&type=1&kind=0&searchtype=1&region=1&firstRow=([30]{0,4})&totalRows=9672'),),
                                callback='parse_list', follow = True)]

def parse_list (self, response):
    jsondata = json.loads(response.text)
    house_detail_domain = "https://rent.591.com.tw/rent-detail-{0}.html"

    for i in range(99):
        print ("========================test===================")

    print (jsondata.keys())

    print (jsondata["status"])
    print (jsondata["records"])
    print (jsondata["is_recom"])

    #print (jsondata["data"])
    print (jsondata["data"].keys())

    #print (jsondata["data"]["biddings"]
    #print (jsondata["data"]["page"]
    print (jsondata["data"]["data"][0])

    #print (jsondata["data"]["topData"]

    print ("========================topdata===================")
    print ("========================test===================")

    print (jsondata["data"]["topData"][0].keys())
    print (jsondata["data"]["topData"][0].values())
    print (jsondata["data"]["topData"][0].items())
    print (jsondata["data"]["topData"][0])
    print ("========================test===================")
    print ("========================test===================")

    for topdata_house in jsondata["data"]["topData"]:
        print (topdata_house.items())
        for each_data in topdata_house.items():
            print (each_data)

    #print (jsondata["data"]["data"])
    print ("========================test===================")
    print ("========================data===================")

    print (jsondata["data"]["data"][0].keys())
    print (jsondata["data"]["data"][0].values())
    print (jsondata["data"]["data"][0].items())
    print (jsondata["data"]["topData"][0])

    print ("========================test===================")

    for data_house in jsondata["data"]["data"]:
        print (data_house.items())
        for each_data in data_house.items():
            print (each_data)

    for i in range(59):
        print ("========================topdata_house_link===================")

    for topdata_house in jsondata["data"]["topData"]:
    #            for each_data in topdata_house.items():
        print (topdata_house["post_id"])
        print (topdata_house["detail_url"])
        yield scrapy.Request(house_detail_domain.format(topdata_house["post_id"]), self.parse_house_detail)
        print (topdata_house["post_id"])
        print (topdata_house["detail_url"])

    for i in range(59):
        print ("========================data_house_link===================")

    for data_house in jsondata["data"]["data"]:
    #            for each_data in data_house.items():
        print (data_house["post_id"])
    #            print (data_house["detail_url"])
        yield scrapy.Request(house_detail_domain.format(data_house["post_id"]), self.parse_house_detail)
        print (data_house["post_id"])

    print ("========================test===================")

def parse_house_detail (self, response):
    house_detail = BeautifulSoup(response.text, "lxml")
    print ("===========================================")
    print (house_detail.select(".houseInfoTitle")[0].text)
    print ("===========================================")
    print (house_detail.select(".pageView")[0].text)
    print ("===========================================")
    print (house_detail.select(".detailInfo")[0].text)
    print ("===========================================")
    print (house_detail.select(".houseIntro")[0].text)
    print ("===========================================")
    print (house_detail.select(".lifeBox")[0].text)
    print ("===========================================")
    print (house_detail.select(".labelList")[0].text)
    print ("===========================================")
    print (house_detail.select(".facility")[0].text)
    print ("===========================================")
    print (house_detail.select(".userInfo"))
    print ("===========================================")
    print (house_detail.select(".banner"))
    print ("===========================================")
    print (house_detail.select("#show"))


text:
Q: Rails 4 - Nested resource routing I have a course and syllabus models defined like this
class Course < ActiveRecord::Base
    has_many :enrollments
    has_many :students, through: :enrollments, class_name: "User"
    has_many :syllabuses

end

class Syllabus < ActiveRecord::Base
    belongs_to :course
end

Routes defined like this
resources :courses do
    resource :syllabuses
  end

My html has a link to edit syllabus
<%= link_to "Edit", edit_course_syllabuses_path, class: "btn btn-primary"  %>

rake routes shows me this
edit_course_syllabuses GET    /courses/:course_id/syllabuses/edit(.:format) syllabuses#edit

server log  shows the request processing like
Started GET "/courses/46/syllabuses/edit" for ::1 at 2015-02-04 20:55:43 +0530
Processing by SyllabusesController#edit as HTML
  Parameters: {"course_id"=>"46"}
  Syllabus Load (0.3ms)  SELECT  "syllabuses".* FROM "syllabuses" WHERE "syllabuses"."id" = $1 LIMIT 1  [["id", nil]]
Completed 404 Not Found in 2ms

ActiveRecord::RecordNotFound - Couldn't find Syllabus with 'id'=:

How to pass the syllabus id to the syllabus controller edit action ?

A: Since you have a has_many association, you also need resources :syllabuses (note the s).
Change that, restart the server and run the following code to see all routes:
bundle exec rake routes

Your path would be now edit_course_syllabuse and you can just use it like:
<%= link_to "Edit", edit_course_syllabuses_path(@syllabuse), class: "btn btn-primary"  %>

You can read more about nested resources in Raild guide


text:
Q: Install XCode 4.5 beta along XCode 4.3 to keep App Store publishing option What is the correct way to install Xcode 4.5 beta along existing Xcode 4.3 stable?
I want to keep App Store publishing option.
Last time i did install an Xcode beta, it wiped out my existing install and I wasn't able to push to the App Store anymore.
I guess with the new Xcode "AppStore sandboxed" packaging, there must be new ways to achieve that in a clean way.

A: Actually if you read the release notes, the file is already the app bundle. So there is no need to install. Just drag the budge to your Application folder and that is it.

A: I don't believe this messes with any NDAs. So...
Download. Install. Run. Right-click and keep it in Dock. Drag it to beside your standard Xcode icon and appreciate that this has PREVIEW written on it. Apple seems to have made this one elegant and easy, compared with the past.


text:
Q: How can you use GWT AutoBeans to parse a JSON message when some of the return values could be an object or a collection of objects? Is it possible to parse a JSON message using GWT AutoBeans when one of the objects returned may be a collection but not always?
For example, if I have a JSON message returning an author and his/her associated writings, it's possible that there could be zero or more books being returned.
{ "name" : "William Gibson", "books" : { bookname : "Neuromancer" } }

could be one response, but so could this:
{ "name" : "William Gibson", "books" : [ { bookname: "Neuromancer"}, { bookname : "Pattern Recognition" } ] }

When I attempt to model this with an interface to be used for marshalling with an AutoBean, I get "expecting indexed data" errors if only one book is returned.
Interface for the AutoBean:
public interface Author {
  @PropertyName(value="name")
  String getAuthorName();
  @PropertyName(value="book")
  List<String> getBooks();
}

Snippet of error:
java.lang.AssertionError: Expecting indexed data
at com.google.web.bindery.autobean.shared.impl.SplittableList.<init>(SplittableList.java:64)

Is this not possible with AutoBeans?
(Note: using GWT 2.5.0 GA)

A: If you have a List, AutoBeans expects a JSON array. That array could contain zero, one or more elements, but it has to be an array (or be absent).
I think you can make your getBooks method return a Splittable though. You could then know whether it's an array (isIndexed()) or not. If you need the array to contain objects, you'd then have to iterate on the array (size() and get(int)) and pass each element to AutoBeanCodex.decode() to decode them (or directly pass the splittable if it's not an array).


text:
Q: libGDX textured disappearing when tapping home button I am developing a mobile game for Android with libGDX. I have noticed that when I click the home button and then go back to the game, the player has disappeared. All other actors attached to the stage exist, and when I remove the code that moves the player it is also drawn. It only disappears when it is moving. I have done so much debugging, and sometimes the position seems to update corretly but the player is invisible, but sometimes it is just NaN. I have for example tried to save position and velocity in pause function and provide the player with them in the resume function, but nothing helps.
This is what I am doing in the player update function:
// When these lines are removed, the app works perfectly
velocity.add(0.0f, GRAVITY);
velocity.scl(deltaTime);
position.add(velocity);
velocity.scl(1/deltaTime);

It doesn't even help if I re-create the player in resume function
player2 = new Player(resourceManager.getRegion("player"), new Vector2(320.0f, 350.0f), 300.0f);

Finally I tried to create completely distinct player object that is drawn after the home button is clicked. It is visible, but is does not move:
player2 = new Player(resourceManager.getRegion("player"), new Vector2(320.0f, 350.0f), 300.0f);

A: Intrestingly enough I was dealing with the same issue today , every texture (actors) remains in screen after resume but not the main actor which was the one who was moving (main actor in my case). After hours debuging I found that when the game state changes between pause and resume the render method (mine looks like this) will get 0 for deltaTime:
 @Override public void render(float deltaTime) {
        update(delta);
        spriteBatch.setProjectionMatrix(cam.combined);
        spriteBatch.begin();
        spriteBatch.draw(background, cam.position.x - (WIDTH / 2), 0, WIDTH, HEIGHT);
....
   spriteBatch.end();}

deltaTime is time elapsed from last render.
apparently there is no time elapsed from pause to resume hence 0.
down the chain of actor updates I was updating my main actor like this
 velocity.scl(deltaTime);
 position.add(MOVEMENT * deltaTime, velocity.y);

which was passed 0 at very next render after resume hence the NaN (Not a Number).
anyway not sure if there is a better way to go about this or not but this is how I did, a simple check for zero deltaTime in my main actor update method and replace with a very small amount .001f : (please note in subsequent update deltaTime wont be zero and this if statment only get called once and exactly after resume)
     public void update(float deltaTime) {
            if (deltaTime <= 0) {
                deltaTime=.001f;
            }
        velocity.scl(deltaTime);
        position.add(MOVEMENT * deltaTime, velocity.y);
...
}

A: Oh yeah, I had the same issue before.
What I did was in onPause(), which is called when you press home button, I destroyed all assets references.
Then in onResume(), which is called when you're back, I reassigned the assets again.

A: render() method continue called when you press home button on Android so it's seems that you player position continue updating with gravity so when you resume your game you not able to see you player on screen so use a flag on position update code and change flag in pause() and resume() method of ApplicationListener interface.
enum GameState{
    PAUSED, RESUMED
}

GameState gameState;

@Override
public void create() {

    gameState=GameState.RESUMED;
    ...
}

@Override
public void render() {

    Gdx.gl.glClearColor(1,1,1,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    if(gameState==GameState.RESUMED) {
       velocity.add(0.0f, GRAVITY);
       velocity.scl(deltaTime);
       position.add(velocity);
       velocity.scl(1/deltaTime);
    }
}

@Override
public void pause() {
    gameState=GameState.PAUSED;
}

@Override
public void resume() {
    gameState=GameState.RESUMED;
}


text:
Q: Submitting file via PHP form gives "function.fopen Filename cannot be empty" warning So, I put a form on a client's web site, and he's asking me to modify it so that people can attach a photo or two. So I'm running some tests, and whenever I submit the form, I get this error:

Warning: fopen() [function.fopen]: Filename cannot be empty in
  /homepages/20/d153810528/htdocs/fabFormHandlerTEST.php on line 32
Warning: fread(): supplied argument is not a valid stream resource in
  /homepages/20/d153810528/htdocs/fabFormHandlerTEST.php on line 33
Warning: fclose(): supplied argument is not a valid stream resource in
  /homepages/20/d153810528/htdocs/fabFormHandlerTEST.php on line 100

Now, I'm guessing that for whatever reason, the file name is not being passed from the form. I'm not sending blanks, I'm actually clicking the "Browse" button and going right for a jpg.
First of all, here's the file input code from the HTML:
Picture #1 (optional)
<input type="file" name="picture1" id="picture1" />

When I click "Submit," the name should be sent to the form handler as "picture1", no?
Here's my PHP code to handle "picture1":
$file1name=$_FILES['picture1']['name'];
$file1type=$_FILES['picture1']['type'];
$file1size=$_FILES['picture1']['size'];
$file1temp=$_FILES['picture1']['tmp_name'];

And here are lines 32 and 33, where the trouble begins:
$fp1=fopen($file1name,"rb");
$file1=fread($fp1,$file1size);

I've tried replacing $file1name in the fopen() funciton with $file1temp, but that didn't make a difference.
I've confirmed that the server is set to allow fopen().
What am I missing???
EDIT
Here's the complete form:
<form enctype="multipart/form-data" name="contactRich" id="contactRich" method="post" action="fabFormHandlerTEST.php" onsubmit="return fabFormValidate()">

Contact

        Your name:
        <input type="text" id="cName" name="cName" size="31">

        Neighborhood or closest major intersection:
        <input type="text" name="cNeighborhood" size="31">

        Your phone number:
(Include area code)
        (<input type="text" size="3" maxlength="3" name="cAreaCode"/>) <input type="text" id="cNumber" name="cNumber" size="23" maxlength="8" onkeyup="addHyphen()">

        Your e-mail address:
        <input type="text" name="cEmail" size="31">

        What can we help you with?
        <select name="cTopic">
                <option value="null">(Please choose:)</option>
                <option value="an estimate">Estimate</option>
                <option value="bifold doors">Bifold doors</option>
                <option value="broken window ropes">Broken window ropes</option>
                <option value="door that won't stay shut">My door won't stay shut!</option>
                <option value="noisy doors">My door is noisy!</option>
                <option value="sticking doors">My door is sticking!</option>
                <option value="drywall repairs">Drywall repairs</option>
                <option value="garbage disposals">Garbage disposals</option>
                <option value="grab bars">Grab bars</option>
                <option value="your various services">(other)</option>
            </select>

        Any additional details?
        <textarea name="cAdditional" cols="27" rows="4" wrap="soft"></textarea>

        Picture #1 (optional)
        <input type="file" name="picture1" id="picture1" />

        Picture #2 (optional)
        <input type="file" name="picture1" id="picture1" />

        Picture #3 (optional)
        <input type="file" name="picture1" id="picture1" />

        <input type="submit" value="Submit" />

<input type="hidden" id="isValid" name="isValid" value="no" />
</form>

A: Apparently the value in $file1name is empty or NULL.  Back track the cause of the problem by temporarily adding print_r($_FILES);

A: PHP is telling you that $file1name does not contain anything; check that you set the correct enctype on the HTML form and go through the "Common Pitfalls" section.


text:
Q: An optimization problem related to parabolas, yields a hard to solve derivative
Hello, I have came up with what I think is a unique optimization problem.
We are given the positive real parameters $k,t$. $t$ is the height of the rectangle, and $k$ is half of its width (see the picture).
Let the parabola intersect the $x$-axis at $x=p, -p$ and pass through the top vertices: $(k,t), (-k,t)$ of the rectangle. The equation of the parabola is: $$y=ax^2+c$$ $c > t > 0$, $a < 0$. We want to find $a,c$ such that the length of the parabolic curve from $-p$ to $p$ is minimized (note that $p$ is dependent on $a$ and $c$).
My work on the problem so far:
notice that $(k,t)$ is a point on the parabola. So:
$$ak^2+c=t$$
$$c=t-ak^2$$
So know we really just need to find $a$.
let us solve for $p$ ($x$ intersection):
$$ap^2+c=0$$
$$p=\sqrt{\frac{-c}{a}}=\sqrt{\frac{ak^2-t}{a}}=\sqrt{\frac{t-ak^2}{-a}}=\frac{\sqrt{t-ak^2}}{\sqrt{-a}}$$
recall that the length of a curve from $-p$ to $p$ is given by:
$$\int _{-p}^p\:\sqrt{1+\left(\frac{dy}{dx}\right)^2}dx$$
By symmetry, the length of the parabola from $-p$ to $p$ will be 2*length of the parabola from $0$ to $p$.
Subsituting:
$$2\int _{x=0}^{x=p}\:\sqrt{1+\left(2ax\right)^2}dx$$
This integral is quite easy to solve with trig substitution. After solving I got that:
$$f\left(a\right)=\frac{2ap\sqrt{1+4a^2p^2}+ln\left(2ap+\sqrt{1+4a^2p^2}\right)}{2a}$$
Note that $p$ is not a constant, because it is dependant on $a$.
It seems as though we have made progress, we have managed to build a function, dependant on only one variable, that returns the length of the curve. The function works and returns a correct result (I have verefied it with a couple of examples) but the derivative is very long and i doubt that it is solvable. I am quite stuck here with my current knowledge. But I am positive because when you graph the function on desmos there is indeed one local minimum for $a < 0$.
An easier variant is trying to minimize the area blocked by the parabola and the $x$ axis. It was much easier to solve...


text:
Q: AJAX call fails depending on position in code, browser fires document.ready mid-call. Twitter Bootstrap issue? I am chasing a nasty issue. An AJAX call in an onclick handler does not complete, as the browser fires document.ready mid-call. When tracing the readystate and status in the Firebug console I get:

*

*READYSTATECHANGE:1 STATUS:0

*READYSTATECHANGE:2 STATUS:0

*READYSTATECHANGE:4 STATUS:0

*Document Ready (-> this is the
second firing, breaking everything as the UI is rewired )

I believe I am not facing a cross-domain security block as the same AJAX call will complete correctly when called elsewhere in the page.
I am using Jquery 1.8.1 and I have tried multiple variations of AJAX client calls (i.e.
$.getJSON
$.ajax

as well as using the standard XMLHttpRequest object.
Has anyone seen this before? Pointers for deeper debugging would be fantastic.

A: After having debugged the issues I now have a work around. My AJAX call was invoked from a click handler linked to a Twitter Bootstrap Button. Clicking the button triggered the AJAX call but also a window.load event, which refreshed the JS application.
My work around was to replace the <button>..</button> with an <input>..</input> field, see below:
<form class="form-search">
    <label>Enter search string:
        <input id="SearchString" type="text" class="input-medium search-query">
        <!-- Broken: <button id="SearchAction" type="submit" class="btn btn-primary"> Search </button> -->
        <!-- This works: -->
        <input type="button" id="SearchAction" value="Go Find"/>
        <img id="RssAction" style="vertical-align:bottom" src="images/feed-icon-14x14.png">
    </label>
</form>

This may not be the root cause yet.


text:
Q: Why does 'IIS on the server' behave differently than 'Local IIS' and 'IIS Express'? (ASP.NET Core + Angular + Windows Authentication) If I create an ASP.NET Core + Angular project and enable Windows Authentication (following these instructions link) and debug it using IIS Express, why does the Angular app load if I open the browser with a local user (runas /user:MY-PC\local-user Chrome.exe) which is not in AD? Shouldn't IIS Express ask me for credentials?
If I publish to Local IIS (with Windows Authentication enabled and Windows Hosting Bundle installed) using Web Deploy I get the same result, Angular app loads and Local IIS does not ask for credentials. I tried splitting the project with ASP.NET Core API + Angular, but I got the same result. I had to implement an endpoint with some logic to return 401 (not network user), 403 (network user but not in my AD Group) and a Guard in Angular to avoid loading the Component and 401 and 403 pages.
However, when I did publish to IIS on the server (manually, I created the website and copied the files, and installed Windows Hosting Bundle), I realized the behavior is different, the Angular app is not loaded and IIS always asks for credentials. If I put wrong credentials or click on Cancel, IIS shows 401. With the correct credentials I can access and browser will remember them, but if I close and open the browser again, I need to re-enter my credentials, which is a bit annoying.
IIS Express and Local IIS never ask me for credentials when I open a normal browser (using my AD account).
Why does 'IIS on the server' behave differently than 'Local IIS' and 'IIS Express'?


text:
Q: Multiple next / previous One of my custom post types requieres multiple next/precious post titles buttons for usability issues. Does anyone know how to get this working?
Example:
LATEST POST (Today)
[previous post title] - [previous post title] - [previous post title]
YESTERDAY POST
[next post title] - [previous post title] - [previous post title]
LAST POST
[next post title] - [next post title] - [next post title]
Thanks in advance.

A: You should try Ambrosite Next/Previous Post Link Plus. It gives you the option of displaying multiple next or previous links among a number of other great options.


text:
Q: AutoNumber per group box in crystal report I'd like to add Auto Number per group box in crystal report. Here I use Record Number but it increases by group box.
Report View

The AutoNumber will be at the front of Barcode Column. How to set it per group box?

A: To get an incremental number for each record displayed in a group you need to do use a Running Total Field.

*

*Create a new Running Total Field

*Give it a suitable name

*The Field to summarize can be any field, in your case Barcode

*The Type of Summary should be Count

*In the Evaluate section you need to select For each record

*In the Reset section you need to select On Change of group and then select the Group Name from the drop down.

*Place this Running Total Field next to the Barcode field.

This should give you an incremental number for each record in your group.


text:
Q: IOS Push Notification not working in Producation: fwrite(): SSL: Broken pipe I am using apple push notification to send notifications to a user when an other user send him a message.
The code i am using is working fine in development mode but when i uploaded my app to app store my users don't get notifications.
So I have created a new pem file (BUT WITH PRODUCATION certification) according to this tutorial(same tutorial i have used for producation):
http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1
**In apple member center the notification is enable for the Distribution mode
But now there is a problem, when the server try to send the notification:
fwrite(): SSL: Broken pipe'
My Code:
 $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', 'file.pem');
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

        // Open a connection to the APNS server
        $fp = stream_socket_client(
                     'ssl://gateway.sandbox.push.apple.com:2195', $err,
                     $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

        if (!$fp)
            return;

    $message = "Hello world";
    $deviceToken = "token...";

    // Create the payload body
        $body['aps'] = array('alert' => $message,
                             'sound' => 'default');

        // Encode the payload as JSON
        $payload = json_encode($body);

        // Build the binary notification
        $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

        // Send it to the server
        $result = fwrite($fp, $msg, strlen($msg));

        // Close the connection to the server
        fclose($fp);

I don't know what to do, I have searched all the web for a solution with no good results.
Hope you will help me, Thanks =)

A: You are sending the notification to the sandbox server - ssl://gateway.sandbox.push.apple.com:2195
You should send it to the production server ssl://gateway.push.apple.com:2195

A: I m getting the same issue on production and resolve the issue using below steps.
you need to change in one line, and need to closed the connection adding one additional line. I have describable below line line line.
Step 1: Change below
From
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195',
$err,
$errstr,
60,
STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT,
$ctx);

To below:
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195',
$err,
$errstr,
60,
STREAM_CLIENT_CONNECT,
$ctx);

Step 2: add below line just before the "$result = fwrite($fp, $msg, strlen($msg));"

stream_set_blocking($fp, 0);


text:
Q: Rails link_to not working correctly I am trying to put in a link_to on my table to go to the show action but it is putting the URL as /admin/vulnerabilities.object_id instead of /admin/vulnerabilities/object_id
my index view is:
...
<% @vulnerabilities.each do |vulnerability| %>

    <%=link_to vulnerability.id, admin_vulnerabilities_path(vulnerability) %>
    <%= vulnerability.type %>
    <%=h truncate(vulnerability.description, :length => 80) %>
    <%= vulnerability.published %>
    <%= vulnerability.modified %>
    <%= link_to vulnerability.href, vulnerability.href , target: :_blank %>

<% end %>
...

I have a show.html.erb template setup and my show action is as follows:
def show
  @vulnerabilities = Vulnerability.find(params[:id])
end

From what I can see, this should work but when clicking the links it just redirects to the index page, effectively refreshing it and not using my show page at all.

A: It would be helpful if you added the relevant parts of your routes.rb file to your question, but I speculate that the problem is that admin_vulnerabilities_path(vulnerability) should be admin_vulnerability_path(vulnerability).
Also, as noted in the comments, it is probably better to use @vulnerability as your instance name since find will return a single record.


text:
Q: Swapping JButton elements in Java updated my code I realized I should have but the actionListener on the JButton (since they're the ones actually doing all the work). My logic is off now on the sorting part. I'm able to get the jButtons to swap values, but I've got the output looking correct, but I'm trying to figure out where I'm screwing up my sorting mechanism. This program "should" work correctly by selecting a start point with the radio button, and selecting a different location for the JButton to swap. (for instance, radio 3 then jbutton 8 would move the 3rd element into the 8th location) I know I'm pretty close, but I've worked myself into a rut and can't see out. Any pointers? (disclaimer This is a bonus points programming 2 assignment).
new code
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class GUIswitch
{
    public static void main(String[] args)
    {

        GUIswitchClass myWindow = new GUIswitchClass();
        myWindow.setSize(300,350);
        myWindow.setLocation(100,100);
        myWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        myWindow.setVisible( true );

    }
}
//====================================================================================================================
class GUIswitchClass extends JFrame                                         //fields
{
        JPanel          leftPanel       =   new JPanel();
        JPanel          rightPanel      =   new JPanel();
        JPanel          allPanel        =   new JPanel();
        JRadioButton    rdoBut[]        =   new JRadioButton[10];
        JButton         teamBut[]       =   new JButton[10];
        ButtonGroup     rdBtGp          =   new ButtonGroup();
        String          rdoButNum[]     =   {"1","2","3","4","5","6","7","8","9","10"};
        String          teamName[]      =   {"A","BB","CCC","DDDD","EEEEE","FFFFFF",
                                            "GGGGGGG","HHHHHHHH","IIIIIIIII","JJJJJJJJJJ"};
        //String            from;
        //String            to;
        int from;
        int to;
        String fromTo;  //??
        int i;

    public GUIswitchClass()                                                 //constructor
    {
        super("Proj 3");

        fromTo  = setButs();
        //to        = teamBut[ teamName[i] ];

    }
    private String setButs()
    {
        int i;
        leftPanel.setLayout(new GridLayout(10,1));
        rightPanel.setLayout(new GridLayout(10,1));
        for(i=0;i<10;i++)
        {
            rdoBut[i] = new JRadioButton(rdoButNum[i]);
            rdoBut[i].setFont(new Font("Courier", Font.PLAIN, 30) );
            rdBtGp.add(rdoBut[i]);
            leftPanel.add(rdoBut[i]);
        }

        /*for(i=0;i<10;i++)
            if(rdoBut[i].isSelected() )
            {
                from = Integer.parseInt(rdoBut[i].getText() );
            }
        */
        for(i=0;i<10;i++)
        {
            teamBut[i]  =   new JButton(teamName[i]);
            teamBut[i].setFont(new Font("Courier", Font.PLAIN, 30) );
            teamBut[i].setHorizontalAlignment(SwingConstants.LEFT);
            teamBut[i].addActionListener(new checkHdlr() );
            rightPanel.add(teamBut[i]);
        }

        allPanel.setLayout(new BorderLayout());
            allPanel.add(leftPanel, BorderLayout.WEST);
            allPanel.add(rightPanel, BorderLayout.CENTER);
        add(allPanel);

        return fromTo;

    }
    @SuppressWarnings("unused")
    private class checkHdlr implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            //String userNum;
            //userNum = event.getActionCommand();
            for(i=0;i<10;i++)
                if(rdoBut[i].isSelected() )
                {
                    from = Integer.parseInt(rdoBut[i].getText() );
                }

            for(i=0;i<10;i++)
            {
                if(event.getSource() == teamBut[i])
                {
                    //teamBut[i].
                    teamBut[i].setText(teamName[i]);
                    //to = (int)(teamBut[i]);
                }
            }
            rightPanel.revalidate();                //refresh the panels
            moveTeam(teamName, from, to);
        }
    }

//--------------------------------------------------------------------------
     public void moveTeam(String teamName[],int from,int to)
      {
        //int             from=0;
        //int             to=0;

        if(from>to)                           //determine direction to move
          moveUp(teamName,from,to);
        else
          moveDown(teamName,from,to);
      }

 //---------------------------------------------------------------------move up
  public static void moveUp(String teamList[], int from, int to)
  {
    String clipboard;
    int    row;

    clipboard = teamList[from];           //copy

    for(row=from;row>to;row--)            //shift others down
      teamList[row] = teamList[row-1];

    teamList[row] = clipboard;            //paste
  }
  //-------------------------------------------------------------------move down
  public static void moveDown(String teamList[], int from, int to)
  {
    String clipboard;
    int    row;

    clipboard = teamList[from];           //copy

    for(row=from;row<to;row++)            //shift others up
      teamList[row] = teamList[row+1];

    teamList[row] = clipboard;            //paste
  }

}

old code
import java.awt.*;
import java.awt.event.*;
import java.util.StringTokenizer;

import javax.swing.*;

public class GUIswitch
{
    public static void main(String[] args)
    {

        GUIswitchClass myWindow = new GUIswitchClass();
        myWindow.setSize(300,350);
        myWindow.setLocation(100,100);
        myWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        myWindow.setVisible( true );

    }
}
//====================================================================================================================
class GUIswitchClass extends JFrame                                         //fields
{
        JPanel          leftPanel       =   new JPanel();
        JPanel          rightPanel      =   new JPanel();
        JPanel          allPanel        =   new JPanel();
        JRadioButton    rdoBut[]        =   new JRadioButton[10];
        JButton         teamBut[]       =   new JButton[10];
        ButtonGroup     rdBtGp          =   new ButtonGroup();
        String          rdoButNum[]     =   {"1","2","3","4","5","6","7","8","9","10"};
        String          teamName[]      =   {"A","BB","CCC","DDDD","EEEEE","FFFFFF",
                                            "GGGGGGG","HHHHHHHH","IIIIIIIII","JJJJJJJJJJ"};
        String          from;
        String          to;
        String fromTo;
        int i;

    public GUIswitchClass()                                                 //constructor
    {
        super("Swap Elements");

        fromTo  = setButs();
        //to        = teamBut[teamName[i]];

    }
    private String setButs()
    {
        int i;
        leftPanel.setLayout(new GridLayout(10,1));
        rightPanel.setLayout(new GridLayout(10,1));
        for(i=0;i<10;i++)
        {
            rdoBut[i] = new JRadioButton(rdoButNum[i]);
            rdoBut[i].setFont(new Font("Courier", Font.PLAIN, 30) );
            rdoBut[i].addActionListener(new checkHdlr() );
            rdBtGp.add(rdoBut[i]);
            leftPanel.add(rdoBut[i]);
        }

        for(i=0;i<10;i++)
        {
            teamBut [i] =   new JButton(teamName[i]);
            teamBut[i].setFont(new Font("Courier", Font.PLAIN, 30) );
            teamBut[i].setHorizontalAlignment(SwingConstants.LEFT);
            rightPanel.add(teamBut[i]);
        }

        allPanel.setLayout(new BorderLayout());
            allPanel.add(leftPanel, BorderLayout.WEST);
            allPanel.add(rightPanel, BorderLayout.CENTER);
        add(allPanel);

        return fromTo;

    }
    @SuppressWarnings("unused")
    private class checkHdlr implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            String userNum;
            userNum = event.getActionCommand();

        }
    }

//--------------------------------------------------------------------------
     public static void moveTeam(String teamName[],String fromTo)
      {
        int             from;
        int             to;

        if(from>to)                           //determine direction to move
          moveUp(teamName,from,to);
        else
          moveDown(teamName,from,to);
      }

 //---------------------------------------------------------------------move up
  public static void moveUp(String teamList[], int from, int to)
  {
    String clipboard;
    int    row;

    clipboard = teamList[from];           //copy

    for(row=from;row>to;row--)            //shift others down
      teamList[row] = teamList[row-1];

    teamList[row] = clipboard;            //paste
  }
  //-------------------------------------------------------------------move down
  public static void moveDown(String teamList[], int from, int to)
  {
    String clipboard;
    int    row;

    clipboard = teamList[from];           //copy

    for(row=from;row<to;row++)            //shift others up
      teamList[row] = teamList[row+1];

    teamList[row] = clipboard;            //paste
  }
  //---------------------------------------------------------------------display
  public static void disp(String teamList[])
  {
    int r;
    for(r=0;r<10;r++)
      System.out.printf("%2d %s\n",r+1,teamList[r]);
  }
}

A: I wouldn't swap JButtons per se, but rather give the JButton's AbstractActions and simply swap these Actions as that is immeasurably easier to do. Or you could swap the JButton's text and actionCommand (you should do both if you're going this route), but that would involve doing parallel swaps and doesn't feel as clean to me.

A: I'd replace the JRadioButtons with JCheckBoxs, mostly because you can have two selected at the same time and it makes more sense to allow check boxes to be selected this way then it does to allow radio buttons.
I would create a single action listener for all the check boxes, so every click goes through it.
In the action listener, I would use a java.util.List to keep track of the currently selected options (you could walk the array, but I found this to be simpler).
When the list contains two items I would...

*

*Deselect the two check boxes and empty the list

*Get each of the check boxes current index (or Z order) using Container.getComponentZOrder(Component)

*Find the corresponding buttons from the left panel (this is achieved by using the index value retrieved in the previous step), using Container.getComponent(int)

*Swap the components.  This is achieved by using setComponentZOrder(Component, int)
Some thing like...
int index0 = leftPanel.getComponentZOrder(cb0);
int index1 = leftPanel.getComponentZOrder(cb1);

Component comp0 = rightPanel.getComponent(index0);
Component comp1 = rightPanel.getComponent(index1);

rightPanel.setComponentZOrder(comp0, index1);
rightPanel.setComponentZOrder(comp1, index0);

You'll also need to revalidate() on the frame to update the layout ;)


text:
Q: Spring Boot JMS: access receiveMessage() result via a (RxJava) subscription? How can I access a JMS message receipt with e.g. 'receiveMessage( )' in a RxJava subscription like manner?
I don't want to do this in a callback style. I want to have the details of the implementation, like @JmsListener, to be hidden from the caller.
For example, I have a typical method called when there is a message available at a JMS queue.
@JmsListener(destination = "mailbox", containerFactory = "myFactory")
public void receiveMessage(Email email) {
    logger.info("Received <" + email + ">");
}

How can I access available messages via a (RxJava) subscription?
receiver.subscribe( message -> { ... });

A: Just use a RxJava Subject. I know that Observables are a bit better.
PublishSubject<String> source; = PublishSubject.create();

public PublishSubject<String> getMessages() {
    source = PublishSubject.create();
    return source;
}

@JmsListener(destination = "mailbox", containerFactory = "myFactory")
public void receiveMessage(Email email) {
    logger.info("Received <" + email + ">");
    source.onNext( email.getmessage());
}

Give the consumer the Subject. It could call:
source.subscribe( f -> System.out.println( "Subscriber1: " + f));


text:
Q: Erros no programa para classificar um triângulo Estou com alguns problemas e não sei como corrigir:
1) Um triângulo equilátero, três lados iguais e ângulos = 60°, é lido como um triângulo isósceles (dois lados iguais).
2) Além de imprimir errado, eu não consigo retirar esse 'NONE'.
3) Quando o triângulo tem um dos ângulos = 90, ele é retângulo. Mas o programa não reconhece.
4) O quarto e último problema é que eu não sei como posso reiniciar o programa:
'Digite S para reiniciar ou N para finalizar o programa'
Alguém pode me ajudar ???
import math

# lado a
a = int(input('Digite o valor de um dos lados do triângulo '))

# lado b
b = int(input('Digite o valor do outro lado do triângulo '))

# angulo entre a e b
m = int(input('Digite o ângulo entre estes dois lados '))
ab = (m*math.pi)/180

# calculo do lado c
def lado_c ():
    global a,b,c,ab
    c = math.sqrt(a**2 + b**2 - 2*a*b*math.cos(ab))
    return round(c,2)

# angulo entre a e c
def angulo_ac ():
    global a,b,c,ac
    n = ((a**2+c**2)-(b**2))/(2*a*c)
    ac = (math.acos(n)*180)/math.pi
    return (round(ac,2))

# angulo b e c
def angulo_bc ():
    global a,b,c,bc
    p = ((c**2+b**2)-(a**2))/(2*b*c)
    bc =(math.acos(p)*180)/math.pi
    return (round(bc,2))

# perímetro
def perimetro ():
    global P,a,b,c
    P =(a+b+c)
    return P

# área
def area ():
    global a,b,c,P,A
    p = (a+b+c)/2
    A = float(math.sqrt(p*(p-a)*(p-b)*(p-c)))
    return A

# altura
def altura ():
    global A
    h = (A*2)/c
    return h

# classificação quanto aos lados
def lado_class ():
    global a,b,c,ab
    if a!=b and a!=c and b!=c:
        print ('Escaleno')
    elif ab == 60 and a == b and b == c:
        print ('Equilátero')
    elif a != b and b == c or b !=c and c == a or c !=a and a==b:
        print ('Isósceles')
    return

# classificação quanto aos angulos
def angulo_class ():
    global ab, ac, bc
    if ab == 90 or bc == 90 or ac == 90:
        print ('Retângulo')
    elif ab < 90 and bc < 90 and ac < 90:
        print ('Acutângulo')
    elif ab > 90 and bc < 90 and ac < 90   or   bc > 90 and ac < 90 and ab < 90    or   ac > 90 and ac < 90 and ab < 90 :
        print ('Obtusângulo')
    return

#-----------------------------------------------------------------------------
print ('Lado c = '+ str(round(lado_c (),2)))

print ('Ângulo entre a e c '+str(angulo_ac ()))
print ('Ângulo entre b e c '+str(angulo_bc ()))
print('Área = '+str(round(area (),2))+' unidades de área')
print('Perímetro = '+str(round(perimetro(),2))+' unidades de comprimento')
print ('Altura, em relação ao lado c = '+str(round(altura (),2))+' unidades de comprimento')
print(lado_class ())
print (angulo_class ())

> import math

# lado a
a = int(input('Digite o valor de um dos lados do triângulo '))

# lado b
b = int(input('Digite o valor do outro lado do triângulo '))

# angulo entre a e b
m = int(input('Digite o ângulo entre estes dois lados '))
ab = (m*math.pi)/180

# calculo do lado c
def lado_c ():
    global a,b,c,ab
    c = math.sqrt(a**2 + b**2 - 2*a*b*math.cos(ab))
    return round(c,2)

# angulo entre a e c
def angulo_ac ():
    global a,b,c,ac
    n = ((a**2+c**2)-(b**2))/(2*a*c)
    ac = (math.acos(n)*180)/math.pi
    return (round(ac,2))

# angulo b e c
def angulo_bc ():
    global a,b,c,bc
    p = ((c**2+b**2)-(a**2))/(2*b*c)
    bc =(math.acos(p)*180)/math.pi
    return (round(bc,2))

# perímetro
def perimetro ():
    global P,a,b,c
    P =(a+b+c)
    return P

# área
def area ():
    global a,b,c,P,A
    p = (a+b+c)/2
    A = float(math.sqrt(p*(p-a)*(p-b)*(p-c)))
    return A

# altura
def altura ():
    global A
    h = (A*2)/c
    return h

# classificação quanto aos lados
def lado_class ():
    global a,b,c,ab
    if a!=b and a!=c and b!=c:
        print ('Escaleno')
    elif ab == 60 and a == b and b == c:
        print ('Equilátero')
    elif a != b and b == c or b !=c and c == a or c !=a and a==b:
        print ('Isósceles')
    return

# classificação quanto aos angulos
def angulo_class ():
    global ab, ac, bc
    if ab == 90 or bc == 90 or ac == 90:
        print ('Retângulo')
    elif ab < 90 and bc < 90 and ac < 90:
        print ('Acutângulo')
    elif ab > 90 and bc < 90 and ac < 90   or   bc > 90 and ac < 90 and ab < 90    or   ac > 90 and ac < 90 and ab < 90 :
        print ('Obtusângulo')
    return

#-----------------------------------------------------------------------------
print ('Lado c = '+ str(round(lado_c (),2)))

print ('Ângulo entre a e c '+str(angulo_ac ()))
print ('Ângulo entre b e c '+str(angulo_bc ()))
print('Área = '+str(round(area (),2))+' unidades de área')
print('Perímetro = '+str(round(perimetro(),2))+' unidades de comprimento')
print ('Altura, em relação ao lado c = '+str(round(altura (),2))+' unidades de comprimento')
print(lado_class ())
print (angulo_class ())

Eu também publiquei o código aqui (é melhor para visualizar):
https://code.sololearn.com/cUh4dY3oul2A/#py

A: As questões 1 e 3 podem ser respondidas com a análise de suas variáveis e dos retornos das suas funções. Em um exemplo em que defino um dos lados do triangulo como 50, outro lado como 50 e o ângulo entre eles de 60°, vou obter como resposta do seu script:
a: 50                         # Valor do lado a - int
b: 50                         # Valor do lado b - int
c: 49.99999999999999          # Valor do lado c não arredondado
m: 60                         # Ângulo ab (graus) - int
ab: 1.0471975511965976        # Ângulo ab (radianos) não arredondado
ac: 60.00000000000001         # Ângulo ac (graus) não arredondado
bc: 60.00000000000001         # Ângulo bc (graus) não arredondado
lado_c: 50.0                  # Valor do lado c arredondado ---- Retorno de função
angulo_ac: 60.0               # Ângulo ac (graus) arredondado ---- Retorno de função
angulo_bc: 60.0               # Ângulo bc (graus) arredondado ---- Retorno de função

A partir desses dados é possível ver o porquê das suas funções retornarem com alguns erros. Ao analisar a função lado_class() temos:
def lado_class ():
    global a,b,c,ab
    if a != b and a != c and b != c:
    """ Comparação a, b e c.
        Sua variável c não está arredondada, o que vai influenciar na sua comparação.
    """
        print ('Escaleno')
    elif ab == 60 and a == b and b == c:
    """ Comparação a, b e c + análise do ângulo ab.
        Novamente sua variável c não está arredondada.
        A variável ab está definida como o ângulo entre a e b em RADIANOS,
        porém você compara ela com o valor em graus.
    """
        print ('Equilátero')
    elif a != b and b == c or b !=c and c == a or c != a and a == b:
    """ Comparação a, b e c.
        Novamente o mesmo problema com a variável c.
    """
        print ('Isósceles')
    return

O mesmo problema vai se repetir na sua função angulo_class(), porém com outras variáveis. Recomendo sempre ter conhecimento do retorno de todas as suas variáveis, mesmo que seja só para teste.
Para corrigir esse problema você tem duas opções: Ajuste as suas comparações ou modifique suas funções.
# Opção 1. Ajuste dos condicionais.
if a != b and a != lado_c() and b != lado_c():
    (...)

# Opção 2. Ajuste das funções.
def lado_c ():
    """ Arredonde a variável c, e não apenas o retorno da função.
        NOTA: Lembre-se que arredondar c irá influenciar
        os próximos cálculos que o utilizarem.
    """
    global a,b,c,ab
    c = round(math.sqrt(a**2 + b**2 - 2*a*b*math.cos(ab)))
    return c

Em relação à pergunta 2: O None é o retorno vazio da função que decorre da própria forma que você escreveu as suas funções. Vou trabalhar com apenas uma delas, mas o raciocínio é o mesmo para ambas.
def lado_class():
    global a,b,c,ab
    if a != b and a != c and b != c:
        print ('Escaleno')
    elif ab == 60 and a == b and b == c:
        print ('Equilátero')
    elif a != b and b == c or b != c and c == a or c != a and a == b:
        print ('Isósceles')
    return    # <----- Essa é a linha que está definindo o retorno vazio.

Você tem a duas opções para corrigir isso. A primeira é de mudar o retorno de sua função para:
def lado_class():
    global a,b,c,ab
    if a != b and a != c and b != c:
        return 'Escaleno'     # Nesse caso o retorno será 'Escaleno'.
    elif ab == 60 and a == b and b == c:
        return 'Equilátero'   # Nesse caso o retorno será 'Equilátero'.
    elif a != b and b == c or b != c and c == a or c != a and a == b:
        return 'Isósceles'    # E finalmente aqui o retorno será 'Isósceles'.

Escrita dessa forma a função não dará o print quando usada e sim apenas retornará o valor indicado. Nesse caso, se quiser dar um print no retorno da função você escreverá:
print(lado_class())

Se você não quiser modificar sua função você pode usá-la sozinha. Sem a necessidade do print:
angulo_class()

Assim você não imprimirá o retorno None da sua função. Como você já programou o print dentro da função, não há a necessidade de dar um print no retorno dela.
Em resumo: Ao definir uma função atente-se a quando usar return e print. (doc. return; doc. print)
Questão 4: Eu colocaria tudo dentro de um while, mas não sei se é a forma mais indicada de se fazer isso. O while roda seu script até que você dê a condição para ele parar (doc. while).
Exemplo com while:
import math

repetir = True

while repetir is True:

    ##### Seu script aqui #####

    consulta_repet = input('Deseja repetir? (S/N)')
    comando_ok = False

    while comando_ok is False:
        if consulta_repet.lower() == 's':
            repetir = True
            comando_ok = True
        elif consulta_repet.lower() == 'n':
            repetir = False
            comando_ok = True
        else:
            consulta_repet = input('Comando não entendido. Deseja repetir? (S/N)')

A: Você pode utilizar o código abaixo. Este código irá receber as medidas dos três lados do triângulo em uma mesma linha separados por apenas um espaço, em seguida o programa irá verificar se as medidas dos lados formam de fato um triângulo e, se de fato formarem um triângulo, retornará o tipo do triângulo.
O código é o seguinte...
continuar = True
while continuar == True:
    try:
        l = list(map(float, input('Medida dos lados: ').split()))
        l.sort(reverse=True)
        print()

        if l[0] >= (l[1] + l[2]):
            print('NAO FORMA TRIANGULO')
        else:
            if (l[0] ** 2) == (l[1] ** 2 + l[2] ** 2):
                print('TRIANGULO RETANGULO')
            if (l[0] ** 2) > (l[1] ** 2 + l[2] ** 2):
                print('TRIANGULO OBTUSANGULO')
            if (l[0] ** 2) < (l[1] ** 2 + l[2] ** 2):
                print('TRIANGULO ACUTANGULO')
            if l[0] == l[1] == l[2]:
                print('TRIANGULO EQUILATERO')
            if l[0] == l[1] != l[2] or l[1] == l[2] != l[0] or l[0] == l[2] != l[1]:
                print('TRIANGULO ISOSCELES')

        resposta = input('Digite "S" para reiniciar ou "N" para encerrar: ')
        while resposta not in 'SsNn':
            print(f'Valor INVÁLIDO! Digite apenas uma das duas letras sugeridas!')
            resposta = input('Digite "S" para reiniciar ou "N" para encerrar: ')
        if resposta == 's' or resposta == 'S':
            continuar = True
        else:
            break

    except:
        break

Como você pode notar, este algoritmo não precisa saber as medidas dos ângulo para os identifica-los. Ele os identifica analisando apenas o comportamento do maior lado em relação aos outros.
Para você utilizar corretamente este programa, basta rodar o programa e digitar as medidas dos lados na mesma linha, separados por um espaço, tal qual mostrado abaixo...
Medida dos lados: 3 4 5

... em seguida, digitar "Enter" e o programa resolverá a situação exibindo o seguinte resultado...
TRIANGULO RETANGULO
Digite "S" para reiniciar ou "N" para encerrar:

... e então, você pode digitar "S" ou "N", de acordo com a situação.


text:
Q: Is there a way to find the pod that was update after pod update in post_install Trying to catch the pod that was updated using
pod update
I want to catch the pod and eventually find its target(I know how to find the target)
what I wanted is there a way to catch  or target that got update in post_install

A: Go to terminal then,
cd ios
enter and type arch -x86_64 pod update then enter.
Now run application.
(On Mac m1 work for me)


text:
Q: Resizing Image according to window size for IE According the given script

It's work fine for chrome and firefox ... any idea how to make it work with IE 7, 8, 9
i tried many scripts and nothing work well like FF and chrome.

A: IE before 9 does not support background-size:
http://www.css3.info/preview/background-size/
You'll have to come up with a different technique to handle that case. See this for an explanation of workarounds:
http://kimili.com/journal/the-flexible-scalable-background-image-redux
If you want an example (I won't claim it's a great example, but technically speaking, it works), you can look at the code for this site that I worked on last year. The client wanted a background image that scaled to the size of the screen, but also changed when the slides rotated, so it gets a little scary, code-wise:
http://www.buzzhoney.com/
You're going to want to pay attention to the various settings in http://www.buzzhoney.com/Content/style.css
This site was also supposed to be responsive, so there are several levels of @media queries to look at, there. There is a lot in there, and I don't have time to repeat it all, but here are highlights:
Based on this shell of markup (I've removed all the extra stuff that would just get in the way of how these primary elements work together):

Starting around line 316, we set up initial styles for the background container and its image, but only for devices between 320px and 480px wide, for smartphones. At 416, however, we start to set up styles that will apply from devices 321px wide and up:
#background
{
    left: 0;
    min-height: 730px;
    overflow: hidden;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: -1;
    height:100%;
}

#background img
{
    left: 0;
    min-width: 1200px;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: -2;
    display:block;
    opacity:0;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    filter: alpha(opacity=0);
}

Note how the container (#background) is set to 100% width and height, with a min-height of 730px, and the image inside is set to 100% width, but is given no specific height, just a min-width of 1200px. This basically says that it will scale up, and height will change in proportion to its width, but the width will never go below 1200px, so at that point, the container will collapse around the image and hide the excess that doesn't fit within its area (overflow:hidden).
Note also, that I'm using position:fixed, and a left:0, top:0, to anchor the background container in place, and using a z-index:-1 to place it behind everything else.
There are minor modifications to add some other features at higher resolutions, but nothing alters this basic setup. For your purposes, unless you want the fading/changing backgrounds, you would remove the lines:
    opacity:0;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    filter: alpha(opacity=0);

as they'll make the background image invisible.


text:
Q: A lot of columns in INFORMATION_SCHEMA.COLUMNS don't exists in the actual table I need to create a dynamic query in Google Bigquery, and for that I'm using the INFORMATION_SCHEMA.COLUMNS.
the problem I'm facing that a lot of the columns in the COLUMNS table doesn't exist in the original table, what could be the reason for this problem?
I tried to compare between the columns that really exist in the table and other columns but they look the same and there's absolutely no difference between them
#standard SQL
SELECT
  CONCAT('select ',columns,',count(*) n from `',table_catalog,'.',table_schema,'.',table_name,'` group by ',columns)
FROM (
  SELECT
    STRING_AGG(column_name,', ') columns,
    table_name,
    table_catalog,
    table_schema
  FROM
    `MY_PROJECT.MY_DATASET.INFORMATION_SCHEMA.COLUMNS` a
  WHERE
    a.table_name = 'MY_TABLE'
    AND ordinal_position IS NOT NULL
    AND column_name <> 'EXCLUDED_COLUMN'
  GROUP BY
    table_name,
    table_schema,
    table_catalog);

The resulted query contains a lot of columns that are not in the actual table and running the resulted query keeps giving me the following error:
Unrecognized name {column_name} at {position}

A: This could be a side effect of Time Travel.  DROP and reCREATE the table, or just wait 7 days if that is an option for you.  See https://stackoverflow.com/a/69291989/7359502


text:
Q: An uncountable Hausdorff space such that every countable subset is closed is discrete Let $X$ be a topological space. Is the following claim true: If $X$ is uncountable, Hausdorff, and every countable subset of $X$ is closed, then $X$ is discrete.
This claim is false without the Hausdorff assumption (If every countable subset of a space is closed, is the topology discrete?), but the example given in the link does not work since it is not Hausdorff. I think my claim is not true (but not sure) and I cannot found a counterexample. Any hints?

A: Let $X=\Bbb R$; every point of $\Bbb R\setminus\{0\}$ is isolated, and open nbhds of $0$ are co-countable. Thus, the topology on $X$ is
$$\wp(\Bbb R\setminus\{0\})\cup\{\Bbb R\setminus C:C\subseteq\Bbb R\setminus\{0\}\text{ is countable}\}\,.$$
Every countable set is closed, and $X$ is Hausdorff, but $0$ is a limit point of $X\setminus\{0\}$.


text:
Q: Why is OneToMany relationship persisted in multiple rows in the Database I have a hibernate entity class
public class MyComplexClass implements  Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    String name;
    int number;
    @ElementCollection
    Map<String,String> myMap;

    @ManyToOne
    Simple simple;

    public MyComplexClass(String name, int number, Map<String,String> myMap) {
        this.name = name;
        this.port = number;
        this.myMap = myMap;
    }

    public MyComplexClass() {
        // TODO Auto-generated constructor stub
    }

    public void setName(String name) {
        this.name = name;

    }

    public String getName() {
        return name;
    }

    public void setNumber(int number) {
        this.port = number;
    }

    public int getPort() {
        return port;
    }

    public void setMyMap(Map<String,String> myMap) {
        this.myMap = myMap;
    }

    public Map<String,String> getMyMap() {
        return this.myMap;
    }

    public Simple getSimple() {
        return this.simple;
    }

And in the class simple I have a mapping of the form
    @Entity
    @Table(name = "Simple")

    public class Simple  implements Comparable<Simple>, Serializable {
    @JsonProperty
    @OneToMany(mappedBy="simple",fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    Set<MyComplexClass> myComplexClass;

    public void setMyComplexClass(List<MyComplexClass> myComplexClass) {
        this.myComplexClass = myComplexClass;
    }

    public List<MyComplexClass> getMyComplexClass() {
        return this.myComplexClass;
    }

Somewhere in the system I set the values as
Map<String, String> myMap = new HashMap<String,String>();
myMap.put("value","value");
MyComplexClass myComplexClass = new MyComplexclass("a", 123, myMap)
Set<MyComplexClass> myComplexClassList = new HashSet<MyComplexClass>();
myComplexClassList.add(myComplexClassList)
simple.setMyComplexClass(myComplexClassList);
myComplexClass.setSimple(simple);
// save to the database
dao.save(simple);

This gets persisted in the database with multiple rows for my complex class with the same foreign key for the simple classs
 Table: MyComplexClass
    id  name number simple_id
     1  abc   234    1
     2  abc   234    1
     3  abc   234    1
     4  abc   234    1
     5  abc   234    1
     6  xyz   432    2
     7  xyz   432    2
     8  xyz   432    2

What have I missed? The id for all these rows is different which makes me think that they have been initialized multiple times in the code. But they aren't. Any reason they have different entries? I am using AKKA actors, could that be a reason?
Based on various similar problems. I have changed the Collection to be a Set and also added a compareTo method as follows
public int compareTo(MyComplexClass o) {
        if (o == null) {
            return 1;
        }

        if (this.getName().equals(o.getName()) && this.getNumber() == o.getPort()) {
            return 0;
        }
        return (int) (id - o.id);
    }

A: I'd vote to close this example that doesn't compile and isn't complete if I could, but since it has a bounty I can't. You reference a dao object that you don't include source for. You call doa.save, is this a Spring question? Otherwise, there is nothing wrong with your entities, it all works just fine for me.
public class JPAExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence");
        EntityManager em = emf.createEntityManager();
        try {
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            Simple simple = new Simple();
            Map<String, String> myMap = new HashMap<String,String>();
            myMap.put("value","value");
            MyComplexClass myComplexClass = new MyComplexClass("a", 123, myMap);
            Set<MyComplexClass> myComplexClassList = new HashSet<MyComplexClass>();
            myComplexClassList.add(myComplexClass);
            simple.setMyComplexClass(myComplexClassList);
            myComplexClass.setSimple(simple);
            // save to the database
            em.persist(simple);
            tx.commit();
        } finally {
            emf.close();
        }
    }
}

Simple.class
@Entity
@Table(name = "Simple")
public class Simple implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id;
    //    @JsonProperty
    @OneToMany(mappedBy = "simple", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    Set<MyComplexClass> myComplexClass;
    public void setMyComplexClass(Set<MyComplexClass> myComplexClass) {
        this.myComplexClass = myComplexClass;
    }
    public Set<MyComplexClass> getMyComplexClass() {
        return this.myComplexClass;
    }
}

MyComplexClass
@Entity
@Table(name="MyComplexClass")
public class MyComplexClass implements  Serializable {
    private static final long serialVersionUID = 1L;
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id;
    String name;
    int number;
    @ElementCollection
    Map<String,String> myMap;
    @ManyToOne
    Simple simple;
    public MyComplexClass(String name, int number, Map<String,String> myMap) {
        this.name = name;
        this.myMap = myMap;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setMyMap(Map<String,String> myMap) {
        this.myMap = myMap;
    }
    public Map<String,String> getMyMap() {
        return this.myMap;
    }
    public Simple getSimple() {
        return this.simple;
    }
    public void setSimple(Simple simple ) {
        this.simple = simple;
    }
}

Produces the following output...
Hibernate: create table MyComplexClass (id bigint generated by default as identity (start with 1), name varchar(255), number integer not null, simple_id bigint, primary key (id))
Hibernate: create table MyComplexClass_myMap (MyComplexClass_id bigint not null, myMap varchar(255), myMap_KEY varchar(255), primary key (MyComplexClass_id, myMap_KEY))
Hibernate: create table Simple (id bigint generated by default as identity (start with 1), primary key (id))
Hibernate: alter table MyComplexClass add constraint FK_qlkwvh7xyrn3udhnrn40fl6f8 foreign key (simple_id) references Simple
Hibernate: alter table MyComplexClass_myMap add constraint FK_qp5xa90y7pk94lb64kvt62589 foreign key (MyComplexClass_id) references MyComplexClass
Jun 12, 2017 10:06:56 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Simple (id) values (default)
Hibernate: insert into MyComplexClass (id, name, number, simple_id) values (default, ?, ?, ?)
Hibernate: insert into MyComplexClass_myMap (MyComplexClass_id, myMap_KEY, myMap) values (?, ?, ?)
Jun 12, 2017 10:06:56 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:hsqldb:mem:standalone]

Which shows only one row inserted into the MyComplexClass table.
You can copy this code and use it to figure out what is wrong with your code.

A: Since you are using a Hash based collection Set, you must override equals and hashcode in your MyComplexClass entity.
From the docs

You have to override the equals() and hashCode() methods if you:
   intend to put instances of persistent classes in a Set (the recommended way to represent many-valued associations); and
  intend to use reattachment of detached instances

Overriding equals and hashcode should fix your problem.


text:
Q: How to store the string data in string 2D array in C++ I want to store data in the first element at the first index of 2D array t[0][0]!
 I write this code:
int main()
{
    string input;
    cout << "Enter string of code:\n";
    cin >> input;
    queue < string > m;
    string t[100][3];
    while (input != "^")
    {
        int i = 0;

        t[i][0] = input;
        m.push(t[i][0]);
        if (input == " ")
        {
            t[i + 1][0];
            break;
        }

        cin >> input;
        i++;

    }
    int c = 1;
    while (!m.empty())
    {
        int i = 0;
        t[i][0] = m.front();
        string temp;
        temp = t[i][0];
        t[i][1] = check(temp);
        //cout <<c<<" "<<t[i][0]<<" Is: " << t[i][1] << endl;
        c++;
        m.pop();
        i++;
    }
    cout << endl;

    cout << c << " " << t[0][0] << " Is: " << t[0][1] << endl;

    system("Pause");
    return 0;
}

I  have problem with this statement

cout << c << " " << t[0][0] << " Is: " << t[0][1] << endl;

this doesn't print the value in the array!

A: Declare and initialize i above the while loop, like this:
int i = 0;
while (!m.empty())
{
    t[i][0] = m.front();
    ...

Let me explain what happens (in your code) here:
while (!m.empty())
{
    int i = 0;
    t[i][0] = m.front();
    string temp;
    temp = t[i][0];
    t[i][1] = check(temp);
    //cout <<c<<" "<<t[i][0]<<" Is: " << t[i][1] << endl;
    c++;
    m.pop();
    i++;
}

Every time you enter the body of the loop, a variable named i is declared and initialized to 0. The scope of i is the body of the loop.
You increment i at the end of the loop, but as soon as the loop runs again, i will be again be initialized to 0 (you also re-declare it). So if we were in the second loop, you would want to i to have a value of 1, but because you initialize to 0 every time you enter the loop, it will always have a value of 0 as you are executing the body of the loop.

Moreover, this line:
t[i + 1][0];

should issue a warning of this kind:
main.cpp:22:23: warning: expression result unused [-Wunused-value]
            t[i + 1][0];
            ~~~~~~~~ ~^

I got by compiling your code like this:

g++ -Wall main.cpp

where the flag Wall enables all warnings, pretty cool, make this your friend.
It is helpful, as it happens now, since that line does nothing that has impact on your code.

PS: Of course, I don't know what is the check() you have in your code, so this is all I can say .


text:
Q: How to sort data via drop down list i am working on car dealer website where client can post different-different types of cars. Customer can categories or view the car on the basic of White plate or Yellow plate.
What my query id:
There is a category page where i am displaying all types of car by default. but i need when customer select any value from down down data will change as per selecting value. Here is the drop down code:
<form action="" method="post" enctype="multipart/form-data">

                    SORT BY
                    <select name="cartype" id="cartype" class="m-select">
                        <option value="" selected="">Select Car Type</option>
                        <?php
                            $query=mysql_query("select * from cartype");
                            while($display=mysql_fetch_array($query))
                                {
                        ?>
                        <option value="<?php echo $display['cartype']; ?>"><?php echo $display['cartype']; ?></option>
                        <?php
                            }
                        ?>
                    </select>

            </form>

This is my data display code:

                       <?php
                        $query=mysql_query("select * from productdetail");
                        while($display=mysql_fetch_array($query))
                            {
                       ?>

                                    <a href="details.php?id=<?php echo $display['id']; ?>"><img class='img-responsive' src="images/product/<?php echo $display['img']; ?>" width="400" height="300" alt='chevrolet'/>

                                        <a href="details.php?id=<?php echo $display['id']; ?>">
<?php echo $display['companyname']; ?>

<?php echo $display['make']; ?>

<?php echo $display['model']; ?>

<?php echo $display['status']; ?>

<?php echo $display['fueltype']; ?>

<?php echo $display['price']; ?>

<?php echo $display['kilometer']; ?>

                                            <a href="details.php?id=<?php echo $display['id']; ?>" class="btn m-btn">VIEW DETAILS

                        <?php
                            }
                        ?>

A:

<form action="" method="post" enctype="multipart/form-data">

                    SORT BY
                    <select name="cartype" id="cartype" onchange="myFunction()">
                        <option value="" selected="">Select Car Type</option>

                        <option value="VOLVO">VOLVO</option>

                    </select>

            </form>

Your result will display here


text:
Q: Change MAC address I've searched a lot on the internet and couldn't find a very good answer.
What I've tried:
I've tried to change the MAC address from registry programmatically but all of my methods failed.
This is my code
 private string readMAC()
    {
        RegistryKey rkey;
        string MAC;
        rkey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\0012", true); //--->this is the string to change
        MAC = (string)rkey.GetValue("NetworkAddress");
        rkey.Close();
        return MAC;
    }

I use win 10 but it's important to change this mac on every Windows like Win server and win 8,7


text:
Q: Adding a new string to the end of a specific line in a text file I'm new to python hence I am unable to implement the solutions I've found online in order to fix my problem.
I am trying to add a specific string to the end of a specific line to a textfile. As I understand text commands, I must overwrite the file if I don't want to append to the end of it. So, my solution is as follows:
    ans = 'test'
numdef = ['H',2]
f = open(textfile, 'r')
lines = f.readlines()
f.close()
f = open(textfile, 'w')
f.write('')
f.close()
f = open(textfile, 'a')
for line in lines:
    if int(line[0]) == numdef[1]:
        if str(line[2]) == numdef[0]:
                k = ans+ line
                f.write(k)
    else:
        f.write(line)

Basically, I am trying to add variable ans to the end of a specific line, the line which appears in my list numdef. So, for example, for

2 H: 4,0 : Where to search for information : google

I want

2 H: 4,0 : Where to search for information : google test

I have also tried using line.insert() but to no avail.
I understand using the 'a' function of the open command is not so relevant and helpful here, but I am out of ideas. Would love tips with this code, or if maybe I should scrap it and rethink the whole thing.
Thank you for your time and advice!

A: When you use the method
lines = f.readlines()

Python automatically adds "\n" to the end of each line.
Try instead of :

k = line+ans

The following:
k = line.rstrip('\n') + ans

Good luck!

A: Try this. You don't have an else case if it meets the first requirement but not the other.
ans = 'test'
numdef = ['H',2]
f = open(textfile, 'r')
lines = f.readlines()
f.close()
f = open(textfile, 'w')
f.write('')
f.close()
f = open(textfile, 'a')
for line in lines:
    if int(line[0]) == numdef[1] and str(line[2]) == numdef[0]:
        k = line.replace('\n','')+ans
        f.write(k)
    else:
        f.write(line)
f.close()

Better way:
#initialize variables
ans = 'test'
numdef = ['H',2]
#open file in read mode, add lines into lines
with open(textfile, 'r') as f:
    lines=f.readlines()
#open file in write mode, override everything
with open(textfile, 'w') as f:
    #in the list comprehension, loop through each line in lines, if both of the conditions are true, then take the line, remove all newlines, and add ans. Otherwise, remove all the newlines and don't add anything. Then combine the list into a string with newlines as separators ('\n'.join), and write this string to the file.
    f.write('\n'.join([line.replace('\n','')+ans if int(line[0]) == numdef[1] and str(line[2]) == numdef[0] else line.replace('\n','') for line in lines]))


text:
Q: Flask-Bootstrap, flask-wtf, adding class to submit button I'm using a flask-wtf submit button as follows:
 {{ wtf.form_field(form.submit, button_map={'submit': 'primary'}) }}

I want to add a class to the submit button but I can not find anything about that,
I'm pretty new with this but this http://pythonhosted.org/Flask-Bootstrap/basic-usage.html#templates did not helped me a lot.
Anything to recommend?

A: It's super-easy, usually, so unless Flask-Bootstrap does something odd you can just tell it what you want the class to be:
{{ wtf.form_field(form.submit, class="something", button_map={'submit': 'primary'}) }}

Generally, anything you pass to the rendering function that isn't recognised will be added as a parameter to the html, so you can do things like:
{{ wtf.form_field(form.submit, cats="mew") }}

And your resulting html field would be something like <input cats="mew" id="name" name="name" type="text" value="">


text:
Q: SQL AVG over subset of rows I'm having trouble with an average I'm trying to calculate in a frequently run query. This fiddle should show what I've got so far:
http://sqlfiddle.com/#!3/6afa9/4
Ideally I'd like to restrict the average calculation to just the 4 most recently submitted reports. So the expected result should be something like
+----+---------+
| id | runtime |
+----+---------+
|  1 |     600 |
|  2 |     660 |
+----+---------+

I've tried OVER PARTITION but couldn't seem to find something that was close to what I wanted.

A: You can embed a ROW_NUMBER() into CTE to get the most recent 4 runs by date finished.
;WITH cte AS (
  SELECT
    id,
    DATEDIFF(minute, started, finished) AS runtime,
    ROW_NUMBER() OVER (PARTITION BY id ORDER BY finished DESC) AS RowNum
  FROM report
)
  SELECT
    id,
    AVG(runtime) AS AvgRuntime
  FROM cte
  WHERE RowNum <= 4
  GROUP BY id

Yields these results
| ID | AVGRUNTIME |
|----|------------|
|  1 |        600 |
|  2 |        660 |

Link to SQL Fiddle: http://sqlfiddle.com/#!3/6afa9/8/0


text:
Q: Closest distance between 2 convex hulls I have two non-convex meshes and I want to find the closest distance between them. An approximate value is enough for my needs (as long as it does not deviate too much from the true value).
I break the non-convex meshes in many convex parts, and for speed reasons I also find the convex hulls of each convex part.
Then, I test the distances for all combinations between the hulls of the first and the second mesh. The shortest one defines the closest distance between the two meshes.
I already have a working solution with CGAL's Optimal Distances package (see image below). The result is nice, but the runtime is not ideal, actually it is the main bottleneck in my pipeline.
It makes sense that this problem is resource intensive, but it would be really nice to have a faster alternative with CGAL or another library or approach that gives a similar result. Unfortunately I have not found any alternative up to now.

Update:
The link provided above pinpoints to the CGAL-example that I'm following, namely the "polytope_distance_d_fast_exact.cpp" example. Regarding the used kernel, I use:
// use an inexact kernel...
typedef CGAL::Homogeneous<double>                         K;
typedef K::Point_3                                        Point;
// ... and the EXACT traits class based on the inexcat kernel
typedef CGAL::Polytope_distance_d_traits_3<K, ET, double> Traits;
typedef CGAL::Polytope_distance_d<Traits>                 Polytope_distance;

A: It's a bit of an older library - and it's been a few years since I used it - but I seem to remember trying to do something similar with the GNU Triangulated Surface library...
In particular, using the function gts_surface_distance to find the distance between two GtsSurfaces (which I think your non-convex meshes can still be represented as).
See here for more info.
I'm afraid I have no idea if it might be faster for you - but perhaps worth a shot!


text:
Q: Advice with post method I'm so close to solving the phpMyAdmin connection, but still after onclicked nothing has happend, no error, no freeze. What is wrong here? Or maybe in my PHP code?
final String suma = Float.valueOf(zam.getSuma()).toString();

ib_wyslij.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

         new MyAsyncTask().execute(suma);
    }
});

private class MyAsyncTask extends AsyncTask<String, Integer, Double> {

    @Override
    protected Double doInBackground(String... params) {
        // TODO Auto-generated method stub
        postData(params[0]);
        return null;
    }

    protected void onPostExecute(Double result) {

        Toast.makeText(getApplicationContext(), "command sent",
                Toast.LENGTH_LONG).show();
    }

    public void postData(String valueIWantToSend) {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.kuba.ro/exeConn.php");

        try {
            // Add your data

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("Zam_suma",
                    valueIWantToSend));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        }
        catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }
}

Part of my PHP file:
$Zam_suma = $_POST['Zam_suma'];

mysql_query("INSERT INTO Zamowienie(Zam_suma) VALUES($Zam_suma)");

A: *

*For what do you need the params Integer and Double in your asynctask? If you only need the asynctask to post the string, you can use Void for the other parameters:
private class MyAsyncTask extends AsyncTask<String, Void, Void>

*Add the @Override annotation to the onPostExecute() to override the method (see Arjan's answer).

*Call e.printStackTrace() in your catch blocks to see when, where and why an error occurs.

*Good tutorial

A: For your PHP file:

*

*Be sure to validate the posted item via PHP, that you are receiving the right value using
is_int is_string, etc.

If your value is supposed to be int, use the following code example.
if (is_int($_POST['example_value']) {
    $value = $_POST['example_value'];
}

Also you should not use mysql_query, because it's nearly deprecated. Instead, you should use PDO mysqli.


text:
Q: multiple CSS selectors I want to target an HTML element when BOTH the id and class selectors match.
Ie, if the fieldset has id 'id1' AND class 'collapsed', some CSS rule applies (to ensure its height is reduced to zero).
CSS 2.1 docs suggest that multiple attribute selectors may fill this task:
http://www.w3.org/TR/CSS2/selector.html#matching-attrs
But the following syntax doesn't seem to take effect (tested in Safari and FFox3):
div[id=id1][class=collapsed] { display: none ; }

Is there a way to do something like this?
div#id1.collapsed { /* rules */ }

A: You are doing it right, but the order of the selectors is wrong, you need to put the element first, then the class, and then the id
div.myclass#myid { /*rules*/ }

IMPORTANT EDIT:
div#myid.myclass { /*rules*/ }

Also works.

A: You want div.myclass#myid { /*rules*/ }, but with one caveat: this won't work in IE (as always)
See http://css-discuss.incutio.com/?page=InternetExplorerWinBugs (specifically the Multiple ID class bug which is discussed at http://archivist.incutio.com/viewlist/css-discuss/60941)

A: Thanks Krusty! And thanks also DarkWulf for the warning about IE :)
Btw, I discovered that I had slightly wrong syntax for the approach I was trying.
The correct code for what I was trying (multiple attribute selectors) would have been
div[id="id1"][class~="collapsed"] { /* */ }

The tilde means that div[class~="collapsed] will match with the same rule that div.collapsed would, ie against any of the classes specified.
div[class="collapsed"] { }

matches the class attribute exactly, so it will match

and won't match


text:
Q: Why isn't this module displaying in the django 1.4 admin interface? directory stucture
tutorial/tutorials
turotial/tutorial

tutorial/settings.py
 INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
#'domains'
'tutorials'
)

tutorials/admin.py
from tutorials.models import Tutorial
from django.contrib import admin

admin.site.register(Tutorial)
# Create your views here.

tutorials/models.py
from django.db import models

class Tutorial(models.Model):
    name = models.CharField(max_length=200)
    url = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

class User(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

class Country(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name

A: Few things to help finding the problem:

*

*Do you have admin.autodiscover() in your urls.py

*Have you run syncdb

*Have you tried to open manage.py shell and import the model to see if there are errors.

A: You probably do not have an entry in your INSTALLED_APPS setting for this app.


text:
Q: adding border to a shape generated by two adjacent divs and clip-path here is my code where i want to add 2px border with rounded corners. two containers share single background generated by clip-path and pseudo classes. when i add borders to individual divs its clipped and does not appear.

here is how i want borders

and here is how borders should be rounded

#pool-container {
  padding: 10px;
  width: 200px;
  margin: 0 5px 0 5px;
  display: flex;
  flex-direction: column;
  background: yellow;
  position:relative;
}

#side-step {
  height:80px;
  width:80px;
  transition:1s all;
}
#pool-container:hover #side-step{
  margin-left:150px;
}
#side-step,
#main-pool {
  clip-path:polygon(0 0,100% 0,100% 100%,0 100%);
}
#side-step::before,
#main-pool::before {
  content:"";
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background: linear-gradient( 120deg, rgba(248, 201, 129, 1) 0%, rgba(227, 76, 145, 1) 100%);
}

#main-pool {
  width: 100%;
  height:150px;
}

A: With an extra container holding the background, you may have a translucide container to both div and add a drop shadow from that parent. border (shadow) will be drawn around transparent edges .
here is a possible example :

#parent {
  width: max-content;
  background:linear-gradient(to bottom left, transparent,rgba(255,255,255,0.75),transparent,rgba(255,255,255,0.75),transparent,rgba(255,255,255,0.75)) yellow;
}

#pool-container {
  padding: 10px;
  width: 200px;
  margin: 0 5px 0 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  filter: drop-shadow(0px -2px 0px black) drop-shadow(0px 2px 0px black) drop-shadow(-2px 0px 0px black) drop-shadow(2px 0px 0px black)
}

#side-step {
  height: 80px;
  width: 80px;
  transition: 1s all;
}

#pool-container:hover #side-step {
  margin-left: 150px;
}

#side-step,
#main-pool {
  clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
}

#side-step::before,
#main-pool::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient( 120deg, rgba(248, 201, 129, 1) 0%, rgba(227, 76, 145, 1) 100%);
}

#main-pool {
  width: 100%;
  height: 150px;
}

rounding the shapes could be another question
inspired from https://codepen.io/gc-nomade/details/HKEpo , you could also do from a single element and have text fall lower

* {
  box-sizing: border-box;
  margin: 0;
}

#pool-container {
  padding: 10px;
  width: 220px;
  height: 250px;
  margin: 0 5px 0 5px;
  background: yellow;
  position: relative;
}

.buffer {
  background: inherit;
  height: 100%;
}

#pool-container:before,
#pool-container .buffer:before {
  width: 0;
  float:left;
  content: "";
  height: 80px;
  background: inherit;
  transition: 1s width;
  border-bottom: solid 2px;
}

#pool-container .buffer:before {
  float: right;
  width: 50%;
  border-left: 2px solid;
}

#pool-container:hover .buffer:before {
  width: 0;
}

#pool-container:hover:before {
  width: 50%;
}
#pool-container:before {
  box-shadow: 2px 0;
}

#main-pool {
  background: linear-gradient( 120deg, rgba(248, 201, 129, 1) 0%, rgba(227, 76, 145, 1) 100%);
  box-shadow: inset 0 0 0 2px;
}

#main-pool {
  height: 100%;
}

p {
  font-size: 15px;
  padding: 1em;
}

Pellen tesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vesti bulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.


text:
Q: How to share the \Mongo instance between Doctrine ODM and MongoDbSessionHandler? I'm trying to use MongoDB to store my sessions, and I need to get a reference to the \Mongo instance.
But apparently it's not declared as a service. Instead, doctrine creates it from within the wrapper.
So what can I do about it? I tried this:
services:
    mongo.connection:
        class: MongoDoctrine\MongoDB\Connection
        factory_service: doctrine.odm.mongodb.document_manager
        factory_method: getConnection
    mongo:
        class: Mongo
        factory_service: mongo.connection
        factory_method: getMongo

But sometimes it returns null, and it also conflicts with my logger preprocessor that adds the request_id to the logs, which I think has something to do with the session.
Any ideas?

A: Looking at the source for Doctrine\MongoDB\Connection, the getMongo() method simply returns the $mongo class property, which may or may not be initialized. If possible, you can call initialize() manually before you inject the connection. Given that you're already defining a service for the Connection wrapper, you should be able to do this:
services:
    mongo.connection:
        class: Doctrine\MongoDB\Connection
        factory_service: doctrine.odm.mongodb.document_manager
        factory_method: getConnection
        calls:
            - [initialize, []]
    mongo:
        class: Mongo
        factory_service: mongo.connection
        factory_method: getMongo

That would invoke the initialize() method between the container constructing the mongo.connection service from its factory method and it being returned.
Some additional points to note:

*

*If mongo.connection is only going to be used once (to injected into mongo), you may prefer using anonymous service definitions in lieu of defining another service.

*The ODM bundle already defines each connection as doctrine_mongodb.odm.%s_connection, using its name from the configuration in place of %s; however, that's not helpful if you need to add a method invocation to the service definition.

*The latest version of the ODM bundle (for Symfony 2.1+) changed its service prefix from doctrine.odm.mongodb to doctrine_mongodb.odm, although a BC alias exists for the default document manager. It'd be wise to switch over to the new prefix, though.