text:
Q: Yii model relation one-to-newest Assume we have 3 tables like this:
---------    ---------------    -------------------
| USER  |    | USER_STATUS |    | STATUS_DICT     |
|-------|    |--------------    |------------------
| id    |    | id          |    | id (int)        |
| name  |    | user_id     |    | status (string) |
| email |    | status_id   |    -------------------
---------    | timestamp   |
             ---------------

Each user has many statuses (user_status), related with user.id <-> user_status.user_id. Each user_status has one related record in status_dict which is string label of int status (for example 0 = active).
What I want is make User model to retrieve last user's status using relation. Set relations:
/* User model */
public function relations() {
    return array(
        'status' => array(self::HAS_ONE, 'UserStatus', 'user_id', 'order'=>'status.id DESC'),
    );
}

and
/* UserStatus model */
public function relations() {
    return array(
        'status' => array(self::BELONGS_TO, 'StatusDictionary', 'status_id'),
        'user' => array(self::BELONGS_TO, 'User', 'user_id'),
    );
}

Then when I call User::model()->findByPk(1)->status I get latest status for user #1.
BUT.
When I want to find all users with specified status it does not work as I want. Instead of getting only users with specified status (latest record in user_status) I get all users who at least once had this status.
What I have to do to make relation one-to-newest (I call it like this for this case's purpose)? I saw this article and it does the job, but I'm wondering if there is way to achieve it with Yii's conventions.
I wanted to declare named scope like this:
/* in User model */
public function withStatus($status) {
    if(!is_numeric($status) && !is_null($status)) {
        $status = StatusDictionary::model()->find('lower(name)=lower(:name)', array(':name' => $status))->getAttribute('id');
    }

    $this->getDbCriteria()->mergeWith(array(
        'condition' => (is_null($status) ? 'status.status_id IS NULL' : 'status.status_id=:statusId'),
        'params' => array(':statusId' => $status),
        'with' => array('status')
    ));

    return $this;
}

But it doesn't work either, User::model()->withStatus(0)->findAll() returns all users with related record in user_status with user_status.status_id = 0 even if some of users have newer, different status.
Thanks in advance for any help.

A: I found somewhere else similar solution:
Scope function:
public function withStatus($status) {
    if(!is_numeric($status) && !is_null($status)) {
        $status = StatusDictionary::model()->find('lower(name)=lower(:name)', array(':name' => $status))->getAttribute('id');
    }

    $this->with('status');
    $this->getDbCriteria()->compare('i.statusId', $status);

    return $this;
}

Relations record (this join is protecting relation from filter criteria):
'status' => array(self::HAS_ONE, 'Status', 'clientId',
                'join' => 'INNER JOIN (select max(id) id from status group by clientId) j ON i.id=j.id',
                'alias' => 'i'
            ),

It works for me.

A: Ok, I found solution with TheRifler's help from his post. It turned out that I had a solution right under my nose (article linked in a question).
Relation should be defined as below:
/* User model */
public function relations() {
    return array(
        'status' => array(self::HAS_ONE, 'UserStatus', 'user_id',
            'order' => 's.id DESC',
            'alias' => 's',
            // http://murrayhopkins.wordpress.com/2008/10/28/mysql-left-join-on-last-or-first-record-in-the-right-table/
            'join' => 'LEFT JOIN ( SELECT s1.*
                        FROM `user_status` as s1
                        LEFT JOIN `user_status` AS s2
                        ON s1.user_id = s2.user_id AND s1.id < s2.id
                        WHERE s2.user_id IS NULL ) as `status`
                        ON (s.user_id = `status`.user_id)'
            ),
    );
}

and the named scope:
public function withStatus($status) {
    if(!is_numeric($status) && !is_null($status)) {
        $status = StatusDictionary::model()->find('lower(name)=lower(:name)', array(':name' => $status))->getAttribute('id');
    }

    $this->with('status');
    if(!is_null($status)) {
        $this->getDbCriteria()->compare('status.status_id', $status);
    }
    else {
        $this->getDbCriteria()->addCondition('s.status_id IS NULL');
    }

    return $this;
}

It contains some dirty work, because withStatus() uses status join subquery's data if $status is specified or base s alias if $status is null (it's because we're looking for user without record in status table). Maybe this is not most elegant solution, but works as it should.
Now I can use:

*

*User::model()->findByPk(1)->status to access specified user's status

*User::model()->withStatus('active')->findAll() list users with specified status (status may be passed as integer [user_status.id] or string [status_dict.name])

*User::model()->withStatus(null)->count() get number of users without any status


text:
Q: Solderable number tag for PCB Is there a component with a simple 2-digit number on it (00...99) that can be mounted during standard board assembly process (i.e. pick-and-place machine and reflow)? Something like Molex track-it Traceability Pad but just with a very short human-readable number.

A: Here is a demo video of a label feeder that allows label placement using an SMT mounting machine.

The cost of labels in tape feed that can withstand reflow may be too high for your purposes.
The same process can be used to place polyimide masking dots.

A: This is what I used

That is board number 011. Was done in eagle, I must have the file somewhere, but I probably don't have a functioning eagle any more.

A: Talk to your fabricator. It's possible to add labels during assembly (even pre-printed ones).

A: Does it have to be a component?
Since many assembly houses have laser engraving systems. Which is the to-go high volume, easy method to mark boards.
There are also labels, but labels run out and can be taken off.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Derivative of an univalent function I know that the derivative of a univalent function cannot be zero. But I am wondering if a function has non zero derivative, then is it univalent?
Under what conditions the converse is true?

A: The only holomorphic univalent functions from $\mathbb C$ into $\mathbb C$ are those of the form $z\mapsto az+b$, with $a\neq0$, and they all have non-zero derivative everywhere.

A: Let $f$ analytic in the unit disc and locally univalent ($f'(z) \ne 0$ anywhere); then consider the Schwarzian derivative $S(f)(z)= \frac{d}{dz}({\frac{f''(z)}{f'(z)}})-\frac{1}{2}(\frac{f''(z)}{f'(z)})^2$.
Nehari's theorem says that if $|S(f)(z)| \le 2(1-|z|^2)^{-2}$ for all $|z|<1$, then $f$ is univalent and $2$ is best constant for which the result holds (there are counterexamples for all constants bigger than $2$)
(Conversely, it is known that for all univalent functions in the disc, the inequality above is satisfied with $6$ instead of $2$ and again that is best possible)

A: There are many results (necessary, sufficient, etc) on univalence of holomorphic functions. The most famous is probably Bieberbach Conjecture, proven by de Branges, which is a neccessary condition for univalence:
Theorem.  If a power series $z+ \sum_{n=2}^\infty a_nz^n$ defines a univalent function in the unit disk then
$$
|a_n|\le n, \forall n\ge 2.
$$
Remarkably, there is also a necessary and sufficient condition for univalence of a holomorphic function defined in the unit disk; the condition has the form of an infinite set of inequalities, called   Grunsky inequalities.
There are several books on univalent function (it used to be a very active area of research in complex analysis), for instance,
P. Duren,  Univalent functions, Grundlehren der Mathematischen Wissenschaften, 259, Springer-Verlag, 1983.


text:
Q: Google-Maps-for-Rails - How do I set the size of a map image using gmap4rails? Greetings.
I've had trouble with the Cartographer plugin when deploying to Heroku.
I tried Google-Maps-for-Rails (gmaps4rails gem) and it looks very promising. But I've not been able to figure out how to set the map image size.
With Cartographer, I can set the map image size using markup like the following.

  <%= raw Cartographer::Header.new.to_s %>
  <%= raw @map.to_html %>

[Map]

How do I get similar behavior using gmaps4rails? I'm trying this.

<%= gmaps4rails(@events_map) %>

That draws the map but does not set image size. What's a sensible approach?
Thanks.

A: Let's be even more precise.
In gmaps4rails, a css file is loaded containing the properties of the map container and the map itself. The default are visible here:
https://github.com/apneadiving/Google-Maps-for-Rails/blob/master/public/stylesheets/gmaps4rails.css
So you have two choices:

*

*basic: override this css (which works fine)

*A better alternative is to redefine the css the way you want + cancel the loading of the default css file. You could achieve that by passing falseas second argument of the gmaps or gmaps4rails view helper. See here : https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Miscellaneous

A: You can set it via css:
#gmaps4rails_map {
  width: 658px;
  height: 348px;
}

See the gem author's answer here: Gmaps4rails : Setting map width and height

A: I'm following apneadiving's approach, though my implementation may be a bit awkward, i.e., naive.
In my view I have the following markup.

   <%= stylesheet_link_tag 'gmaps4rails_welcome' %>
   <%= gmaps4rails(@models_map, false, true) %>

I load my own gmaps4rails_welcome.css and avoid loading the default gmas4rails css by passing 'false' as the second argument.
My gmaps4rails_welcome.css file contains the following code.
#map-container {
  padding: 6px;
  border-width: 1px;
  border-style: solid;
  border-color: #ccc #ccc #999 #ccc;
  -webkit-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
  -moz-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
  box-shadow: rgba(64, 64, 64, 0.1) 0 2px 5px;
  width: 800px;
}

#gmaps4rails_map {
  width: 658px;
  height: 347px;

}
For each map rendering I have a specific stylesheet. This works.
Thanks!

A: I had the same issue and solved it differently. I commented out the width from gmaps4rails.css and wrapped the Google map in a div which has the width-setting. Through this, the map is resizeable, e.g. when using a responsive approach, grid system, etc.
I use this with Twitter Bootstrap and it works fine. Note that I fix the height so far.
Hope that helps.
#map-container {
  padding: 6px;
  border-width: 1px;
  border-style: solid;
  border-color: #ccc #ccc #999 #ccc;
  -webkit-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
  -moz-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
  box-shadow: rgba(64, 64, 64, 0.1) 0 2px 5px;
//  width: 800px;
}

#gmaps4rails_map {
//  width: 658px;
    height: 347px;
}


text:
Q: Displaying plots from a loop in Rmarkdown html format with parameters I have a hard time trying to understand what happened here, I have a list params$output_file to return through R shiny app. It didn't work if I use loop, it just worked only outside loop
If I used outside loop, it worked. I have been spent a whole day try to figure out, but I have no luck, if anyone points out what wrong with it. I am appreciated.
The plots showed up, which were outside the loop, but there is nothing inside loop
---
title: Test
output: html_document
params:
  output_file: NA
---

```{r  results='asis', echo=FALSE, cache=TRUE}
library(knitr)

# Outside loop, it is working
params$output_file[[1]]

params$output_file[[2]]

params$output_file[[3]]

for(i in seq_along(params$output_file)){

  print("Inside Loop print nothing")

  params$output_file[[i]]

}


text:
Q: Is there any function in twisted python similar to 'select' in socket programming? I am doing a muticlient chat server program in twisted python. Is there any function in twisted python similar to 'select' in in socket programming? Can anybody give me the answer please?.. If yes, please tell me the implementation, please.

A: No, there isn't.
Twisted calls select (or something like it) for you.
You don't ever need to call a function like select; just let the reactor run, and do its work for you.


text:
Q: Selenium c# как двигать мышкой? пытаюсь зайти в меню, активируемое по hover и кликнуть на элемент.
Например:
https://www.w3schools.com/howto/howto_css_dropdown.asp
Как послать ввод с клавиатуры я нашел, например:
 SearchInput.SendKeys("как вырастить гомункула" + OpenQA.Selenium.Keys.Enter);
А вот обработка перемещения мыши мне не далась.
В интернете написано что вроде должен работать такой код:
IWebElement pictClick = Browser.FindElement(By.Id("pv_nav_btn_right"));

Actions action = new Actions(Browser);
action.MoveToElement(pictClick);
action.Build();
action.Perform();

Почему то у меня он не сработал.
Подскажите пожалуйста как в Selenium можно двигать мышкой так, чтобы вызывалось hover ?

A: Код для джавы, но, в общем, код для шарпа должен быть идентичным (только размеры букв местами не будут совпадать):
WebElement el = driver.findElementById("elementId");

Coordinates c = (RemoteWebElement)el).getCoordinates();

driver.getMouse().mouseMove(c);

Если же ты хочешь двигать мышку физически, то тебе нужно смотреть в сторону WinAPI


text:
Q: Bundle data changes abruptly I have a service and i pass a request object to it.
    final Intent mServiceIntent = new Intent(context, DataManager.class);
final Bundle bundle = new Bundle();
        bundle.putParcelable("request", request);
        mServiceIntent.putExtras(bundle);
        context.startService(mServiceIntent);

The above code is to call my service and have set a bundle in it with an object 'request'. Request object contains an int variable named 'dataVersion'. Now when i get the bundle from the intent :
this.request = bundle.getParcelable("request");

The dataVersion in the request object changes from 3 to 350 and 350 to -1. It happens very rarely but yes it does happen. Mostly i get the bundle as expected. But when i constantly kill and restart the service in a quick succession, it happens that the dataVersion object changes its value randomly.
Below is my parcelable request :
public int updateId;
    public int dataVersion;
    public int priority;
    public boolean setCurrentCompanyOnUpdate;

    public DataUpdateRequest() {
    }

    public DataUpdateRequest(final int dataVersion, final int priority, final boolean setCurrentCompanyOnUpdate) {
        this.updateId = idGen.getAndIncrement();
        this.dataVersion = dataVersion;
        this.priority = priority;
        this.setCurrentCompanyOnUpdate = setCurrentCompanyOnUpdate;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.updateId);
        dest.writeInt(this.dataVersion);
        dest.writeInt(this.priority);
        dest.writeByte(this.setCurrentCompanyOnUpdate ? (byte) 1 : (byte) 0);
    }

    protected DataUpdateRequest(Parcel in) {
        this.updateId = in.readInt();
        this.dataVersion = in.readInt();
        this.priority = in.readInt();
        this.setCurrentCompanyOnUpdate = in.readByte() != 0;
    }

    public static final Creator<DataUpdateRequest> CREATOR = new Creator<DataUpdateRequest>() {
        @Override
        public DataUpdateRequest createFromParcel(Parcel source) {
            return new DataUpdateRequest(source);
        }

        @Override
        public DataUpdateRequest[] newArray(int size) {
            return new DataUpdateRequest[size];
        }
    };


text:
Q: Population Estimation using Power-Law Inter-arrival Times I am wondering if the community could give me some pointers on how to solve the following problem. I feel as if I am missing a key link and so I am having some challenges making some headway. Any Assistance would be greatly appreciated. Here we go!
There are $N$ fishermen on a lake with a fixed, yet unknown, number of fish in the lake. Each fisherman fishes at the same time and for a length of time $T$. When a fisherman catches a fish, the fisherman annotates the time when the fish was caught. There is no catch and release.
At the end of the fishing period, a person collects all times, sorts them and computes the inter-catch (inter-arrival) times. He notes that they are power-law distributed according to
\begin{equation}
\frac{\beta \alpha^\beta}{x^{1+\alpha}} I_{[\alpha,\infty)}(x)
\end{equation}
where $I_{[\alpha,\infty)}(x)$ represents that indicator function, or domain, where the distribution is defined.
With this setup, is it possible to estimate the population of fish within the lake?


text:
Q: Unable to get 2560x1600 resolution when connected with 2 monitors having resolution of 2560x1600 and 1920x1080 I have 2 monitors connected using display port 1st monitor supports 2560x1600 and the second monitor supports 1920x1080 when connected mode my first monitor only shows the max resolution of 2048x1152 but when I change the setting to show only on 1 then I am able to get the 2560x1600 resolution.
enter image description here


text:
Q: Not getting Current DropDownList value on HTTP Post in MVC I am working on MVC Application. I have used a dropdownlist to select value. Now, there is an update form in which there are multiple items that can be updated.
The problem is if I update the field and do not select an item from dropdownlist, its did not get the existing value and instead shows Null.
How is it possible to get the exisiting selected value in dropdownlist in HTTPPost?
View
<div>
    @Html.LabelFor(Student => Student.Gender)
    @Html.DropDownList("Gender","Select Gender")
</div>

Controller
  [HttpPost]
    public ActionResult UpdateStudent(Student student)
    {
        if (ModelState.IsValid)
        {
                var studentToUpdate = (from students in db.Students
                                       where students.StudentId == student.StudentId
                                       select students).Single();

                studentToUpdate.Name = student.Name;
                studentToUpdate.Gender = student.Gender;
                db.SaveChanges();
                return RedirectToAction("Index");
       }
        else
        {
            return View(student);
        }
    }

Thing is when I am updating name and gender then everything works fine. However, If I update only name then at the time of postback the value in dropdown box turns out to be null i.e. I need to select an item from dropdownlist.

A: You have to assign the value also, not only the Text of Drop Down List.
<option value="volvo">Volvo</option>
<option selected="selected" value="saab">Saab</option>

When you assign the value you have to assign relevant value attribute for the drop down list option.
This is just a guess.


text:
Q: PDF Manipulation for Bayesian analysis This post pertains to Bayesian pdf manipulation.

*

*Firstly, assuming a prior probability specified as Gamma distribution such that $\alpha = \mu_{0}^{2}/\sigma_{0}^{2}$ and $\beta = \mu_{0}/\sigma_{0}^{2}$; is it correct to assume, substituting into the Gamma distribution, that the prior has the following form:

$$\pi(\mu) \propto \mu^{(\mu_{0}^{2}/\sigma_{0}^{2})-1}\text{exp}\{-(\mu_0/\sigma_{0}^{2})\mu\}1_{\{\mu>0\}}$$

*

*Secondly, as an aside, assuming the prior adhered not to a Gamma distribution, but, in fact, to a Beta distribution, would it be correct to assume the following:

Given that the pdf for a Beta distribution has the form:
$$\frac{\mu^{\alpha-1}(1-\mu)^{\beta-1}}{B(\alpha, \beta)}$$
The prior distribution would have the following form:
$$\pi(\mu) \propto \mu^{\alpha-1}(1-\mu)^{\beta-1}$$
And, given that the likelihood remains normally distributed, the posterior would have the form:
$$\pi(\mu|\textbf{x}) \propto \mu^{\alpha-1}(1-\mu)^{\beta-1}\text{exp}\{-\frac{1}{2\sigma^{2}}\sum_{i=1}^{n}(x_{i}-\mu)^{2}\}$$
With $\frac{\alpha}{\alpha+\beta}=\mu_{0}$ and $\frac{\alpha\beta}{(\alpha+\beta)^{2}(\alpha+\beta+1)} \space{ } = \sigma_{0}^{2}$
Owing to:
$E[\mu] = \frac{\alpha}{\alpha+\beta}$, $Var[\mu] = \frac{\alpha\beta}{(\alpha+\beta)^{2}(\alpha+\beta+1)}$

*

*Finally, is it correct to suggest that $\pi(\mu|\textbf{x})$ in the above example (Beta/Normal posterior) is a member of the exponential family given that it can be rewritten in the general form:

$$h(\mu)^{n}\text{exp}\{\sum t(x_{i})\psi(\mu)\}$$


text:
Q: Remove an old namespace from a g.cs File? I previously had a subfolder in my WPF application project called "Controls". It contained a WPF user control. I decided to move that user control to my "Views" folder. Since the original folder was empty, I decided to delete it from the project.
Because the user control and folder is removed I receive a compilation error because the user control used the ProjectName.Folder namespace and now nothing references it. MainWindow.g.cs is what references ProjectName.Controls in a using statement.
I know that *.g.cs are generated by VS and can't be edited because it will be overwritten. What do I do to not allow that namespace to be written to the g.cs file? I tried cleaning my solution/project and rebuilding but nothing has worked.

A: In your user control file,
In your ClassName.xaml, you must change the namespace as shown below
<UserControl
    x:Class="YourOldNamespace.ClassName"
    ...
    ...
/>

And in your ClassName.xaml.cs, you must change the namespace as shown below
using System;
using System.Windows;

namespace YourOldNamespace{

   public class ClassName{ ....

}

In both the files, you must replace YourOldNamespace to some new namespace as needed.

A: I had a local reference to the Controls namespace in my Xaml code (MainWindow.xaml). I removed the reference, cleaned the project and produced a successful build.

A: I have had problems with g.cs files in my projects before too. Since they are auto generated, I tend to just delete the file manually and rebuild.

A: Dont forget too, that you must check to see if the Build Action property when you click on the affected XAML file is set to PAGE (instead of resource). This is useful to know when you copy a XAML from another project using copy-paste to save time.

A: Also look at App.xaml and all of your resource dictionaries. For whatever reason, VS 2012's replace in files / "Entire Solution" option didn't find the old namespace reference in App.xaml, had to manually change that. Fixed it for me.

A: Don't forget to change your Generic.xaml file too,
<ResourceDictionary
                   xmlns:local="clr-namespace:MyOldNameSpace">
</ResourceDictionary>


text:
Q: Range of a function using graph If we are given a function
$$y = \frac{x-1}{x+2}$$
and we have to find the range .
So I tried, I wrote
$$y = 1 - \frac3{x+2}$$
$$y-1 = \frac{-3}{x-2}$$
We know this is an equation of rectangular hyperbola , but
how can I find range using its graph?

A: Hint. Try taking the limits at $-\infty,~+\infty$ and also the right and left limits at $x_0=-2.$ You can verify that the range is $\mathbb{R}\setminus \{1\}$.

A: As an appendix to Nikolaos Skout's hint, the function looks like below. You should be able to imagine something like this using the usual methods and tricks in calculus for graphing functions.

A: The function $f(x) = 1/x$ has domain $D_f = (-\infty, 0) \cup (0, \infty)$ and range $R_f = (-\infty, 0) \cup (0, \infty)$.

Based on your work, we can see that the graph of the function
$$g(x) = \frac{x - 1}{x + 2} = 1 - \frac{3}{x + 2}$$
is obtained from the graph of $f(x)$ by reflecting the graph of $f(x)$ in the $x$-axis, stretching it vertically by a factor of $3$, and translating it two units to the left and one unit up.  Consequently, the domain of $g(x)$ is $D_g = (-\infty, -2) \cup (-2, \infty)$ and its range is $R_g = (-\infty, 1) \cup (1, \infty)$.

A: If you can graph it, you can determine its asymptotes. The range will be the set of y values that the curve sweeps over.

A: At $y = 1 - somehyperbola$ you're almost done.
The hyperbola can become anything except $0$. Add or subtract from $1$, you can have anything except $1$.


text:
Q: Is there a way to fix home folder permissions remotely? I have a remote ubuntu computer that I connect to via SSH. The remote computer has only one user. I accidentally changed the user's home folder permissions (to 555, I believe) and because of that I can no longer ssh in. Is there a way to fix the permissions remotely?

A: It's possible you may be able to run commands over ssh even though you cannot start a login shell over ssh.
This may work
ssh remotecomputer chmod 775 .


text:
Q: How to upload a game to Telegram bot - Python I want to upload a bot in which there will be a game. The code is ready and working. But now how to make the user click on the 'Play' button and the bot sends him the game. I wrote to Botfather and didn't understand anything, there are no guides. Help.
enter image description here


text:
Q: Use docker system prune to filter networks I want to use the command docker system prune to remove all unused containers and images, but I want network with a certain driver to be kept alive.
If I run docker system prune --filter "driver!=foo" I get the following result: Invalid filter 'driver!'.
When I use docker network ls I can filtering a specific driver using docker network ls --filter driver=foo.
How can I filter a certain driver in docker system prune?

A: The filter you are trying to apply is not supported. As a workaround, you can use label when creating the network:
$ docker network create --label=mynet your_network_name_here

and then use:
docker system prune --filter "label!=mynet"

The docs mention that docker system prune supports 2 filter cases:

Filtering
The currently supported filters are:

*

*until (<timestamp>) - only remove containers, images, and networks created before given timestamp

*label (label=<key>, label=<key>=<value>, label!=<key>, or label!=<key>=<value>) - only remove containers, images, networks, and volumes with (or without, in case label!=... is used) the specified labels.

Example:
$ docker network create test-1
13ce668830472bb33d2d2b4be5b3236b59df4ea5d20f571e5ba04359ea3617f1

$ docker network create test-2
46a4bb3021250667fd26bf8d76bd06f789c7cf8149ab698b1cec40e1c23d34ad

$ docker network create test-3
a4c2f507e767dfef12684ce451e855a88225c44fcadfdbed7c7cd4502fd0cdd2

$ docker network create --label=mynet test-4
41e9d3c38c1de54e6bb4e25784d73ef7bfbe3e848208a130eb2564c46670a330

$ docker system prune --filter "label!=mynet"
WARNING! This will remove:
        - all stopped containers
        - all networks not used by at least one container
        - all dangling images
        - all dangling build cache
        - Elements to be pruned will be filtered with:
        - label={"label!":{"mynet":true}}
Are you sure you want to continue? [y/N] y
Deleted Networks:
test-1
test-2
test-3

Total reclaimed space: 0B

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
3ca2cec4eda2        bridge              bridge              local
dc9d8ffaed44        host                host                local
d21298cd02e3        none                null                local
41e9d3c38c1d        test-4              bridge              local


text:
Q: Codeigniter Mysql:Too many connections I am getting following error:
Message:  mysqli::real_connect(): (08004/1040): Too many connections
Here is the code of my DB config
$db['default'] = array( 'dsn'   => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'gatha_data',
 // 'database' => 'storegrunt-dev',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE );

Please reply as early as possible

A: You can increase this value in main config file (e.g., /etc/my.cnf) using this syntax:
[mysqld]
set-variable=max_connections=250

and also you can change php.ini file
; Allow or prevent persistent links.
mysql.allow_persistent=Off

Or You can set
'pconnect' => TRUE,


text:
Q: jquery bind dblclick event to multiple elements I am attempting to bind a dblclick event to divs in a nodeList which I am iterating through.
Here is the code:
var elems = document.getElementsByClassName("click");
currentLocation = elems[0].id;
for (var i=0; i<elems.length; i++){
    $(elems[i]).dblclick(function() {
            if((elems[i].id) != currentLocation){
                badAnswer = true;
                alert(badAnswer);
            }
        });

    }

currentLocation is a global variable set to the first element id of the node list.  badAnswer is also a global boolean set to false. If a element is double clicked that matches an element other than the currentLocation global, badAnswer is set to true.
Currently I receive a undefined error, which I tried to remedy by creating a local variable inside of the event handler.  This didn't seem to work either and badAnswer is always true on double click as the elementID is always equal to the ID value of the last element.
Is there a better way to do this?

A: Yes, there is a much better way:
var currentLocation = $(".click")[0].id;
$(".click").on("dblclick", function() {
    if (this.id != currentLocation) {
        badAnswer = true;
    }
});

A: $('.click').dblClick(function() {
    if(this.id != currentLocation) {
        ...
    }
});

You're already using jQuery so you might as well use the selectors...much easier!


text:
Q: find a Pattern Match in string in Python I am trying to find a amino acid pattern (B-C or M-D, where '-' could be any alphabet other than 'P') in a protein sequence let say 'VATLDSCBACSKVNDNVKNKVKVKNVKMLDHHHV'. Protein sequence in in a fasta file.
I have tried a lot but couldn't find any solution.
I tried a lot. the following code is one of them
import Bio
from Bio import SeqIO

seqs= SeqIO.parse(X, 'fasta') ### to read the sequences from fasta file
for aa in seqs:
    x=aa.seq ## gives the sequences as a string (.seq is a build in function of Biopython)

    for val, i in enumerate(x):

        if i=='B':
            if (x[val+2])=='C':

                if x[val+1]!='P':
                   pattern=((x[val]:x[val+2])) ## trying to print full sequence B-C

But unfortunately none of them work.
It would be great if someone can help me out with this problem.

A: >>> x = 'VATLDSCBACSKVNDNVKNKVKVKNVKMLDHHHV'
>>> import re
>>> m = re.search('B(.+?)C', x)
>>> m
<_sre.SRE_Match object at 0x10262aeb0>
>>> m = re.search('B(.+?)C', x).group(0)
>>> m
'BAC'
>>> m = re.search('M(.+?)D', x).group(0)
>>> m
'MLD'
>>> re.search(r"(?<=M).*?(?=D)", x).group(0)
'L'
>>> re.search(r"(?<=B).*?(?=C)", x).group(0)
'A'

A: In python you can use the Regex module (re):
import re      # import the RE module
import Bio
from Bio import SeqIO

seqs = SeqIO.parse(X, 'fasta')
for sequence in seqs:
    line = sequence.se

    RE = r'B[A-OQ-Z]C|M[A-OQ-Z]D'
    # [A-OQ-Z] : Match from A to O and from Q to Z (exl. P)
    # | : is an operator OR = either the left or right part should match
    # The r before the string specify that the string is regex:  r"regex"

    results = re.findall(RE, line)
    # The function findall will return a list of all non-overlapping matches.

    # To iterate over each result :
    for res in results:
        print(res)

Then you can also modify the Regular expression to match any other rule you would like to match.
More information about the findall function here : re.findall(...)
The following website can help you build a regex :
https://regex101.com/

A: A common solution for pattern matching is the usage of regex.
A possible regex for your problem is B[^P]C|M[^P]D.
The following code has been generated by regex101 with the regex I propose and the test string you gave us. It find all matching pattern with their positions in the original string.
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"B[^P]C|M[^P]D"

test_str = "VATLDSCBACSKVNDNVKNKVKVKNVKMLDHHHV"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

A: Use a regular expression with an exception assertion "^".
import re

string = 'VATLDSCBACSKVNDNVKNKVKVKNVKMLDHHHV'
re.findall(r"B[^P]C|M[^P]D", string)

Output:
['BAC', 'MLD']


text:
Q: Which of methods of adding many strings to StringBuilder is faster? I have a StringBuilder and I need to add in It many short strings. There are two ways at least. First is adding each string separately:
StringBuilder sb = new StringBuilder ();
sb.Append (str1);
sb.Append (str2);
.....
sb.Append (strN);

The second is adding all strings together:
sb.Append (string.Concat (str1, str2, ..., strN);

Which of them is faster and preferable fo use?
P.S.: That operation will be executing many times in my program (in cycle) and I don't know, should I to create so many strings via string.Concat so as they will not be used anymore.

A: I would say the first one, because the second one is creating a temporary string for the Concat.
Let's see the worse scenario:

x == sb.Length;
y == Sum(str 1-n Length)
sb has space for y - 1 characters.
In the first case you'll copy around: y - 1 characters to sb from the strings, then x + y - 1 from the old sb buffer to a new sb buffer then the last 1 character. So x + 2y - 2 + 1 characters, so x + 2y - 1 characters.
In the second case the Concat buffer is of the right size, so you copy around y characters from the strings to the Concat buffer plus x from the old to the new sb buffer (because thanks to the single Append the sb knows he has to resize before appending), plus y from the Concat buffer to the new sb buffer. So x + 2y. The first method should wins by 1 character.

But if you really need to make it faster:
int totalLength = str1.Length + str2.Length...

sb.EnsureCapacity(sb.Length + totalLength);

sb.Append(str1);
sb.Append(str2);
sb.Append(str3);

and so on.
In this way you copy around x + y characters.
You first ensure the sb has enough capacity and then begin adding the strings.
But we are speaking of premature optimization, unless your program does this things "by the thousand".

A: As ever, performance shouldn't be based on guesswork - you should test these things. In particular, it may well be affected by:

*

*The framework version you're using

*The number of strings (N)

*The size of strings

*The order of the strings (big ones first or small ones first?)

*Probably many other things I've forgotten about

I'd expect String.Concat to be faster here if you didn't need the StringBuilder otherwise, as it can work out the exact buffer size required, allocate it once, then copy. StringBuilder may need to reallocate multiple times. The downside is that if N is large it will also create an array. EDIT: I originally misread the question, not spotting that the result of String.Concat was being used in another Append operation. Can you write the whole operation in a single String.Concat call rather than mixing StringBuilder and String.Concat.
But yes, basically you should:

*

*Decide how fast you actually need it to be

*Write the most readable code

*Benchmark it

*Change to other code only if it's not fast enough


text:
Q: configure error building GHC on Arch Linux - "error adding symbols: Bad value" I was building GHC to get more libraries than the default installation the Arch repos give, but I managed to do something to the system which makes the initial configure fail on a clean copy of the source:
:~/tmp$ tar -xvf ghc-7.10.2-src.tar.xz
...
:~/tmp$ cd ghc-7.10.2
:~/tmp/ghc-7.10.2$ ./configure --prefix=`pwd`/inst
checking for gfind... no
checking for find... /usr/bin/find
checking for sort... /usr/bin/sort
checking for GHC Git commit id... given 0da488c4438d88c9252e0b860426b8e74b5fc9e8
checking for ghc... /usr/local/bin/ghc
checking version of ghc... 7.10.2
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking target system type... x86_64-unknown-linux-gnu
Build platform inferred as: x86_64-unknown-linux
Host platform inferred as: x86_64-unknown-linux
Target platform inferred as: x86_64-unknown-linux
GHC build  : x86_64-unknown-linux
GHC host   : x86_64-unknown-linux
GHC target : x86_64-unknown-linux
configure: Building in-tree ghc-pwd
/usr/bin/ld: utils/ghc-pwd/dist-boot/Main.o: relocation R_X86_64_32S against `.text' can not be used when making a shared object; recompile with -fPIC
utils/ghc-pwd/dist-boot/Main.o: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
configure: error: Building ghc-pwd failed

What could I have done to the system? I can only remember doing a sudo make install (before deciding I wanted a user-land install as in the command line above) after getting it to build once, but the error is a ld error not a ghc error...

A: I was only looking in /usr/local/lib and /usr/local/bin for ghc stuff to purge, but it seems the make install actually installed things here:
/usr/local/haskell/ghc-7.10.2-x86_64

After removing this directory and reinstalling the repo version of ghc, the configure error goes away. A useful command for me in finding this directory was:
sudo updatedb && (locate ghc | cut -f1-4 -d'/' | sort | uniq)


text:
Q: How to compile OpenCL on Ubuntu? Question: What is needed headers and drivers are needed and where would I get them for compiling open CL on ubuntu using gcc/g++?

Info: for a while now I've been stumbling around trying to figure out how to install open CL on my desktop and if possible my netbook. There are a couple tutorials out there that I've tried but none seem to work. Also, they all just give a step by step with out really explaining why for the what, or even worse they are specific to a particular IDE so you have to learn the IDE to be able to do anything.
So I have an NVIDA GX465 in my desktop and integrated graphics in my netbook. my priority is of course my desktop, the netbook is just a convenience for development purposes(both run ubuntu 11.04 and will be running 11.10 as soon as it comes out). Can some one spell out for me what exactly is needed to get it so I can actually compile code and have it run. and if you could also explain what each piece does so that I can understand it's importance.

A: Ubuntu 20.04 with an NVIDIA Quadro M1200, Lenovo P51
The software integration got a lot better since I had last tried, so I will do an update.
First, at least for graphics, I needed to tweak some BIOS settings as mentioned at, not sure needed for OpenCL: https://askubuntu.com/questions/973605/ubuntu-17-10-boot-stuck-at-message-started-nvidia-persistence-daemon-after-ins/976578#976578
Then, I find and install the latest driver available:
apt-cache search nvidia-driver
sudo apt install nvidia-driver-435 nvidia-opencl-dev

You can also search under:
software-properties-gtk

in the "Additional Drivers" tab.
Now I can compile and run the following test program:
main.c
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>

#define CL_TARGET_OPENCL_VERSION 220
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
#include <CL/cl.h>

int main() {
    cl_command_queue command_queue;
    cl_context context;
    cl_device_id device;
    cl_int input = 1;
    cl_int kernel_result = 0;
    cl_kernel kernel;
    cl_mem buffer;
    cl_platform_id platform;
    cl_program program;
    const char *source = "__kernel void increment(int in, __global int* out) { out[0] = in + 1; }";

    clGetPlatformIDs(1, &platform, NULL);
    clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL);
    context = clCreateContext(NULL, 1, &device, NULL, NULL, NULL);
    command_queue = clCreateCommandQueue(context, device, 0, NULL);
    buffer = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, sizeof(cl_int), NULL, NULL);
    program = clCreateProgramWithSource(context, 1, &source, NULL, NULL);
    clBuildProgram(program, 1, &device, "", NULL, NULL);
    kernel = clCreateKernel(program, "increment", NULL);
    clSetKernelArg(kernel, 0, sizeof(cl_int), &input);
    clSetKernelArg(kernel, 1, sizeof(cl_mem), &buffer);
    clEnqueueTask(command_queue, kernel, 0, NULL, NULL);
    clFlush(command_queue);
    clFinish(command_queue);
    clEnqueueReadBuffer(command_queue, buffer, CL_TRUE, 0, sizeof (cl_int), &kernel_result, 0, NULL, NULL);

    assert(kernel_result == 2);
    return EXIT_SUCCESS;
}

GitHub upstream
with:
gcc -ggdb3  -O0 -Wall -Wextra -pthread -std=c11 \
  -pedantic-errors -o main.out main.c -lm -pthread -lOpenCL
./main.out

Notes:

*

*find your GPU model: https://askubuntu.com/questions/72766/how-do-i-find-out-the-model-of-my-graphics-card

*test that the driver is working: https://askubuntu.com/questions/68028/how-do-i-check-if-ubuntu-is-using-my-nvidia-graphics-card

*similar answer for CUDA: https://askubuntu.com/questions/917356/how-to-verify-cuda-installation-in-16-04/1215237#1215237
Ubuntu 15.10 with an NVIDIA NVS 5400M, Lenovo T430
sudo apt-get install nvidia-352 nvidia-352-dev nvidia-prime nvidia-modprobe
sudo ln -s /usr/include/nvidia-352/GL /usr/local/include
sudo ln -s /usr/lib/x86_64-linux-gnu/libOpenCL.so.1 /usr/local/lib/libOpenCL.so

Then use the header as:
#include <CL/cl.h>

And compile with:
gcc -o main main.c -lOpenCL

Notes:

*

*do not install the nvidia-current package. It is old. Either apt-cache search nvidia and get the latest one, or use software-properties-gtk "Additional Drivers" tab.

I really recommend upgrading to 15.10 to get this to work: I had never managed before.

A: Things that worked for me in Ubuntu 16.04
I have installed openCL on:
SandyBridge CPU: cpu only
IvyBridge GPU
Nvidia GTX 950
install packets
Generic ubuntu packages for OpenCL
Basic installation

sudo apt install ocl-icd-libopencl1
sudo apt install opencl-headers
sudo apt install clinfo

Package that allows to compile OpenCL code (1.2 I think)
Needed to link and compile

sudo apt install ocl-icd-opencl-dev

For Intel GT core
Package that enables runnig openCL on Intel GT, IvyBridge and up

sudo apt install beignet

For SandyBridge Intel CPU and possible others
Download this file
OpenCL™ Runtime 16.1.1 for Intel® Core™ and Intel® Xeon® Processors for Ubuntu* (64-bit)
On https://software.intel.com/en-us/articles/opencl-drivers#latest_linux_SDK_release
Install packages for turning rpm to deb

sudo apt-get install -y rpm alien libnuma1

Untar downloaded file

tar -xvf opencl_runtime_16.1.1_x64_ubuntu_6.4.0.25.tgz
cd opencl_runtime_16.1.1_x64_ubuntu_6.4.0.25/rpm/

Turn rpm files to deb

fakeroot alien --to-deb opencl-1.2-base-6.4.0.25-1.x86_64.rpm
fakeroot alien --to-deb opencl-1.2-intel-cpu-6.4.0.25-1.x86_64.rpm

Install .deb packages

sudo dpkg -i opencl-1.2-base_6.4.0.25-2_amd64.deb
sudo dpkg -i opencl-1.2-intel-cpu_6.4.0.25-2_amd64.deb

Touch local config file

sudo touch /etc/ld.so.conf.d/intelOpenCL.conf

Open the file

sudo vim /etc/ld.so.conf.d/intelOpenCL.conf

and add the line

/opt/intel/opencl-1.2-6.4.0.25/lib64/clinfo

Create a vendors dir and add intel.icd

sudo mkdir -p /etc/OpenCL/vendors
sudo ln /opt/intel/opencl-1.2-6.4.0.25/etc/intel64.icd /etc/OpenCL/vendors/intel64.icd
sudo ldconfig

test if this worked
clinfo should list your devices
Dowload this file

https://codeload.github.com/hpc12/tools/tar.gz/master

Run this code to make sure everything works

tar xzvf tools-master.tar.gz
cd tools-master
make
./print-devices
./cl-demo 1000 10

This should print out GOOD in the end
For Nvidia
install nvidia drivers (I used 370), this should include all the runtime dirvers

A: I've recently used similar process on a clean build on linux, setting up OpenCL with an NVIDIA card.
Steps I took:
1 - install the NVIDIA driver.
2 - install the CUDA tool kit - (follwing the steps in the guide, there are many ways to do it, but I used the .deb installer, guide can be found here: http://docs.nvidia.com/cuda/cuda-getting-started-guide-for-linux/)
3 - using apt-get install the OpenCL headers. Command: sudo apt-get install opencl-headers
Using the : CL/opencl.h header I was able to compile C/C++ code using gcc/g++ and the flag: -lOpenCL
Explaination of steps
1 - Self explanatory
2 - The CUDA toolkit also installs the OpenCL library (libOpencl.so) but not the header (at least not on my system)
3 - hence the header can be installed with apt-get. The header files get stored in the /usr/include/CL directory

A: To compile and run OpenCL code under Linux, you'll need four things:
1) An NVIDIA Driver which supports OpenCL. The drivers packaged with Ubuntu are somewhat
old, but they should still work just fine. Unless you have explicit need for current
drivers, you should stick with the ones packaged with Ubuntu. To be clear, these are
the same drivers installed through the restricted drivers manager. OpenCL libaries are shipped with driver, so to just run OpenCL programs driver should be enough.
2) The CUDA toolkit. This includes the headers necessary to compile OpenCL code. Install this to the default location.
3) The GPU Computing SDK (optional). This includes various NVIDIA specific support tools, as well as OpenCL code samples.
All three of these items may be found at http://developer.nvidia.com/cuda-toolkit-40.
4) OpenCL C++ bindings (optional). Strangely, they are not included with CUDA Toolkit, but in case you use C++, they could make your code much more redable. You can download them from http://www.khronos.org/registry/cl/api/1.1/cl.hpp, and just put it in /usr/local/cuda/include/CL an you desktop.
Once these are installed, you'll need to perform a few more steps to be able to compile and run OpenCL outside of the NVIDIA SDK.
1) The CUDA toolkit will have included the OpenCL headers (Listed at http://www.khronos.org/registry/cl/), likely they are in the directory /usr/local/cuda/include/CL. To make these headers available system wide, you should link this directory into /usr/include/, such that they may be accessed as /usr/include/CL/[headerfilename]. Instead of creating a symlink, you could add /usr/local/cuda/include to your C_INCLUDE_PATH and CPLUS_INCLUDE_PATH environment variables, but this would last for only currest session.
2) Make sure that the OpenCL library (libOpenCL.so) is present in /usr/lib. This should have been put in place by the driver, so you shouldn't have to do anything.
You're ready to write code. Make sure to include CL/cl.h (or CL/cl.hpp if you'd like to use C++ version of API) in any C(++) program which makes OpenCL API calls. When you compile, make sure to link against the OpenCL library (pass gcc the -lOpenCL flag).
As far as your netbook, integrated graphics don't generally support OpenCL. In theory, AMD's APP Acceleration supports running OpenCL on the CPU, but it's not clear that it actually works.


text:
Q: There's a way to save a XML without displaying the Dialog Box? I just created a xml editor in Flex that works perfectly, but i'm having trouble with save option. In fact he's saving quite well, the problem is that it is displaying a dialog box for saving the document, and i want to save and replace the file automatically when i click the save button without displaying the dialog box.
Can anyone help me with this?
NOTE: I am using the FileReference class to use the method Save(), i read somewhere on the internet that FileStream class can be used for this, but i don't know how...
Well, anyway...
Thank you.

A: FileStream class is only available when developing an AIR application. The code would be something along this:
_file = new File("path_to_file_in_filesystem");
_loader = new URLLoader();
_loader.dataFormat = URLLoaderDataFormat.BINARY;
_loader.addEventListener(Event.COMPLETE, _loadingComplete);

var req:URLRequest = new URLRequest("path_to_file_on_web");
_loader.load(req);

private function _loadingComplete(evt:Event):void
{
    var fs:FileStream = new FileStream();
    fs.open(_file, FileMode.WRITE);
    fs.writeBytes(_loader.data);
    fs.close();
    fs = null;
    _loader.unload();
    _loader = null;
}

There is no way to save a file into the filesystem without users permission in web player.


text:
Q: Wake PIC16F1825 from sleep with RS232 Is it possible to wake a Microchip PIC16F1825 from sleep using RS232 without looking characters?
Because one of the permissible RX pins supports interrupt on change, I thought this might be possible.
Has anybody implemented this successfully?

A: Sure!
From datasheet PIC16(L)F1825/1829:
9.1 Wake-up from Sleep
The device can wake-up from Sleep through one of the following events:
1. External Reset input on MCLR pin, if enabled
2. BOR Reset, if enabled
3. POR Reset
4. Watchdog Timer, if enabled
5. Any external interrupt
6. Interrupts by peripherals capable of running
   during Sleep (see individual peripheral for more information)

So you can use:
1)External interrupt INTERRUPT-ON-CHANGE, if you are connecting RX pin with one  of other pins which is configured as interrupt-on-change.
2)Peripheral interrupt RCIF: USART Receive Interrupt Flag bit. When receiver buffer is full (one UART word is received), an interrupt is pending and your CPU should wake up.


text:
Q: HTTP 400 on PUT Request for Firefox/IE. Works correctly for Chrome/Opera There's a website using jquery to call a WCF Webservice on another domain (Utlising CORS). Most of the methods are GET ones but there are a couple of PUT ones.
All GET methods work correctly on all browsers.
PUT methods however will only work for Chrome and Opera. For Firefox and Internet Explorer they will result in a HTTP 400 BAD REQUEST error. I have read everything and tried everything to change the CORS settings of the web services with no success.
How differently can browsers be making these PUT calls if they work flawlessly for some and not for others?
For reference, the webservice Global.asax file looks like that:
 protected void Application_BeginRequest(object sender, EventArgs e)
    {

        //CORS ENABLED
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Authorization, Origin, Content-Type, Accept, X-Requested-With");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");

            HttpContext.Current.Response.End();

        }
    }

and the web.config relevant session is like that:
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
   <httpProtocol>

   </httpProtocol>
  </system.webServer>

Any ideas?
Edit: This is there jQuery Request:
       addAbs = function addAbs() {
        return $.ajax({
            type: 'PUT',
            url: Constructor.prototype.getServletURL(),
            contentType: "application/json; charset=utf-8",
            headers: {"Origin": "http://app-eservices.talentia-software.com"},
            data: JSON.stringify(newAbsence),
            timeout: GlobalContext.xhrTimeout,
            beforeSend: self.showLoadingDialog('')
        });

A: Turns out the reason was the AJAX Request specified a contentType of "charset=utf-8" , instead of "charset=UTF-8", so capitalisation made the difference. For reference, the capitalised version is the correct one, but both are supposed to work.
This was not an issue for Chrome which auto-capitalised it, but for Firefox and other browsers that did not change the capitalisation, the request would end up with a HTTP 400 Bad Request error. Apparently WCF services can only accept the capitalised version which is weird. Other than changing the AJAX request, does anyone know if there's another way to make the WCF services accept the lowercase version?


text:
Q: Powershell cutting off output I am using the below to see a folder structure but when i look at the transcript a chunk of the resuts have been cut off from the top - as if it is starting halfway through
Start-Transcript -Path "C:\transcripts\transcript.txt"
tree /f
Stop-Transcript

A: I get the same behavior with tree /f from a large directory tree. I don't know what is happening at this point, but I can offer a workaround:
tree /f 2>&1 | Tee-Object -FilePath treeOutput.txt

You could also do the following, if you don't need to output to the console at the same time:
tree /f 2>&1 > treeOutput.txt

As for the issue with tree /f, tree is actually tree.com, not tree.exe, which means it actually runs in an MS-DOS subsystem. I suspect that Start-Transcript isn't fully compatible with .COM programs and I suggest using output redirection as recommended above as a suitable workaround.


text:
Q: In grails 4.0.5, moving datasource definition to runtime.groovy causes DB not to be created during tests I need to move the configuration of the datasource to runtime.groovy, because that configuration code need to access some of my classes.
In previous versions of grails, this was not an issue. However i find that if I move the environments block, and the default datasource block to runtime.groovy, Hibernate will not create the database, and my functional tests fail, obviously.
This is the configuration that I removed from application.yml:
hibernate:
    cache:
        queries: false
        use_second_level_cache: false
        use_query_cache: false

dataSource:
    pooled: true
    jmxExport: true
    driverClassName: org.h2.Driver
    username: sa
    password: ''

environments:
    development:
        grails.plugin.console.csrfProtection.enabled: false
        dataSource:
            dbCreate: create-drop
            url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    test:
        dataSource:
            dbCreate: update
            url: jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        hibernate:
            jdbc:
                use_get_generated_keys: true

Which in my runtime.groovy looks like this:
hibernate {
    cache {
        queries = false
        use_second_level_cache = false
        use_query_cache = false
    }
}

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "org.h2.Driver"
    username = "sa"
    password = ""
}

environments {
    development {
        dataSource {
            dbCreate = "create-drop"
            url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
        }
    }
    test {
        dataSource {
            dbCreate: "update"
            url: "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
        }
    }

    production {
        hibernate {
            jdbc {
                use_get_generated_keys = true
            }
        }

        dataSource {
//production datasource setup irrelevant
        }
    }

I tried combinations, keeping some of it in application.yml, some of it in application.groovy, all of it in runtime.groovy. Keeping the test and dev sections in application.yml, and the runtime-specific environments in runtime.groovy, does not work either.
Nothing seems to work.
I can't leave it like this because my production mode needs to be able to connect a secrets store to set up the production datasource.
Is there some hidden switch I am missing with the newer versions of grails?
Additional notes, the following commands do work (server starts up):
./grailsw -Dgrails.env=dev run-app
./grailsw -Dgrails.env=test run-app
./gradlew shell -q

The tests fail complaining about missing tables when i run this:
./grailsw -Dgrails.env=test test-app

The tests that are failing are inheriting from GebSpec, as they are full functional tests that need to run against the controllers.
So it seems like Hibernate is not properly initializing when running functional tests, if I move the configuration away from application.yml?
Thanks
FINAL UPDATE
There is a typo in my code, as Jeff pointed it out. Thanks Jeff!

A: The config you show for your runtime.groovy should be in grails-app/conf/application.groovy (does not need to be runtime.groovy).  The problem with your config is you have this:
test {
    dataSource {
        dbCreate: "update"
        url: "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }
}

You have colons where you should have equals signs, like this:
test {
    dataSource {
        dbCreate = "update"
        url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }
}


text:
Q: django template print only first unique occurance I have a pretty simple task to do but I do not know how to do it most effectively in django templates.
Basically, this is what I am trying to accomplish:
Jan. 27, 2015
    first post
    second post
    third post
Jan. 28, 2015
    another post
    and other
    etc
Feb. 18, 2015
    again
    and again

This could be its model:
class Post(models.Model):
    date=models.DateField()
    name=models.CharField()

In views.py passing just queryset as posts:
Post.objects.filter(date__gte = date.today()).order_by("date")

And then in template priting it out with for cycle:
{% for post in posts%}
    {{post.name}}
{% endfor %}

How do I get printed unique date only once? Is it possible to do this in templates or do I have to take care of it in views? I found similar two year old post.

A: There is an inbuilt template tag for that - regroup!
This isn't perfect, but with the documentation it should get you close.
{% regroup posts by date as date_list %}

{% for date in date_list %}

{{ date.grouper }}

        {% for item in date.list %}

{{ date.name }}

        {% endfor %}

{% endfor %}

A: You can use {% ifchanged %} template tag:
{% for post in posts %}
    {% ifchanged %}
{{ post.date }}
{% endifchanged %}

{{ post.name }}

{% endfor %}


text:
Q: What data type for a column which can have three states: yes, no, unknown I have an application where the user can decide between:

*

*yes

*no

*unknown

I started to use a boolean column which is nullable.
But things get quite complicated since my framework (django) does not provide a input field for coding a search form out of the box.
In the search form I need four states:

*

*yes

*no

*unknown

*show all (ignore this column in the search)

Related question: https://stackoverflow.com/questions/38307866/search-form-for-nullbooleanfield
An old rule of thumb comes to my mind again:

Avoid nullable db columns.

I want to change the data type from a nullable boolean field to something different.
What data type for a column which can have three states: yes, not, unknown?
I use Postgres 9, but AFAIK this should not matter for this question.

A: You want boolean.
It can have true (=yes), false (=no) and null (=unknown)
More details in the manual:
https://www.postgresql.org/docs/current/static/datatype-boolean.html

"Avoid nullable columns" is only a recommendation. If you need an "unknown" state, then NULL is exactly what you are looking for. It was specifically created to represent "unknown".
Postgres even support the keyword unknown for boolean expressions: where some_column is unknown is equivalent to where some_column is null if some_column is defined as boolean

A: Does the BIT datatype exist in Postgres land?
BIT is the datatype I use in SQL Server when I want to have Y/N/NULL values only.

A: In Django, you can use models.CharField with combination with a field option choices as it is described at https://docs.djangoproject.com/en/1.9/ref/models/fields/#choices.
This solutions is more flexible in case when your logic changes.


text:
Q: UVM- Using my own configuration files vs using config db I wrote a sequence which can be generic to a variety of tests. I want to do it by adding configuration files for each test.
The code for the sequnce:
//----------------------------------------------------------------------
//Sequence
//----------------------------------------------------------------------
class axi_sequence extends uvm_sequence#(axi_transaction);
   `uvm_object_utils(axi_sequence)

   //new
   function new (string name = "axi_sequence");
      super.new(name);
   endfunction: new

   //main task
   task body();
      int file_p, temp, len;
      byte mode;
      bit [31:0] addr;
      string str;
      axi_transaction axi_trx;
      bit [31:0] transfers [$];
      bit [31:0] data;

      //open file
      file_p = $fopen("./sv/write_only.txt", "r"); //the name of the file should be same as the name of the test
      //in case file doesn't exist
      `my_fatal(file_p != 0, "FILE OPENED FAILED")
      //read file
      while ($feof(file_p) == 0)
    begin
       temp = $fgets(str, file_p);
       axi_trx =  axi_transaction::type_id::create(.name("axi_trx"), .contxt(get_full_name()));
       // ~start_item~ and <finish_item> together will initiate operation of
       // a sequence item.
       start_item(axi_trx);
       transfers = {};
       $sscanf(str, "%c %d %h", mode, len, addr);
       //assign the data to str
       str = str.substr(12,str.len()-1);
       //create and assign to transfers queue
       if(mode == "w")
         begin
            for (int i = 0; i <= len; i++) begin
           temp = $sscanf(str, "%h", data);
           `my_fatal(temp > 0, "THE LENGHT PARAM IS WRONG- too big")
           transfers. push_back(data);
           str = str.substr(13+(i+1)*8,str.len()-1);
        end//end for
            `my_fatal($sscanf(str, "%h", temp) <= 0, "THE LENGHT PARAM IS WRONG- too small")
       end//if
       axi_trx.init(mode,len,addr,transfers);
       if (to_random == 1) to_random should be a part of the configuration file.
           trx.my_random(); //trx is transaction instance
           else
           trx.delay = const_config; //const_delay should be a part of the configuration file.
       //contains the send_request which send the request item to the sequencer, which will forward
           // it to the driver.
       finish_item(axi_trx);
    end//begin
   endtask: body

endclass: axi_sequence

Should I do it by using different configuration file, or can I do it by values that will be passed from the test to the agent through the config db?
And how can I pass different path (for the file_p = $fopen()) for each test?

A: You shouldn't need a separate configuration file for each test. Ideally, you would just pass down the configuration from the test level down into the env through the config_db (or through a separate configuration object for your agent)
When you create your sequence in your test (or virtual sequencer), you should be able to set your variables as needed.


text:
Q: Eclipse is saying that static field of a class cannot be resolved Despite the HttpComponents documentation saying that the class DefaultConnectionReuseStrategy has a static field called INSTANCE, Eclipse is telling me that's unresolved.
I've tried everything I know of (checked the version, rebuilt the code etc) but nothing makes it go away.
Does anyone know what could be causing this problem?

Code is:
socket = serverSocket.accept();
                DefaultBHttpServerConnectionFactory connFactory = DefaultBHttpServerConnectionFactory.INSTANCE;
                HttpServerConnection conn = connFactory.createConnection(socket);
                ConnectionReuseStrategy connReuseStrat = DefaultConnectionReuseStrategy.INSTANCE;
                HttpService httpService = new HttpService(httpproc, connReuseStrat, new DefaultHttpResponseFactory(), null, null);
                HttpContext context = new BasicHttpContext(null);
                httpService.handleRequest(conn, context);

A: The version of Apache HTTPComponents included in Eclipse is 4.2.x which does not have the INSTANCE field - this appears to be new in 4.3


text:
Q: Trouble calling a superclass method from inside a subclass static method I have a class Mouse that extends the class Mammal. In Mouse, I have a static method which takes in as parameter an ArrayList of Mouse objects, like this:
public static void mate(ArrayList<Mouse> mice)

Inside this static method, I have this line of code:
if((mice.get(i).getIsMale ^ mice.get(j).getIsMale) && (mice.get(i).getAge > 1 ) &&  (mice.get(j).getAge > 1 ) )
    //if either mouse is male but not both and if both are older than 1 day

where getIsMale and getAge are methods defined in the superclass Mammal, and i and j are variables I use inside the static mate method.
I get 4 errors from the compiler in the above line: Cannot find symbol. One for each getIsMale and one for each getAge
I would appreciate any (quick) help. I have to submit this assignment and go to sleep. Thanks!

A: Quick answer (:-P): You have to add brackets so that it's getIsMale() and getAge(). All functions must be called with brackets, in Java.
Style comment: Boolean getters should normally be named isXXX, not getXXX, so your male getter should be named isMale, not getIsMale.

A: Here's your code:
if ((mice.get(i).getIsMale ^ mice.get(j).getIsMale) &&
    (mice.get(i).getAge > 1 ) &&
    (mice.get(j).getAge > 1 )) {
    // ...
}

The way that this is written, you are saying "give me the value of the field getIsMale" and so on.  It getAge and getIsMale are not fields: they are methods.  So you have to call them:
if ((mice.get(i).getIsMale() ^ mice.get(j).getIsMale()) &&
    (mice.get(i).getAge() > 1 ) &&
    (mice.get(j).getAge() > 1 )) {
    // ...
}

(The reason that the Java compiler says "symbol not found" rather than "its a field" is that field names and method names are in different name spaces.  If you wanted to, you could write a class that has both a field called foo and a method called foo.  So ... the compiler is telling you about the error that it sees, rather than trying to guess what you might have actually meant.)

Minor point: The JavaBeans convention says that a getter for a boolean property should be called isXxx rather than getXxx.  You should rename getIsMale() to be isMale().


text:
Q: Scala, docker - how to set mainClass in multimodule application using sbt-native-packager? I have created a multimodule, sbt project in Scala. For now it is:

*

*main project (main-service) with build.sbt file

*http module with Main class
In my sbt file I have:
lazy val root = (project in file("."))
  .aggregate(http)
  .settings(
    dockerBaseImage := "openjdk:jre-alpine",
    name := "main-service",
    libraryDependencies ++= Seq(

    )
  )
  .enablePlugins(JavaAppPackaging)
  .enablePlugins(DockerPlugin)
  .enablePlugins(AshScriptPlugin)

lazy val http = (project in file("http"))
  .settings(
    mainClass in Compile := Some("Main"),
    name := "main-http",
    libraryDependencies ++= Seq(
    ))

As you can see, I want to run it with docker. Image of this project is created well, but when I made docker run then I got an error:
docker: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"/opt/docker/bin/main-service\": stat /opt/docker/bin/main-service: no such file or directory": unknown.

I think the problem could be with mainClass line. I have my Main class in main-http/src/main/scala directory, but it looks like docker does not see it.
How should I move this Main class or change path to it and run it correctly?

A: If you want to keep the main class in http subproject, you need to move the plugins to this project too as following.
lazy val root = (project in file("."))
  .aggregate(http)
  .settings(name := "main-service")

lazy val http = (project in file("http"))
  .settings(
    mainClass in Compile := Some("Main"),
    dockerBaseImage := "openjdk:jre-alpine",
    name := "main-http",
    libraryDependencies ++= Seq()
  )
  .enablePlugins(JavaAppPackaging)
  .enablePlugins(DockerPlugin)
  .enablePlugins(AshScriptPlugin)

The plugins must be enabled at the project where the Main class is located.
To build a docker image, do
sbt http/docker:publishLocal


text:
Q: Jump to Definition goes to derived data folder for static library's header files instead of the static library project I have an iOS app that has a static library as a dependency. The static library is setup per Apple's recommendations https://developer.apple.com/library/ios/technotes/iOSStaticLibraries/iOSStaticLibraries.pdf
Sometimes when I use "Jump to Definition" on a symbol from the static library I end up in the header file that has been copied to the derived data folder of the app instead of the header file inside the static library project. Other times things work perfectly.
When "Jump to Definition" fails more often than not I delete the derived data folder for the project through the Organizer window and this seems to fix the problem temporarily.
Does anyone know if there is a way to tell Xcode to exclude the derived data folder from "Jump to Definition"?

A: select 'Build Phases' -> 'Target Dependencies';
add your static library .


text:
Q: Adding borders to an entire row in a table I have a table with multiple rows (a regression table).  I would like to add a coloured border highlighting one particular variable.  I have found a way to border one cell at a time but is there a way to add a border around an entire row?
EDIT: Here is some detail on my table:
\begin{tabular}{rcccccccc|cccccccc}

       &                                                       \multicolumn{ 8}{c}{section 1} &                                                           \multicolumn{ 8}{c}{section 2} \\

       &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\

       &        (1) &        (2) &        (3) &        (4) &        (5) &        (6) &        (7) &        (8) &        (9) &       (10) &       (11) &       (12) &       (13) &       (14) &       (15) &       (16) \\

       &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\

regression coef 1 &         no &         no &         no &         no &         no &             no &         no &         no &         no &         no &         no &         no &         no &         no &         no &         no \\

       &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\

regression coef 2 & {\bf 1234} & {\bf 1234} & {\bf 1234} & {\bf 1234} & {\bf 1234} & {\bf 1234} & {\bf 1234} & {\bf 1234} &            &            &            &            &            &            &            &            \\

       & {\bf [2]} & {\bf [2]} & {\bf [2]} & {\bf [2]} & {\bf [2]} & {\bf [2]} & {\bf [2]} & {\bf [2]} &            &            &            &            &            &            &            &            \\

\end{tabular}

A: You can get fancier borders using tikz but the classic way is to us \hline

\documentclass{article}
\usepackage{pdflscape}

\begin{document}

\begin{landscape}
\begin{tabular}{rcccccccc|cccccccc}
& \multicolumn{ 8}{c}{section 1} & \multicolumn{ 8}{c}{section 2} \\
&            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\
&        (1) &        (2) &        (3) &        (4) &        (5) &        (6) &        (7) &        (8) &        (9) &       (10) &       (11) &       (12) &       (13) &       (14) &       (15) &       (16) \\
&            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\
regression coef 1 &         no &         no &         no &         no &         no &             no &         no &         no &         no &         no &         no &         no &         no &         no &         no &         no \\
&            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\
\hline
\multicolumn{1}{|r}{regression coef 2 }& \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 &            &            &            &            &            &            &            &\multicolumn{1}{c|}{}  \\
\hline
& \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] &            &            &            &            &            &            &            &
\end{tabular}

\end{landscape}

\end{document}

A: You can use \tikzmark to place some marks at the desired locations and then draw the frame using the marks; a little example:
\documentclass{article}
\usepackage{tikz}
\usepackage{pdflscape}

\newcommand\tikzmark[1]{%
  \tikz[remember picture,overlay] \node (#1) {};}

\begin{document}

\begin{landscape}
\begin{tabular}{rcccccccc|cccccccc}
& \multicolumn{ 8}{c}{section 1} & \multicolumn{ 8}{c}{section 2} \\
&            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\
&        (1) &        (2) &        (3) &        (4) &        (5) &        (6) &        (7) &        (8) &        (9) &       (10) &       (11) &       (12) &       (13) &       (14) &       (15) &       (16) \\
&            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\
regression coef 1 &         no &         no &         no &         no &         no &             no &         no &         no &         no &         no &         no &         no &         no &         no &         no &         no \\
&            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\
\tikzmark{a}regression coef 2 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 & \bfseries 1234 &            &            &            &            &            &            &            &  \\
& \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] & \bfseries [2] &            &            &            &            &            &            &            & \phantom{noo}\tikzmark{b} \\
\end{tabular}

\begin{tikzpicture}[remember picture,overlay]
\draw[line width=1pt,draw=orange!70!black,rounded corners=4pt]
 ([xshift=-3pt,yshift=7pt]a.north) rectangle ([xshift=3pt,yshift=-5pt]b.south);
\end{tikzpicture}
\end{landscape}

\end{document}

The code needs two runs to stabilize.
As a side note, \bf is a deprecated command; you should use \bfseries instead. Also, the table cells define groups so you don't need to explicitly group using braces.

A: With {NiceTabular} of nicematrix.
\documentclass{article}
\usepackage{nicematrix,tikz}
\usepackage{pdflscape}

\begin{document}

\begin{landscape}
\begin{NiceTabular}{rcccccccc|cccccccc}
& \multicolumn{8}{c}{section 1} & \multicolumn{8}{c}{section 2} \\
&            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\
&        (1) &        (2) &        (3) &        (4) &        (5) &        (6) &        (7) &        (8) &        (9) &       (10) &       (11) &       (12) &       (13) &       (14) &       (15) &       (16) \\
&            &            &            &            &            &            &            &            &            &            &            &            &            &            &            &            \\
regression coef 1 &         no &         no &         no &         no &         no &             no &         no &         no &         no &         no &         no &         no &         no &         no &         no &         no \\
&            &            &            &            &            &            &            &            &
                                                                                &            & &            &            &            &            &            \\
regression coef 2 & \RowStyle{\bfseries}1234 & 1234 & 1234 & 1234 & 1234 & 1234 & 1234 & 1234 \\
& \RowStyle{\bfseries} [2] & [2] & [2] & [2] & [2] & [2] & [2] & [2] &            &            &            &
&            &            &            & \phantom{noo} \\
\CodeAfter
  \tikz \draw [red!50!black,rounded corners] (7-|1) rectangle (last-|last) ;
\end{NiceTabular}

\end{landscape}

\end{document}

You need several compilations (because nicematrix uses PGF/Tikz nodes).


text:
Q: Adjust position of some tool tips based on class of trigger using jqueryTOOLS I am using the jqueryTOOLS plugin for jquery to generate tooltips for a set of form fields on my site.
The event trigger is dictated by a small piece of javascript:
$(function() {
$("#myform :input[title],label[title]").tooltip({
position: "top center",
offset: [-10, 0],
effect: "fade",
opacity: 1.0
      });
    });

As you can see, this triggers the title attribute of s and s as a tooltip onFocus.
You can also see that the configuartion of the tooltip takes place as part of this javascript, position is set, as well as an offset etc.
My problem:
There is no one position the tooltip can occupy relative to the fields in the form which is suitable. Some elements I need it to appear on the left, some to the right, and some above. I am looking for a way, based on the class of the element, to dictate an alternative position for the element.
I have tried:
Setting the class of a element for which I need the tip to appear to the left like so:
<input
        title="This text becomes the tooltip"
        class="errorleft"
        type="radio"
        name="somename"
        value="value"
        id="elementID"
                />

and then adjusting my javascript to include an additional trigger:
$(function() {
$("#myform :input[title],label[title]").tooltip({
position: "top center",
offset: [-10, 0],
effect: "fade",
opacity: 1.0
      });
    });

    $(function() {
$("#myform.errorleft :input[title],label[title]").tooltip({
position: "center left",
offset: [0, 0],
effect: "fade",
opacity: 1.0
      });
    });

This does not work (and I can see why) and I know there is a way to do this, but I can't see a way to it, so far non of the documentation I can find on the jqt website has discussed this.
Any ideas much appreciated
jsFiddle
Here is a jsfiddle of my situation using a demo form, and the code I have attempted - in this example the Email field has the class "errorleft" where as all the others are classless. All tooltips display on the right
http://jsfiddle.net/DjHr7/1/

A: You are missing a space in your selector. As currently written,
$("#myform.errorleft :input[title],label[title]")

means, find the element that has an id #myform AND a class .errorleft. It should work with the following syntax:
$("#myform .errorleft")

This means, find an element with class .errorleft inside an element with an id of #myform
(You don't have to worry about adding :input[title],label[title] if you give each input field a class


text:
Q: Use my own rabbitTemplate with auto config connection factory Spring boot weird behaviour Hi I was trying to define my own rabbitTemplate with autoconfig connctionFactory of spring boot .
first i tried this :
@Configuration
@EnableRabbit
public class MyConfiguration {

@Autowired
private ConnectionFactory connectionFactory;

@Bean
public RabbitTemplate rabbitTemplate(){
  RabbitTemplate template = new RabbitTemplate(connectionFactory);
  return template;
}

This was not working ...
So I have tried this :
@Configuration
@EnableRabbit
public class MyConfiguration {
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
    RabbitTemplate template = new RabbitTemplate(connectionFactory);
}

And its works perfectly can someone explain this ?

A: The problem is that you're injecting a bean reference in your configuration class. That bean reference is something that is provided by auto-config. We can't process that configuration class until those field references are wired. But, we're supposed to "parse" user configuration first (i.e. before auto-configuration kicks in).
This has nothing to do with Spring Boot by the way. You should avoid injecting dependencies like that, especially if these are only required by one @Bean declaration.
In other words, try as much as possible to avoid cycles in your configuration.


text:
Q: PHP when executing bat file display command prompt window on server? I've setup a webpage that will allow me to remotely execute the bat file that I use to start my minecraft server in case I want to play while away. I have successfully managed to run the bat file and start the server remotely from my site, however there is no visual display of the command prompt on the server (My desktop) as there generally is when a bat file is normally run. Because of this, I am unaware of a good way to stop my server.
Is there any way to have the command prompt display itself on the server when the bat file is run remotely using PHP? Is anyone aware of any simple way that I can run commands on the server through the website, just as I would if I were using command prompt?
My website is run using wamp (apache) on the same desktop as the server, I change the directory to the location of the bat file and am able to execute it.
Here's my website code:
<?php
if (isset($_POST['button']))
    {
echo getcwd() . "\n";
chdir('C:\wamp\www\MinecraftServer');
exec('server.bat', $output);
echo implode("\n", $output);
}
?>
<!doctype http>

        <title> Index </title>

 Welcome!

 Are you here looking for the minecraft map? Click  here .

    <form method="post">

        <button name="button">Start Server</button>

    </form>

Bat file:
"C:\Program Files\Java\jdk1.7.0_10\bin\java.exe" -Xmx4096M -Xms2048M -jar minecraft_server.1.8.exe nogui
pause

A: *

*Can you please share your .bat? Maybe it's simply not producing any output?

*Can you var_dump the $output? When array is empty, no matter what the glue is, implode will output empty string as far as I remember.

*If you want to make newlines in the browser you shall use
 tag, so your echo shall look like this:
echo nl2br(implode("\n", $output));
or
echo implode("
", $output);

*And you have wrong tag in your HTML markup, change http to html

*Have you tried backicks only?

*You may want to consider output the result of executing .bat to some text file and then read the contents of that file.

*Use @ECHO OFF in your .bat to prevent cluttering the output

A: The popen function can help you, it opens a pipe to a process executed by forking the command given by command.
From Documentation:

popen
(PHP 4, PHP 5) popen — Opens process file pointer
Description
resource popen ( string $command , string $mode )
Opens a pipe to a process executed by forking the command given by command.
Parameters
command The command
mode The mode
Return Values
Returns a file pointer identical to that returned by fopen(), except
that it is unidirectional (may only be used for reading or writing)
and must be closed with pclose(). This pointer may be used with
fgets(), fgetss(), and fwrite(). When the mode is 'r', the returned
file pointer equals to the STDOUT of the command, when the mode is
'w', the returned file pointer equals to the STDIN of the command.
If an error occurs, returns FALSE.


text:
Q: Regex to match day in month I'm trying to edit some existing regexes which tries to extract dates from a piece of text. Since I'm not so proficient with regexes I thought this is a good moment to learn something new.
So I've got a the following regex:
r'\b0*[1-9]?[0-9]\b'

which (if I understand correctly) retrieves a number beginning with zero or more 0's, followed by zero or more numbers between 1 and 9, and 1 number between 0 and 9. So it matches the following:
10
24
01

but it also matches the following things (which are obviously not dates)
94
0000024

while it doesn't match the following (which are in fact dates):
1st
3rd
5th

So I set out to put in words what I need and tried writing the regex behind it what I came up with:

*

*a string starting with either a space, a dash, a slash or nothing at all (i.e. starting directly with the numbers)

*

*my attempt:    \b|-|\/

*a total of 1 or 2 numbers in the string. The number(s) together should be between 1 and 31 with either a leading zero or not.

*

*my attempt:    [1-9]|0[1-9]|[1-2][0-9]|3[0-1]

*either followed by "st", "nd", "rd", "th", a dash, a slash or a space.

*

*my attempt:    st|nd|rd|th|-|\/|\b
Putting this together it would be: \b|-|\/[1-9]|0[1-9]|[1-2][0-9]|3[0-1]st|nd|rd|th|-|\/|\b
But this doesn't seem to work at all. When I test the second part (the numbers) it matches pretty much all numbers I put in.
I don't want to make this a give me ze code question, but could anybody help me out by pointing out what I'm doing wrong? I really want to learn use regexes some more.
All tips are welcome!
ps. I know that some months have less days than 31, but I have to start learning somewhere..
[EDIT]
So to make clear (@Saraiva asked for this in the comments). I want it to match the following:
01
08
9
28
31
2nd
31st
/31st
-22nd/
/25-

but not this:
73
01200
026
/2200nd-
(6th

A: Your regex fragments are correct, you are just making it wrong how to put it all together. If you do this:
\b|-|\/[1-9]|0[1-9]|[1-2][0-9]|3[0-1]st|nd|rd|th|-|\/|\b

you are or-ing (|) everything (so, you match a word boundary, or a dash, or....).
You want something like this:
(?:\b)(([1-9]|0[1-9]|[1-2][0-9]|3[0-1])(st|nd|rd|th)?)(?:\b|\/)

so:
a word boundary (non capturing)
followed by a number 0-31
followed (eventually) by one of st nd rd th
followed by a word boundary (non capturing) or a slash

Example here: https://regex101.com/r/zM4lI5/3
You may get even better results, if you switch to using look-around:
(?<=\b|\/|-)((?:[1-9]|0[1-9]|[1-2][0-9]|3[0-1])(?:st|nd|rd|th)?)(?=\b|\/|-)

(?<=\b|\/|-) whatever matches the following, if preceded by this
(?=\b|\/|-)  whatever matched the preceding, if followed by this

Sample: https://regex101.com/r/zM4lI5/4
EDIT:
If you do only want to capture digits, i'd change the rexgex like this, playing with non-capturing groups:
(?<=\b|\/|-)([1-9]|0[1-9]|[1-2][0-9]|3[0-1])(?:st|nd|rd|th)?(?=\b|\/|-)

EDIT 2: ok I see that Python requires that look-behind assertions have constant length; in our case, \b is 0, while \/ and - are 1 character. If it is good for you, I'd suggest to just use a whitespace instead of the word boundary:
(?<=\s|\/|-)([1-9]|0[1-9]|[1-2][0-9]|3[0-1])(?:st|nd|rd|th)?(?=\b|\/|-)

Sample here: IDEONE regex101


text:
Q: Which per-site-metas are offered in the chat-room creation dialogue? Chat rooms can be associated with meta sites, as discussed, for example, here: Why can meta sites be parents of chatrooms? (In this post you can notice that there were some recent changes concerning where the rooms associated with metas are displayed.)
So I wanted to test whether it is possible to create a new room associated to a meta site. To my surprise, this was possible only for some sites. For example, if I start to type "math", several metas are offered. When I start to type "history", I am only offered main sites. See the screenshots below. (Or you can test this for yourself in the dialogue for creating new rooms.)
This experiment suggests that only the meta sites, for which at least one room already exists, are offered. I have listed metas which had a chatroom here (at the time of posting that question).
In a comment another explanation was suggested, namely that meta sites are not offered for beta sites. For this reason I have included a third screenshot showing that - at the moment - meta is offered in this dialogue neither for Information Security nor for Seasoned Advice. (However, for Server Fault both meta and main are in the list.) So the distinction between beta sites and graduated sites is not sufficient to explain this.

Why only some metas are offered in this dialogue as possible room parents? Is it on purpose?

I do not think it is a big deal. But I can imagine a situation where associating room with meta might be useful. For example, imagine that community around some SE site wants to have two separate rooms: A "main chat room" for general discussion about the subject of this site and a "meta chat room" for various "janitorial" tasks (like closing, reopening, retagging, editing, flagging and advice related to this - which is somewhat separate from the the subject of the site, more closely related to maintenance and moderating of the site). It is my understanding that at least one room associated with a site, be it a main site or meta, is kept alive, even if there was no activity for 14 days. (And this comment by Marc Gravel seems to confirm this.) So the advantage of this arrangement would be that the "janitorial" room would not be frozen even if there were some periods of inactivity. (Assuming it is the only room associated with that particular meta site.)
Perhaps you can think  of some other scenarios when having meta as a parent room might be useful. However, this is not that important for my main question - I am simply asking why the dialogue for room creation behaves in the way described above and whether it is status-bydesign.

Here are the screenshots:

EDIT: Very recently the only room associated with Meta Mathoverflow has been frozen and deleted by a moderator. It seems that this changed the list of rooms offered in this dialogue - Meta Mathoverflow is not offered there anymore. (You can notice that in the screenshot which I took less than an hour ago, Meta Mathoverflow was one of the possibilities.)


text:
Q: RST controller in Mathematica I was wondering, if it is possible to simulate an RST controller using Mathematica ?

This is what I tried, but the computation of the closed loop does not work:
G = TransferFunctionModel[(0.1*z^-1 - 0.2*z^-2)/(1 - 1.3 z^-1 +
      0.42*z^-2), z];
R = TransferFunctionModel[3 - 3.94 z^-1 + 1.3141 z^-2, z];
S = TransferFunctionModel[1 - 0.3742 z^-1 - 0.6258 z^-2, z];
T = 0.3741;

HclosedLoop = T/(1 + R/S);

OutputResponse[HclosedLoop, UnitStep[t], t]

A: You have to add a few things to your code:
Mathematica has to know that these are discrete time transfer functions and the constant T(z) has to be a TransferFunctionModel object as well.
plant = TransferFunctionModel[(0.1*z^-1 - 0.2*z^-2)/(1 - 1.3 z^-1 +
  0.42*z^-2), z, SamplingPeriod -> Td];
controller =
  TransferFunctionModel[1/(3 - 3.94 z^-1 + 1.3141 z^-2), z,
   SamplingPeriod -> Td];
sensor = TransferFunctionModel[1 - 0.3742 z^-1 - 0.6258 z^-2, z,
   SamplingPeriod -> Td];
filter = TransferFunctionModel[0.3741, z, SamplingPeriod -> Td];

compute the complimentary sensitivity transfer function T(z) of the system (do not confuse this with your filter)
sys1 = SystemsModelSeriesConnect[controller, plant];
sys2 = SystemsModelFeedbackConnect[sys1, sensor];
Tz = SystemsModelSeriesConnect[filter, sys2]

Now you can simulate and plot the step response
 resp = OutputResponse[Tz, Table[UnitStep[k], {k, 0, 20}]]

{{0.,0.01247,0.0197026,0.00735946,-0.0285393,-0.0852061,-0.157573,-0.240705,-0.330457,-0.423374,-0.516477,-0.607158,-0.693166,-0.772637,-0.844107,-0.906522,-0.959212,-1.00187,-1.03451,-1.05744,-1.07118,-1.07648,-1.07422,-1.06539,-1.05104,-1.03225,-1.01011,-0.985661,-0.95987,-0.93364,-0.90777,-0.882952,-0.859762,-0.83866,-0.819991,-0.803987,-0.790778,-0.780396,-0.77279,-0.767837,-0.765353,-0.765106,-0.76683,-0.770232,-0.775013,-0.780866,-0.787494,-0.794614,-0.801963,-0.809304,-0.816429,-0.823162,-0.82936,-0.834912,-0.839739,-0.843793,-0.847053,-0.849524,-0.851232,-0.852222,-0.852553,-0.852298,-0.851534,-0.850347,-0.848821,-0.847042,-0.845091,-0.843044,-0.840972,-0.838937,-0.836991,-0.83518,-0.833538,-0.832091,-0.830857,-0.829844,-0.829055,-0.828484,-0.82812,-0.82795,-0.827953,-0.828109,-0.828394,-0.828785,-0.829257,-0.829788,-0.830354,-0.830936,-0.831514,-0.832074,-0.8326,-0.833083,-0.833514,-0.833888,-0.834199,-0.834448,-0.834635,-0.834762,-0.834832,-0.834852,-0.834826}}

ListPlot[resp, Filling -> Axis, PlotRange -> All]

Or with the code from the example page
ListPlot[Map[Thread[{Range[Length[#]] - 1, #}] &, resp],
 Joined -> True, InterpolationOrder -> 0, PlotRange -> All]

I hope this helps.


text:
Q: Codeigniter : route doesn't work when calling php script through AJAX I have a JS file which calls a php script using a relative path. The path used has a matching route in route.php.
The issue is that the route doesn't seem to be correctly applied when the php script is called from the JS file.
More precisely, in the php file, the parameters $1 and $2 of the function do not contain the expected values (example below).
However, when using the url directly in the browser, the parameter $1 has the correct value.
route.php
$route['ajax/quizz/(:any)'] = 'test/ajax/$1';

JS file
var path        = 'ajax/quizz/load_items';  //path used for the AJAX query

Test.php
public function ajax($elt,$elt2 = "arg2"){

    switch($elt){
        case 'quizz' :
            echo "Shouldn't come here. Argument should be 'load_items': $1 $2";
            //$this->ajax_quizz();
            break;

        case 'load_items'   :
            $this->load_items($this->input->post(null,true));
            break;

        case 'add_stats'    :
            $this->add_stats($this->input->post(null,true),$_SESSION['id']);
            break;

        default :
            echo 'Unknown ajax function '.$elt;
    }
}

Expected behaviour
When the AJAX query is performed, the path specified (ajax/quizz/load_items) should match the route ajax/quizz/(:any) and the resulting path should be test/ajax/load_items.
As a consequence, we expect the controller test to be called, and function ajax to be executed, with argument $1 = load_items.
Actual behaviour
When called through AJAX, from the JS file, the path ajax/quizz/load_items has the following effect :

*

*The controller test is called

*The function ajax is executed

*Argument $1 = quizz (expected : load_items)

*Argument $2 = load_items

Direct access through the browser
When using this same path (http://localhost/codeigniter/ajax/quizz/load_items) directly in the browser, i get the expected behaviour :

*

*The controller test is called

*The function ajax is executed

*Argument $1 = load_items

Do you see where my issue might come from?

A: set your js ajax path full.Instead of using ajax/quizz/load_items use
http://localhost/codeigniter/ajax/quizz/load_items.


text:
Q: ZSA Moonlander backtick becomes § and shift backtick is ± Hello I hav the ZSA Moonlander MK2.
When I press the back-tick key, I have § as an outcome and shift back-tick produces ±.
Here is a recording of my virtual keyboard and output
How can I just have the backtick key actually do the backtick?

A: nevermind I re-set the keyboard to ansi according to here and it worked, thanks!https://www.zsa.io/moonlander/macos/


text:
Q: Why does SQLite not use indexes when you use 'IS' instead of '='? This query will not use the index: SELECT * FROM baz WHERE id IS '123'
http://sqlfiddle.com/#!7/7e299/2
This query will use the index: SELECT * FROM baz WHERE id='123'
http://sqlfiddle.com/#!7/7e299/1
Why??
EDIT: I realize there is the stupid answer of expanding the IS to get the correct effect (i.e. making the query SELECT * FROM baz WHERE id='123' OR '123' IS NULL, but I am still curious why this is the case.

A: There's no need to support indexing for such queries.
First, that's just how the query optimizer works:
To be usable by an index a term must be of one of the following forms:

  column = expression
  column > expression
  column >= expression
  column < expression
  column <= expression
  expression = column
  expression > column
  expression >= column
  expression < column
  expression <= column
  column IN (expression-list)
  column IN (subquery)
  column IS NULL

For the IS operator, NULL values are special:

The IS and IS NOT operators work like = and != except when one or both of the operands are NULL. In this case, if both operands are NULL, then the IS operator evaluates to 1 (true) and the IS NOT operator evaluates to 0 (false). If one operand is NULL and the other is not, then the IS operator evaluates to 0 (false) and the IS NOT operator is 1 (true).

In your question,
SELECT * FROM baz WHERE id IS '123'

and
SELECT * FROM baz WHERE id='123' OR id IS NULL

are not the same thing. (The latter can be satisfied using two index lookups.) It should be something like
SELECT * FROM baz WHERE id='123' OR (id IS NULL AND '123' IS NULL)

where the parenthesized expression is always false and therefore useless.
So IS and IS NOT is really only useful when used with NULL operand. With regular literal operand it is the same as = (or !=). And IS NULL can be satisfied by an index.