text:
Q: Symfony 2.6 - Security provider I am currently developping an application using Symfony2.6 And I have some trouble. I have two kind of users customers and employee so in my Database I have a table customer and a table employee. How can I tell symfony to go look in these two tables for the user credentials when the user try to log in?
I know that you can define a provider in the security.yml file which can be the entity but how can I declare two providers? is that possible or do I have to do this another way ?
thank all for you answers

A: I've got something similar with (currently) two different types of users. To handle all of the login and permissions though, I'm using FosUserBundle, and assigning them roles which I can check and then fetch user-profiles based on that.
To ensure that they get the correct ROLE_* assigned on the user creation I've followed the SO question, Adding new FOSUserBundle users to a default group on creation. They pickup a session variable with the future-role they will take, and then I have an event listener to set that role to the newly minted FosUser:
<?php
class UserCreationListener implements EventSubscriberInterface
{

// lots of constructor setup, debugging, logging and checks removed from code

public static function getSubscribedEvents()
{
    return array(
        FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
    );
}

public function onRegistrationSuccess(FormEvent $event)
{
    $user = $event->getForm()->getData();
    $newRole = $this->session->get('futureRole', 'ROLE_CUSTOMER');
    $user->addRole($role);
    $this->userManager->updateUser($user);
    return $this->redirect->redirect('app_profile', 302);
}

}

A: So thx to someone here i've found the answer to this specific problem here
http://symfony.com/doc/current/cookbook/security/multiple_user_providers.html
Symfony allows us to declare a multiple user providers


text:
Q: Problem constructing where clause to include null/0 values I have an application where users can take tests (which are composed of questions and answers).
I'm trying to construct a query that returns a count of answers grouped by question, for a specific teacher and test.
The problem is I would like the query to return 0 count for questions with no answers.
answers

*

*id

*question_id

*test_id

*student_id

questions

*

*id

teacher_students

*

*student_id

*teacher_id

tests

*

*id

Query
   SELECT COUNT(answers.id) AS rcount,
          questions.id
     FROM "questions"
LEFT JOIN answers ON answers.question_id = questions.id
LEFT JOIN teacher_students ON teacher_students.student_id = answers.student_id
    WHERE (questions.test_id = 1)
      AND (teacher_students.teacher_id = 1)
 GROUP BY questions.id
 ORDER BY questions.id

Output
 rcount | question_id
--------+----
      4 | 1
      2 | 3

Desired Output
 rcount | question_id
--------+----
      4 | 1
      0 | 2
      2 | 3
      0 | 4

If I remove teacher_students.teacher_id = 1, the number of questions returned is correct, but the count is not.

A: Move the teacher_students.teacher_id = 1 check from the WHERE clause to the joining ON clause.
When a condition that refers to a table in the right side of a LEFT JOIN is put in the WHERE clause, the LEFT JOIN is cancelled and it acts as an INNER JOIN.
SELECT count(teacher_students.student_id) AS rcount      <--- changed
     , questions.id
FROM "questions"
  LEFT JOIN answers
    ON answers.question_id = questions.id
  LEFT JOIN teacher_students
    ON teacher_students.student_id = answers.student_id
    AND teacher_students.teacher_id = 1
WHERE questions.test_id = 1

GROUP BY questions.id
ORDER BY questions.id

redpajama_set_name: RedPajamaStackExchange


text:
Q: Floating containers so that they are both at bottom I have got a ul list which has several li elements which need to be floated left.
Each li contains an image of variable height either 150px or 200px. So what we get is multiple boxes(li) with images inside them.
This is the exact html inside an li

        MrSpock

Now if an image in any of the li elements is of height 200px and the adjacent li has an image of height 150px, the li with image 150px height stacks up on the top right edge of the li with 200px height. ( Remember both are floated left)
I want the li elements to stack up as if they were boxes of diff height kept on a floor.
Restrictions : I cannot change this html, there can be multiple li elements in which case the images flow to the next row. We do not know in advance if all the images in a row will be of same or diff height.
Is there a CSS only solution possible for this ? Heres a link to my problem :
https://dl.dropboxusercontent.com/u/88049315/home.html
I want the containers in the first row to all align at the bottom.

A: What about this fiddle?

 #container
    {
        width:200px;
        height:200px;
        background-color:#333;
        display:table-cell;
        vertical-align:bottom
    }

    .content
    {
        width:48px;
        height:48px;
        background-color:red;
        float:left;
        margin: 1px;
    }

As long all the floating content together does not have a width larger then the container everything is fine. After that the float functionality takes over and positions the first line one row above the bottom.
Otherwise you could rotate the conainer div so all content in it goes with it. This is more of a hacky way and can cause issues further down the line. The Fiddle


text:
Q: emberjs where should document ready functions go? I'm trying to attach a typeahead to a text input in one of my templates. Because Ember use's handlebars, jQuery's document ready function is not the place for the typeahead definition. Where is the proper place to put "template ready" code? I tried a controller but there was no response from the typeahead. I don't think the template was rendered yet.
App.PersonController = Ember.ObjectController.extend({

    isEditing: false,

    init: function(){
        this._super();

        $('.example-films .typeaheadcx').typeahead([{
              name: 'best-picture-winners',
              remote: 'http://twitter.github.io/typeahead.js/data/films/queries/%QUERY.json',
              prefetch: 'http://twitter.github.io/typeahead.js/data/films/post_1960.json',
              template: '
{{value}} – {{year}}
',
              engine: Ember.Handlebars
        }]);
    },

    actions: {
        edit: function() {
            this.set('isEditing', true);
        },

        doneEditing: function() {
            this.set('isEditing', false);
        }
    }
});

A: The correct place is didInsertElement of Ember.View.
For example:
Template

View
App.FooView = Ember.View.extend({
  templateName: 'foo',
  didInsertElement: function() {
    console.log(this.$().text()); // will log 'hello world'
  }
});


text:
Q: Откуда берется номер строки исключения в Java? К примеру, наш исходный код выполняет деление на ноль в строке 8.
Если собрать jar-файл из этого кода и запустить - ArithmeticException опять скажет нам про строку 8 в нашем исходнике.
Получается, что в .class-файлах сохраняется даже форматирование исходника (java)? Или тут какой-то другой механизм?

A: При компиляции по умолчанию добавляется номер строки в получаемый byte-код.
Можно настроить объем debug-информации, попадаемый в генерируемые файлы, с помощью параметра компилятора -g:
-g:none                Без отладочной информации.
-g:lines               Только номера строк.
-g:lines,source        Номера строк и информация об исходном файле.
-g:lines,source,vars   Номера строк, информация об исходном файле и данные о локальных переменных.
-g                     То же самое, что и -g:lines,source,vars

Значение по умолчанию: -g:lines,source.


text:
Q: FTP Deleted Folder keeps reappearing I have the following WP site hosted under mediatemple:
http://actividades.acropolis.org.mx.s160231.gridserver.com/actividades
(the way it is set up (I didn't do it, I was just tasked to migrate the site over from a crappier host) is that the actividades page becomes the index/home page of the site)
Everything was nice and dandy until yesterday when suddenly, out of nowhere, the old folder /actividades/ (that I had deleted hours before) which shares the same name as the pagename... recreated itself.
This leads to having:
http://actividades.acropolis.org.mx.s160231.gridserver.com/actividades/
Since the apache modrewrite name of the page matches the folder name...it conflicts. To make matters worse, the folder gets 750 permissions instead of 755 which doesn't let .htaccess and apache get into it. If I fix the permissions, you do enter the folder but get the classical (index file not found) crap.
Index page or not, I don't give a damn about the folder...its conflictive and needs to be gone forever...
So I deleted it, fixed the issue and noticed it remade itself 5 seconds later.
I've tried everything, googled everything and there does not seem to be any answer from either a server-side viewpoint nor a wordpress angle.
So broken and defeated I come to you experts for words of wisdom.

A: The plugins installed on this particular wp site turned out to have some info stored in them that kept the former location they were in, in this case the folder /actividades/ before i even began working on the site.
So someone moved them via ftp out of the /actividades/ folder and into the root which did not update the path in which these plugins record their images and data and blabla so they kept remaking the folders...
I deleted the core wp files then the wp content folder and then the remainder of the site and went for a clean re-install.
Given the messy php nature of wordpress itself, not to mention that of its plugins... it was simpler this way. Locating the precise script that triggered the folder recreation was out of my league.


text:
Q: Ignore prerequisite building output only from GNU make What is a simple way to ignore all output from GNU make's building prereqs, but keep all the rest (both stdout and stderr).  I'm working with a script that randomly uses either stream.  So, for example, if I have
t: main.native ${STUFF}
        ./${SCRIPTS}/run-tests

How can I just do make t &> output and get the output without all the rebuild info from the prerequisites prepended (eg. only outputs from run-tests in the above example)?

A: I'm still not quite sure what you're looking for, but you can do this:
t: main.native ${STUFF}
    @echo PREREQS_DONE
    ./${SCRIPTS}/run-tests

>make t | sed '1,/PREREQS_DONE/d'

Or this:
t:
    @$(MAKE) real_t  | sed '1,/PREREQS_DONE/d'

real_t: main.native ${STUFF}
    @echo PREREQS_DONE
    ./${SCRIPTS}/run-tests

A:
How can I just do make t &> output and get the output without all the rebuild info from the prerequisites prepended (eg. only outputs from run-tests in the above example)?

Build targets main.native ${STUFF} first and then run tests only. E.g.
tests : main.native ${STUFF}

run_tests : tests
    ./${SCRIPTS}/run-tests

.PHONY : tests run_tests

And then:
make tests && make run_test &> output


text:
Q: VSTO/WinWord Bind to Entering Event for DropDownListContentControl I have a VSTO addin (not a template project), and I'd like to bind to the Entering event for any content controls manually added to the document, but can't figure out how to do the binding.
It's easy enough to find the appropriate Content Controls:
ActiveDoc.ContentControls.Cast<ContentControl>()
    .Where(cc => cc.Type == WdContentControlType.wdContentControlDropdownList)

ContentControl doesn't have any events at all, so it seems like I need to somehow obtain a DropDownListContentControl but I haven't been able to figure out how to get that from the ContentControl or any other source.

*

*You can't just cast ContentControl to DropDownListContentControl because there are no parents in common.

*I thought I might be able to find by using dynamic, but those don't support events.

*In Template Projects ContentControls are created using Globals.Factory.CreateDropDownListContentControl, but that doesn't seem to work for Addin projects.

I'm guessing there's something simple I'm missing, but hours of googling have been fruitless so far.
TIA

A: Guess I just didn't look long enough.  To do it you need to wrap your Microsoft.Office.Interop.Word.Document in a confusingly named Microsoft.Office.Tools.Word.Document using this:
Microsoft.Office.Tools.Word.Document doc
    = Globals.Factory.GetVstoObject(Addins.Globals.Application.ActiveDocument);

That class has a set of methods that will generate a wrapper with more events than the native controls.  So to get an event on any droplist, you do something like:
        Microsoft.Office.Tools.Word.Document doc = Globals.Factory.GetVstoObject(ActiveDoc);
        foreach (ContentControl cc in ActiveDoc.ContentControls) {
            if (cc.Type == WdContentControlType.wdContentControlDropdownList) {
                var dropList = doc.Controls.AddDropDownListContentControl("MyControl");
                dropList.Tag = "MyControl";
                dropList.Entering += (sender, args) => {
                    var that = (DropDownListContentControl) sender;
                    Debug.Print("Entering: " + that.Tag);
                };
            }
        }

That's all there is to it, other than the controls themselves are pretty terrible from a usability perspective.
See Host Items and Host Controls Overview.

A: Document extendedDocument = Globals.Factory.GetVstoObject(Application.ActiveDocument);
int nIdx=0;
foreach(Word.ContentControl ctrl in Application.ActiveDocument.ContentControls)
{
ContentControl newCC =

extendedDocument.Controls.AddContentControl(ctrl, "contentControlName"+nIdx.ToString());
    newCC.Entering += new ContentControlEnteringEventHandler( enteringEventHanlder);
    nIdx++;
}

it is code that coverting native content control to content control.
it maybe help you.


text:
Q: how many points belong to the quadric $x_0^2+x_1^2+x_2^2+x_3^2=0$ in $\mathbb{P}_3$ over $\mathbb{F}_9$ I have a problem with the following question: how many points belong to the quadric $x_0^2+x_1^2+x_2^2+x_3^2=0$ in $\mathbb{P}_3$ over $\mathbb{F}_9$.
How I tried to solve this problem. Here we have $9^4$ sets of $x_i$, but for every set we can choose only 3  first values ($x _0$,$x_1$ and $x_2$), then we can count $x_3$ for every triplet. So we have $9^3$ sets. Then for every set of $x _0$, $x_1$, $x_2$, $x_3$ which is solution $ax _0$, $ax_1$, $ax_2$, $ax_3$ is also a solution ($a$ is a non zero element of $\mathbb{F}_9$). So we have $(9^3-1)/8=91$ options. But it is still too much! And I don't know any other ways of counting the amount of points.
Sorry for my English, thank you!

A: The idea of @user670344:
Over every finite field $F$ the equation $a^2 + b^2 = -1$ has a solution. For the matrix $A = \left(\begin{matrix} a & -b \\  b & a\end{matrix}\right)$ we have $A^t \cdot A = - I_2$. We conclude that the quadratic forms $x^2 + y^2$ and $- x^2 - y^2$ are equivalent.  Therefore, over any finite field the quadratic forms $x_0^2 + x_1^2 + x_2^2 + x_3^2$ and $x_0^2 - x_1^2 + x_2^2 - x_3^2$ are equivalent.
If  $\operatorname{char} F\ne 2$  then the last form is equivalent to $Q=y_0 y_1 - y_2 y_3$.
Now, over any field, the zero set of $Q$ in $\mathbb{P}_3(F)$ is in bijection with $\mathbb{P}_1(F) \times \mathbb{P}_1(F)$ by the map
$$([a_0\colon a_1], [b_0, b_1])\mapsto [a_0 b_0\colon a_2 b_2 \colon a_0 b_1 \colon a_1 b_0]$$
(a matrix $2\times 2$ of rank $1$ is a product of matrices  $2\times 1$ and $1\times 2$).
Conclusion: over any field of odd cardinality $q$ the quadric $Q$ has $(q+1)^2$ elements.

A: You can try a brute force approach: Simply have a small computer program iterate over all the possible values for your $x_i$. For example in Sage:
from itertools import product
F9 = FiniteField(9)
len([(a,b,c,d) for a,b,c,d in product(F9, repeat=4) if a*a+b*b+c*c+d*d==0])

You will find 801 combinations. One of them is the null vector. And for each of the other values, you get $9-1=8$ possible representations of each point. So you have 100 points on your quadric. Of course if you already use Sage for finite field arithmetic (as I do because I'm lazy), you can leave the rest to it, too:
P3.<x0,x1,x2,x3> = ProjectiveSpace(3, F9)
s = P3.subscheme(x0^2+x1^2+x2^2+x3^2)
s.count_points(1)         # 1 because we want this for field of size 9^1
len(s.rational_points())  # without len this gives you the coordinates


text:
Q: Can I install Jenkins on an unpriviledged account? I'm trying to test Jenkins and see how it would work for our project. The problem is, there are a lot of policies and restrictions about services on my work computer , and Jenkins fails to start with the message:
Cannot start service from the command line or a debugger. A Windows
service must first be installed ...

Is there a possibility of running Jenkins without installing it ( maybe in a portable way )? I cannot create services, nor special user accounts for it.

A: Yes, this should be possible, since starting Jenkins is actually a prerequisite to installing it.
First, verify that you have JRE 1.5 or later. Then it should "just work" with
java -jar jenkins.war

Alternatively, you could launch Jenkins through Java Web Start (test drive mode) then visit http://localhost:8080/ to configure.
If your local policies allow installing a VM host system, a longer way around would be to create a guest VM that allows you to create priviledged accounts.
Finally, if you have a servlet container that supports Servlet 2.4/JSP 2.0 or later (Glassfish, Tomcat 5, JBoss, Jetty 6) you can deploy jenkins.war like a normal WAR file.


text:
Q: NHibernate: Get distinct results based on a column, but retrieve all columns I have a table GL that contains GLCode. I need to get a list of unique GLCodes, but get all the other columns. The following SQL produces the results I want.
select * from GL where GLId in (select Min(GLId) from GL group by GLCode )

Is there a way to do this using the Criteria API?
This is my best attempt:
        var subQuery = DetachedCriteria.For<GL>();
        subQuery
            .SetProjection(Projections.Property("GLCode"))
            .SetResultTransformer(new DistinctRootEntityResultTransformer());

        return (List<GL>)currentSession
            .CreateCriteria(typeof(GL))
            .Add(Subqueries.PropertyIn("GLCode", subQuery))
            .List<GL>();

A: Even though NHibernate doesn't have a way to exclude GLCode from the subquery's result columns, it is still possible to create a query that does the job.  Use a correlated EXISTS subquery instead of IN.  The SQL we're shooting for is like this:
select query.*
from GL query
where exists (
    select
        min(subquery.GLId) AS GLId,
        subquery.GLCode
    from GL subquery
    group by subquery.GLCode
    having min(subquery.GLId) = query.GLId);

And here's the NHibernate query:
var min = Projections.Min("GLId");

var subquery = DetachedCriteria.For<GL>("subquery")
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.GroupProperty("GLCode"), "GLCode")
        .Add(min, "GLId"))
    .Add(Restrictions.EqProperty(min, "query.GLId"));

return session.CreateCriteria<GL>("query")
    .Add(Subqueries.Exists(subquery))
    .List<GL>();


text:
Q: php Mysqli - i want to change id number of some rows to end id my table has an id field with auto_increment and I want some rows to move to end of the table (changing number id to end number).
Like This:
$query= mysqli_query($con,"UPDATE moshakhasat SET id=<?end table?> WHERE username='$username' ");

sorry about this code. I don't know a lot about PHP
I am tired and really need your help
Thank you.

A: I'm not sur if you can change that as mysql is handling the auto increment.
But maybe you could insert new row with your data and then delete the old row.
you could use the INSERT... SELECT syntax
INSERT INTO tbl1 (field1, field2, ...)
  SELECT tbl1.field1, tbl1.field2
  FROM tbl1 WHERE id IN (1,2,3,4);

then
DELETE FROM tbl1 WHERE id IN (1,2,3,4)


text:
Q: Need to use python variable in mysql query through os.system() ID="VC002538"
mysql -u xxxxx --password=xxxxx -e "SELECT orderid FROM Pran_order_detail WHERE orderid='$ID'"

sample
Above query I will execute in Linux shell prompt, it executed successfully with below output
+------+
| id   |
+------+
| 1140 |
+------+

But when do the same in python with os.system() method
I am not getting any output
ID="VC002538"

os.system('mysql -u xxxxx --password=xxxxx -e "SELECT orderid FROM Pran_order_detail WHERE orderid='ID'" sample')

but when I tried with ID value directly
os.system('mysql -u xxxxx --password=xxxxx -e "SELECT orderid FROM Pran_order_detail WHERE orderid='\VC002538\'" sample')

This is working
Please let me know how to use the variable in os.system() in sql query

A: In your first example, what Mysql sees is this query:
SELECT orderid FROM Pran_order_detail WHERE orderid='ID'

You need to construct a string using the variable ID, for example like this:
"SELECT orderid FROM Pran_order_detail WHERE orderid='%s'" % ID

or
"SELECT orderid FROM Pran_order_detail WHERE orderid='" + ID + "'"

or
"SELECT orderid FROM Pran_order_detail WHERE orderid='{}'".format(ID)

You can find more information by googling "python string formatting".


text:
Q: Maven : no main manifest attribute, in target/xx.jar, Unable to execute jar file Here is the pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project
        xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>dl4j</groupId>
    <artifactId>dl4j</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>example.JavaTestExample</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.deeplearning4j</groupId>
            <artifactId>deeplearning4j-core</artifactId>
            <version>1.0.0-beta3</version>
        </dependency>
        <dependency>
            <groupId>org.nd4j</groupId>
            <artifactId>nd4j-native-platform</artifactId>
            <version>1.0.0-beta3</version>
        </dependency>
        <dependency>
            <groupId>org.datavec</groupId>
            <artifactId>datavec-api</artifactId>
            <version>1.0.0-beta3</version>
        </dependency>
        <!--  You need the below dependency to use CodecRecordReader-->
        <dependency>
            <groupId>org.datavec</groupId>
            <artifactId>datavec-data-codec</artifactId>
            <version>1.0.0-beta3</version>
        </dependency>
        <!--       <dependency>
                   <groupId>org.bytedeco.javacpp-presets</groupId>
                   <artifactId>${moduleName}-platform</artifactId>
                   <version>${moduleVersion}-1.4.4</version>
               </dependency>-->
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacv-platform</artifactId>
            <version>1.4.4</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacpp</artifactId>
            <version>1.4.4</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.8.0-beta4</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.8.0-beta4</version>
        </dependency>
        <!--  You need the below dependency to use LocalTransformExecutor-->
        <dependency>
            <groupId>org.datavec</groupId>
            <artifactId>datavec-local</artifactId>
            <version>1.0.0-beta3</version>
        </dependency>
    </dependencies>
    <!-- Uncomment to use snapshot version -->
    <!--<repositories>
        <repository>
            <id>snapshots-repo</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>  <!– Optional, update daily –>
            </snapshots>
        </repository>
    </repositories>-->
</project>

I wanted to run maven-assembly-plugin and create a jar file with all dependencies added to it. When I run java -jar jarfile.jar, I get the below error:
no main manifest attribute, in target/jarfile.jar
I went through several Stack Overflow posts for the same and tried all permutations and combinations. I tried adding both assembly and shade plugins. You can see the settings I have in my pom.xml above. I'm not really sure on how this is happening even though I added proper maven settings.
I verified that Java is running fine:

I verified whether I specified the main class correctly.
Everything looks fine for me except the results and I'm confused at the moment.
What might be going wrong? I expect some of them still mark the question as "duplicate", but I have been reading other posts and tried changing the settings accordingly. None of them worked.

A: Good quality question!
I  think this will help achieve your goal.
This is what I use to build a clickable JavaFX Jar with all dependencies included.
This is using maven-jar-plugin and maven-shade-plugin rather than maven-assembly-plugin; Here is a good resource on the differences.
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <release>10</release>
            </configuration>
        </plugin>
        <plugin>
            <!-- I think you don't need this one -->
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.6.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>${mainClass}</mainClass>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>
                            ${mainClass}
                        </mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.2.0</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ApacheLicenseResourceTransformer" />
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>${mainClass}</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


text:
Q: Neo4j free text search combined with relation query I see that Neo4j have Indexes to support full-text search. But I can't find examples in the documentation on how to use this ability with regular relations query.
For example, I have the following structure: (:User)->[:Wrote]->(:Review)->[:Reviewing]->(:Movie)
I want to search Reviews with the full-text-search ability but only for a specific user. So user '123' want to search all his reviews with 'great acting' in them. So search the user's reviews would be MATCH (:User { id: 123 })-[w]->(review). While searching for reviews with the words 'great' and 'acting' would be CALL db.index.fulltext.queryNodes("reviews", "great acting")
What I can't figure out is how to combine the two with AND logic.
EDIT
I figured I can do the following thing:
CALL db.index.fulltext.queryNodes("reviews", "great acting") YIELD node as reviews
MATCH (:User { id: 123 })-[w]->(reviews)

The thing is, I may have millions of reviews with "great" or "acting" in them while the relevant user probably doesn't have more than 10s reviews. It doesn't sound very efficient.

A: In this particular case full text search won't be a help performance-wise, as this would select all reviews containing 'great acting' (of which there are likely a great, great many) and then you would need to filter to those belonging to the user in question.
This is far less performant than matching to the reviews of the user in question (of which there should be comparatively far far fewer) and then filtering those for the word 'great acting'.
You can use the CONTAINS keyword in your WHERE clause to ensure the property contains the given substring, as in Raj's answer (though this is case sensitive):
MATCH (:User{ id: 123 })->[:Wrote]->(review:Review)->[:Reviewing]->(:Movie)
WHERE review.text CONTAINS 'great acting'
...

You can also create an index on this, though it's far more efficient if it doesn't get used for lookup here and instead starts with the user node (you can EXPLAIN the query to determine what indexes are used to find the starting node(s)).
If you need case insensitive searching of keywords, you can use the =~ regex operator for this, though this is not index-backed. For example:
MATCH (:User{ id: 123 })->[:Wrote]->(review:Review)->[:Reviewing]->(:Movie)
WHERE review.text =~ '(?i).*great acting.*'
...

A: Don't know how to use the full-text search in this case but I think you can use a single property index with CONTAINS predicate in this case.
If you are searching over a single property of node then you can index that property and search with CONTAINS predicate.
Create Index:
CREATE INDEX ON :Review(text)

Search query:
MATCH (:User{ id: 123 })->[:Wrote]->(review:Review)->[:Reviewing]->(:Movie)
WHERE review.text CONTAINS 'love'

P.S.:
Another approach could be first search review nodes using full-text search and then filter these review nodes for a user by matching in the above query. I doubt this will do any performance improvements.

A: You can use following query with the help of APOC library. Assuming you have unique identifier for reviews (id)
MATCH (:User { id: 123 })-[w]->(reviews)
WITH collect(reviews.id) AS reviewIds
WITH "(" + apoc.text.join(reviewIds, " OR ") + ")" AS str
CALL db.index.fulltext.queryNodes("reviews", "text:great acting id:" + str)
YIELD node as reviews


text:
Q: Apache .htaccess to use subfolder as root I know this kind of question is recurrent. But after several hours of searching I didn't find anything.
I'm making a website using Slim. However, in their documentation, they use /public as root directory, which I don't want. I want the website root to be /. Quite concerned about security, I created a .htaccess to redirect http://www.example.com/ to http://www.example.com/public/, so no user can reach /src and other folders :
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^$ /public [P]
</IfModule>

This causes a problem : the URI remains /public/, therefore the public/index.php file below returns a 404 error :
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/', function (Request $request, Response $response, $args) {
    $response->getBody()->write("Hello world!");
    return $response;
});

$app->run();

I have to replace '/' with '/public/' in the code for the page to work. I don't exactly like that.
What should I add to Slim's /public/.htaccess below to remove the /public from the URI ?
<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
  RewriteRule ^(.*) - [E=BASE:%1]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.php [QSA,L]
</IfModule>

Edit: Solution used
I redirected my vhost to /public/. The web hosting service I use supports this, so it's the best solution.
Thanks to MrWhite.

A:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^$ /public [P]
</IfModule>

This only "forwards" requests for the root / homepage, ie. /, not /foo, etc. This also forwards the request using mod_proxy (as a reverse proxy), whereas you only need a simple internal rewrite.
You need to rewrite every request that would otherwise go to the root directory (outside of /public) to the /public subdirectory. ie. /foo rewrites to /public/foo and /images/bar.jpg to /public/images/bar.jpg, etc.
 RewriteEngine On
 RewriteRule (.*) /public/$1 [L]

(No need for the <IfModule> wrapper since mod_rewrite is mandatory here, it's not optional.)
All your URLs (to everything) should then omit the /public subdirectory.
UPDATE: However, it would seem that the BASE environment variable is still being set to the /public subdirectory by the following directives in /public/.htaccess:

RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]

You could simply comment out (remove) the above directives and hardcode the BASE env var:
SetEnv BASE /

However, it's unclear whether this would be a problem or not in the Slim framework. It's possible that this is being used to construct URLs (although it shouldn't, since this is the filesystem path, not the URL-path by which users access the pages - and can easily be calculated in PHP anyway).

Alternatively, everything in /public should be in your document root (ie. your public directory... public_html or htdocs etc.) then the /src (and other folders) will naturally be outside the document root and no additional directives / .htaccess files required to root the request. (Although not every shared server may give you access to above the document root - although they should.)
Or, simply change the DocumentRoot to /public in your server config.


text:
Q: Adding extra params to custom option select html I'm working on a custom theme for a client. Is it possible to add extra parameters to the html for the custom options select without having to extend Mage_Core_Block_Html_Select or Mage_Catalog_Block_Product_View_Options_Type_Select?
I can see in Mage_Core_Block_Html::_toHtml() that there is a call to $this->getExtraParams() but I can't seem to find anywhere that I would utilize this.
Is there a simple way to do this?

A: In the end, I just went ahead an extended the class in a custom module.


text:
Q: Can I use iBeacon in Android with Nearby Messages? In the Beacon overview it says that the Proximity Beacon API supports iBeacon.
Does this mean I can detect an iBeacon and retrieve data attached to it with the Nearby Messages API in an Android app?
EDIT: Since the Get Beacon Messages for iOS says as a note: "The Nearby API for iOS only supports finding Eddystone beacons", but it doesn't say anything for the Nearby API for Android, maybe we can assume that it can see every type of beacons?
I'd still like a confirmation about this.

A: The good news is that Nearby supports iBeacon in addition to Eddystone beacons.
Using the Proximity Beacon API you can totally register iBeacons and attach data to them.
Then, you can tell Nearby to give you messages for the attachment data associated with these iBeacons (in Nearby, you just specify the attachment namespace for the appropriate strategies):
  MessageFilter filter = new MessageFilter.Builder()
      .includeNamespacedType("my-attachment-namespace", "")
      .build();
  Nearby.Messages.subscribe(client, messageListener, Strategy.BLE_ONLY);

See this Stackoverflow question for more hints on how to register an iBeacon using Proximity Beacon.
The note you saw is, however, correct: iBeacon is not supported on Nearby iOS just yet.

A: Nearby Messages on iOS now supports iBeacon scanning.  And support for background scanning was just added.  See the Nearby Messages Developer Site and the CocoaPod for details.


text:
Q: Specifying that a column should just be inserted not upserted I have some data i want to insert via insertGraph
ala ModelName
       .query(trx)
       .insertGraph(data)
 problem is I have a guard with allowInsert that specifies which columns should be populated. I have a column holding a foreign key to another table. I don't want this column to be populated. I keep getting trying to upsert an unallowed relation. I'm at a loss on how to specify that foreignId shouldn't be populated.
My code looks like this with the allowInsert guard
ModelName
       .query(trx)
       .allowInsert([subrelation2.[columnToPopulate1, columnToPopulate2]])
       .insertGraph(data)

P.s. I've tried specifying foreignId in the allowInsert condition to no avail. Specifying relation2.* allows the insertion. But I want to retain the sanity checks

A: Seems like you are specifying columns of the relation2 model, instead of subrelations. Is columnToPopulate1 a subrelation of the Model of relation2? By the name looks like a column of the model, which is wrong.
I think that you want to use a relations to insert two columns in the 'relation2' model. Something like:
let data = {
  modelNameColumn: 'value',
  relation2: {
    columnToPopulate1: 'value',
    columnToPopulate2: 'value',
  }
}

await ModelName
   .query(trx)
   .allowInsert('[relation2]')
   .insertGraph(data)

In allowInsert method you can only specify which relations are allowed to be inserted, but cant define which columns.
In case you want to remove the posibility of a column to be updated, you can use a beforeUpdate() trigger:
class Model2 extends Model {
  async $beforeUpdate(opt, queryContext) {
    await super.$beforeUpdate(opt, queryContext);
    if (this.columnName) throw new Error('columnName shouldnt be updated')
  }
}


text:
Q: Non-blocking thread that runs an external process I have created a Java GUI application which functions as a wrapper for many low level external processes.  The utility works as is, but is in desperate need of one major improvement.
I want my external process run in a non-blocking manner which would permit me to service additional requests in parallel.  In a nutshell I want to be able to process data from the external process as the data is being generated. But it appears my basic attempt to check and see if the external process is still running is blocking.
Below is an excerpt from my ExternalProcess class.  Please see inline comments for specific Java functionality questions about threading and blocking.
public void Execute()
{
    System.out.println("Starting thread ...\n");
    Runner = new Thread(this, "ExternalProcessTest");
    Runner.run();
    System.out.println("Ending thread ...\n");
}

public void run()
{
    System.out.println("In run method ...\n");  // Debug purposes only.
        // Show that we are in the run loop.
    try
    {
        // Execute string command SomeCommand as background process ...
        Process = Runtime.getRuntime().exec(SomeCommand);
        while(IsRunning())
        {
            // External process generates file IO.  I want to process these
            // files inside this loop.  For the purpose of this demo I have
            // removed all file processing to eliminate it as the cause
            // of blocking.  THIS ROUTINE STILL BLOCKS!
            Thread.sleep(1000);
        }
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
    System.out.println("Exiting run method ...\n");  // Debug purposes only.
        // Show that we are exiting the run loop.
}

// Process (instantiated from Runtime.getRuntime().execute doesn't supports
// either fire-and-forget backgrounding (non-blocking) or you can wait for
// the process to finish using the waitFor() method (blocking).  I want to
// be able to execute a non-blocking external process that I monitor via
// threading allowing me to process the external process file IO as it is
// created.  To facilitate this goal, I have created an isRunning() method
// that uses the exitValue() method.  If the process is still running, a
// call to exitValue() will throw an IllegalThreadStateException exception.
// So I simply catch this execption to test if the background process is
// finished -- at which point I can stop processing file IO from the
// process.  Is this the source of the blocking?  If so, is there another
// way to do this?
public boolean IsRunning()
{
    boolean isRunning = false;
    try
    {
        int exitVal = Process.exitValue();
    }
    catch(IllegalThreadStateException e)
    {
        isRunning = true;
    }
    return isRunning;
}

A: Runner = new Thread(this, "ExternalProcessTest");
Runner.run();

The run() method is deceptively named. Because Thread implements the Runnable interface the run() method is exposed publicly, but it is not the right method to call when you want to kick off a new thread. Calling run() causes the thread code to be run in the current thread.
You must call start() to cause a new thread to be instantiated:
Runner = new Thread(this, "ExternalProcessTest");
Runner.start();

A: The run() method on Thread doesn't actually start a new thread, try using Thread.start() instead.


text:
Q: Have Vagrant+Chef run bail out if template files have been checked out with CRLF line endings I keep getting bit by an annoying gotcha that happens when Windows developers check out cookbooks from my Git repo with Git's autocrlf set to true.  When they run vagrant up to bring up a Linux VM, the cookbook files are mapped into the VM with CRLF line endings, which causes no end of obscure errors when the shell and other POSIX utilities try to operate on the (now invalid) template files that have been copied into the VM.
The fix for that is simple enough: re-clone the repository after changing the autocrlf setting to input or false.
My problem is that, when you have the wrong line endings, the only symptoms are errors in strange places that in no way point to there being a problem with line endings.
How can I have Chef† check for the wrong line endings in, say, the cookbook template files and throw an error if it finds one?  I think a simple Ruby snippet that does an assertion on the line endings in a given file that I can put at the top of a recipe would work.
Note: in the particular case of my repo, the sequence of steps is:

*

*Developer checks out repo

*Developer runs vagrant up

*Vagrant kicks off a Chef run in the VM

*Finally, the repo's build script runs in the VM

† Or really anything else included in the repo

A: Rubocop can be used to enforce unix style line endings (among many other things).
For example (from the command line, within the guest):
gem install rubocop
rubocop --only Style/EndOfLine  # only check line endings

Or it could be done from within the context of chef itself with something like the following recipe:
chef_gem 'rubocop'

ruby_block 'check line endings' do
  block do
    # It's probably better to call rubo cop code directly, rather than
    # shelling out, but that can be an exercise for the reader ;-)
    rubocop_cmd = Mixlib::ShellOut.new(
      'rubocop --only Style/EndOfLine',
      :cwd => 'dir_to_check'
    )
    rubocop_cmd.run_command

    # Raise an exception if it didn't exit with 0.
    rubocop_cmd.error!
  end
end

The uncaught exception will cause the chef run to bail out.

A: Here's a Ruby snippet that you can put in any Chef recipe:
def cookbook_supporting_files(*cookbooks)
  cookbooks = cookbooks.map {|name| run_context.cookbook_collection[name]}

  cookbooks.flat_map do |cb|
    (cb.manifest[:files] + cb.manifest[:templates]) \
      .map {|f| ::File.join(cb.root_dir, f['path']) }
  end
end

def dos_eol?(f)
  ::File.open(f, 'rb').read(4096).include? "\r\n"
end

cookbook_supporting_files(cookbook_name).each do |f|
  if dos_eol? f
    raise "Cookbook template '#{f}' contains CRLF line endings"
  end
end

This will check the line endings of the cookbook files and templates that exist in whatever cookbook the above snippet is placed in.
If you want to have the same snippet check other cookbooks, simply replace:
cookbook_supporting_files(cookbook_name)

With the list of the cookbooks you want to check:
cookbook_supporting_files('some_cookbook', 'another_cookbook')


text:
Q: How can Android BLE read more than 20 bytes, requestMtu() is not working? I want to use Android BLE to receive more than 20 bytes one package, but it does not work. So I tried BluetoothGatt.requestMtu(). It returns true, but is not working. I know the MTU exchange request can only be initialized by client, that is an Android phone. I do not understand why this API is not working.
The phone I use is an OnePlus 6 with Android 8.1

A: It is not related to Android framework API. It belongs to Bluetooth BLE specification.
Please check more details here.
Maximum packet length for Bluetooth LE?


text:
Q: Select pixel position for image segmentation based on threshold value I am writing a function to segment an image in MATLAB. I want to do a simple segmentation where I first sum up elements along columns and select pixel position which is greater than threshold and display only those pixels from the original[![enter image description here] image. I have written a function below where it can sum pixel intensities, I need help in selecting pixel position where intensity is greater than threshold and display only that part of image.

 function S = image_segment(im)
% im is the image to segment

nrofsegments = 5; % there is 5 fragments for this image
S = cell(1,nrofsegments);
m = size(im,1);
n = size(im,2);
for kk = 1:nrofsegments
    S_sum=sum(im); %sum the intensity along column
    S_position = ... % get pixel position where the pixel intensity is greater than 128
    S{kk} = ... % im(S_position), only part of image with this pixel position

end

A: This code should work for your image. Please find the explanations inline.
% Read your test image from the web
im = imread('https://i.stack.imgur.com/qg5gx.jpg');

% Get sum of intensities along the columns
colSum = sum(im);

% Set a proper threshold (128 was not working for me)
thresh = 300;

% Get an 1-D logical array indicating which columns have letters
hasLetter = colSum > thresh;

% Get the difference of consecutive values in hasLetter
hasLetterDiff = diff( hasLetter ) ;

% If this is greater than 0, we have the start of a letter.
% The find gets the indices where this is true.
% Then, we add one to compensate for the offset introduced by diff.
letterStartPos = find( hasLetterDiff > 0  ) + 1;

% Use a similar approach to find the letter end position
% Here, we search for differences smaller than 0.
letterEndPos = find( hasLetterDiff < 0  ) + 1;

% Cut out image from start and end positions
numSegments = 5;
S = cell(1, numSegments );
for k = 1 : numel(S)
   S{k} = im( :, letterStartPos(k) : letterEndPos(k));
end

You should consider furthermore to add some code to make it fail-safe for cases where there are less than 5 segments. Moreover, I would recommend to do some low-pass or median filtering on colSum.
Alternative: Instead of deriving the start and stop positions, it would also be possible to use splitapply (introduced in R2015) directly on hasLetterDiff  as follows:
S = splitapply( @(X) { im(:,X) }, 1 : numel( hasLetter),  [1 cumsum( abs( hasLetterDiff))] + 1);
S = S(2:2:end);


text:
Q: perl regex for variable substitution I want to substitute variables marked by a "#" and terminated by a dot or a non-alphanumeric character.
Example: Variable #name should be substituted be "Peter"

abc#name.def => abcPeterdef
abc#namedef  => abc#namedef
abc#name-def => abcPeter-def

So if the variable is terminated with a dot, it is replaced and the dot removed. Is it terminated by any non-alphanum character, it is replaced also.
I use the following:
s/#name\./Peter/i
s/#name(\W)/Peter$1/i

This works but is it possible to merge it into one expression?

A: There are several possible approaches.
s/#name(\W)/"Peter" . ($1 eq "." ? "" : $1)/e

Here we use /e to turn the replacement part into an expression, so we can inspect $1 and choose the replacement string dynamically.
s/#name(?|\.()|([^.\w]))/Peter$1/

Here we use (?| ) to reset the numbering of capture groups between branches, so both \.() and ([^.\w]) set $1. If a . is matched, $1 becomes the empty string; otherwise it contains the matched character.

A: You may use
s/#name(?|\.()|(\W))/Peter$1/i

Details

*

*#name - matches the literal substring

*(?|\.()|(\W)) - a branch reset group matching either of the two alternatives:

*

*\.() - a dot and then captures an empty string into $1

*| - or

*(\W) - any non-word char captured into $1.

So, upon a match, $1 placeholder is either empty or contains any non-word char other than a dot.

A: You can do this by using either a literal dot or a word boundary for the terminator
Like this
s/#name(?:\.|\b)/Peter/i

Here's a complete program that reproduces the required output shown in your question
use strict;
use warnings 'all';

for my $s ( 'abc#name.def', 'abc#namedef', 'abc#name-def' ) {

    ( my $s2 = $s ) =~ s/#name(?:\.|\b)/Peter/i;

    printf "%-12s => %-s\n", $s, $s2;
}

output
abc#name.def => abcPeterdef
abc#namedef  => abc#namedef
abc#name-def => abcPeter-def


text:
Q: How to alert on 90% use of physical RAM I am trying to create an alert when 90% of RAM is used.
I have determined that Committed bytes is the amount of RAM in use but I don't know how to get total RAM.
I am NOT trying to find memory but a percentage of physical ram in use.
Perfmon stats have been indexed for me. I am new to SPLUNK

A: There is another peformance counter that is often also ingested with pefmon, PercentCommittedBytesInUse . I would suggest using that counter, if available.
Other Perfmon counters you can look for include "Available Mbytes"
Alternatively, you can get the total available memory using WinHostMon, Powershell or System Event logs


text:
Q: Assembling a variable from other variables based on a condition Brain totally not working today.
So, I have a few columns in a table that basically designate whether a certain piece of information WAS or WAS NOT provided by the user.
For example, I have a table with:
| ID | USER | crit1 | crit2 | crit3 | crit4 | etc. |

Now, the record could have a 1 or yes for any of the "critX" fields.  I dunno much about math and permutations, but I guess if there were 4 columns, you could have 16 combinations of output.  In my real world example I have 16 different criteria, so I can't factor for the output of that mess.  I need to write a routine of some sort.
In my example, each of those crit values is going to be evaluated and if the criterion == 1/yes, it will be included in another variable AND have a more human friendly bit of data assigned to it.  I am currently pulling each value from the DB an doing something like
### first I pull the values
$mydbarray[crit1] = $cr1;
$mydbarray[crit2] = $cr2;
$mydbarray[crit3] = $cr3;
(etc...)

### then I assign some human friendly text ONLY if the value == 1/yes
if($cr1==1) ($cr1 = "This info is present!";}
if($cr2==1) ($cr2 = "Number two is present!";}
if($cr3==1) ($cr3 = "Three was provided!";}

Now, what I need to do, is collect all that output only if the "IF" fired on true and assemble into a final variable.
So somehow, I want:
$finaloutput = $cr1, $cr2, $cr3;

Obviously that's not valid or what I want, but even if it DID work, it would end up including all the == 0/no instances as well.
So essentially I need a conditional grouping of these variables and I am not getting it.
I was thinking of casting an array and looping through it, but then I was at a loss for including the human intelligible portions...
Some guy at work mentioned an IF statement using bool, but I am not wellversed there.
I would think this is easy, but I've been up all week with the baby. so my brain is broken.
Thanks in advance!!!
Rob

A: First of all much of what you wrote is not valid PHP. I will assume you wrote it just to illustrate the point and didn't bother with the syntax.
Here is how to do it:
You take an array in which you will put your texts:
$texts = array();

For each of your criteria you check if they are provided, but add to the array created before:
if($cr1==1) {$texts[] = "This info is present!";}
if($cr2==1) {$texts[] = "Number two is present!";}
if($cr3==1) {$texts[] = "Three was provided!";}
...

In the end you concatenate all your texts with implode:
$finaloutput = implode(', ', $texts);

I prefer the method with implode to the one that just appends to a string because if I want a comma separator I don't get an extra one at the end.
Good luck, Alin

A: Try this:
$finaloutput = '';
if($cr1) $finaloutput .= "This info is present! ";
if($cr2) $finaloutput .= "Number two is present! ";
if($cr3) $finaloutput .= "Three was provided! ";
echo $finaloutput;

You dont need brackets in an if statement if there is only one item inside it. Im not sure if you want commas in the variable though...


text:
Q: Why do my kernel packages contain the name of a different ubuntu version? I run Ubuntu 14.04 (Trusty) on my desktop at work. I cannot upgrade because subsequent distributions of Ubuntu are incompatible with my lab's robot.
In the latest set of security updates, I noticed, confusingly, that certain packages contain the name "xenial", which is the name of Ubuntu 16.04.
The packages that confuse me are:

*

*linux-generic-lts-xenial

*linux-headers-generic-lts-xenial

*linux-image-generic-lts-xenial

After some investigation, I determined that these packages are already installed on my system.
$ dpkg -l | grep linux | grep xenial | cut -d ' ' --fields=3
linux-generic-lts-xenial
linux-headers-generic-lts-xenial
linux-image-generic-lts-xenial

Reading the description field of dpkg -l, I found the following descriptions:
linux-generic-lts-xenial           Complete Generic Linux kernel and headers
linux-headers-generic-lts-xenial   Generic Linux kernel headers
linux-image-generic-lts-xenial     Generic Linux kernel image

However, running lsb_release assures me that I am indeed running Ubuntu 14.04 (Trusty)
$ lsb_release -rcd
Description:    Ubuntu 14.04.5 LTS
Release:    14.04
Codename:   trusty

I have a couple questions that directly follow from these observations:

*

*Why do the kernel packages installed on my trusty desktop have "xenial" in their names? Does this mean that I'm running a kernel associated with xenial and not with trusty?

*What is the difference between running the xenial version of Ubuntu and having xenial kernel packages?
And a tangential question:

*The xenial packages made me worry that I would accidentally upgrade my version of Ubuntu. Will Ubuntu ever upgrade its version (e.g. through Software Updater's security updates) without having me explicitly confirm that the version is being upgraded?

A: *

*You have the xenial kernel (v4.4) because of an Ubuntu optional feature called Hardware Enablement Stack (also known as HWE or LTS enablement stack).
On Ubuntu 14.04 LTS, if you freshly installed with Ubuntu 14.04.2 or newer, you're automatically enrolled in HWE.  Ubuntu 14.04.1 or Ubuntu 14.04 by default remain on the trusty kernel (v3.13).
You can see the Ubuntu 14.04 kernel support schedule here (click image to expand):

*HWE just gives you the kernel and graphics support from the latest release of Ubuntu, up to the next LTS.  In your case, you'd have the xenial kernel and graphics packages, but everything else (should) still be built for trusty.

*Unlike Microsoft Windows, Ubuntu will not force you to upgrade your release.  Ubuntu would notify you of new releases that you can optionally choose to install on your own time, but you can disable the notifications if you want.
Note that Ubuntu releases do reach "end of life" on a schedule, which you can learn about more in detail here.


text:
Q: How to use *.jar file in a Java project? I'm a complete novice to Java, and I'm stuck in trying to use an external jar library in a Java project I'm working on.
The library is Twitter4J (http://twitter4j.org/), a complex group of files which I can't understand how to include. I'm using Eclipse on Windows. I understood the meaning of CLASSPATH enviroment variable (or well, I think I did), but I can't understand how to link it to the Eclipse enviroment.
This blog post seemed to be what I was looking for: http://jasperpeilee.wordpress.com/2012/01/25/how-to-set-up-twitter4j-quickly-in-your-java-project/
But:
Add twitter4j-core-2.2.5.jar into project for general use.

1) Where should I copy the core file? In the /bin/ folder? Or in a completly unrelated /lib/ folder, as this question in SO stated?
Copy Twitter API property file into your project/bin directory.

2) What is the Twitter API property file?
3) How can I include JavaDoc jar files too? Is it possibile to get them into Elipse?
Any kind of help, even just a link, will be very appreciated!

A: You probably have a project folder for your Eclipse project. Go ahead and make a lib folder inside of your project folder, in the same directory as src and bin. There's nothing special about the lib folder specifically, it's just a convenient name. Copy the .jar file into your newly created folder. Back in Eclipse, right click your project and click Refresh. The lib folder should pop up, including your JAR! Right click the JAR file and go to Build Path --> Add To Build Path. At this point, any class in the project should be able to use Twitter4J features.

A: As for the What question, the Twitter API property file contains configuration that is necessary for the Twitter jar to function. The file should probably be located on the classpath of your application.
And the How question, you can attach the javadoc jar file of the Twitter jar to the Twitter jar's classpath entry in Eclipse. Right-click your project and select Properties. Go to the Java Build Path entry and find the Twitter jar under the Libraries tab. If you expand the Twitter jar entry you will see 'JavaDoc location'. You can specify the javadoc jar there.

A: In Eclipse, right-click your project, select Properties. Now find the entry for Java Build Path and select it. Click the "Libraries" tab if it is not already selected. Click the "Add external JARs..." button. Follow the prompts.


text:
Q: How to fix : instantiating error in Hibernate validator cdi When using Hibernate validation in Spring MVC, I have an instantiating error in Hibernate validator CDI like shown in the attached image. (I'm using Glassfish Server).
here are my CostumerConstoller and CostumerForm.
#CostumerController.java

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

@Controller
@RequestMapping("/customer")

public class customerController  {

  @RequestMapping("/showCustomerForm")
  public String showStudentForm(Model theModel){

      customer customer = new customer();

      // add customer object to the model
      theModel.addAttribute(customer);

      return "customerForm";
  }

  @RequestMapping("/processCustomerForm")
  public String processCustomerForm( @Valid @ModelAttribute("customer") customer theCustomer, BindingResult theBindingResult ){

      if(theBindingResult.hasErrors()){
          return "customerForm";
      }
      else return "welcomeCustomer";
  }

}

#CostumerForm.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

    <title>Form</title>

<form:form action="processCustomerForm" modelAttribute="customer">

    Last Name (*) :

    <form:input path="lastName" id="LastName"/>
    <form:errors path="lastName" cssClass="error"/>

    First Name :

    <form:input path="firstName" id="FirstName"/>

    <form:button value="Submit" type="submit"> Submit </form:button>

</form:form>

I have tried using many versions of JARs but nothing work.
Glassfish Log snapshot


text:
Q: Laravel Queue Job doesn't respect timeout I have this process setting.
php artisan queue:work beanstalkd --sleep=3 --tries=1 --timeout=0 --queue=medium,messages

I also have a job with the setting
public $timeout = 100000000;

But the job is stopped much before that with message has been attempted too many times or run too long. The job may have previously timed out Which was run for the first time.
I also have this in php.ini
max_execution_time = 0

What am I missing here?

A: Console
Things I want to execute from the command line (As you mentioned with your job creates more jobs). But the thing is, you could extract the business logic of it to a command.
Example: A console command with fires a command to fetch images from Imgur. The Class FetchImages  contains the actual business logic of fetching images.
Command
Class which contains the actual logic. You should also be able to call this command from your application with app()->make(Command::class)->handle().
Example: Command mentioned in Example 1. Contains logic which does the actual API calls to Imgur and process returned data.
Jobs
Laravel 5.0 so jobs weren't a thing back then. But as I see it, Jobs are like commands but they are queued and can be dispatched. (As you may have seen in those examples, those commands implement your mentioned Interfaces SelfHandling and ShouldBeQueued).

I see changes in Commands and Jobs are quite difficult to understand.
EDIT:
From the Laravel Docs:

The app/Commands directory has been renamed to app/Jobs. However, you are not required to move all of your commands to the new location, and you may continue using the make:command and handler:command Artisan commands to generate your classes.
Likewise, the app/Handlers directory has been renamed to app/Listeners and now only contains event listeners. However, you are not required to move or rename your existing command and event handlers, and you may continue to use the handler:event command to generate event handlers.
By providing backwards compatibility for the Laravel 5.0 folder structure, you may upgrade your applications to Laravel 5.1 and slowly upgrade your events and commands to their new locations when it is convenient for you or your team.


text:
Q: What happens if you push and pull 5 balls simultaneously connected by springs at opposite ends? Say you have 5 balls connected by Steel springs in space .
Each ball is 1 KG
Distance between each ball is 1 Meter.
Total Object is 5 Meters
1--2--3--4--5
say you push 1 and pull 5 simultaneously with 100 Newtons
Push 100N ~> 1~-2--3--4-~5~> 100N Pull
What happens to ball 3 when the energy/longitude waves meets ?
Does the ball move towards 5?
IF it move towards 5 what would the exact force in that moment of time be?
or does it not move?
IF it does not move then what happens to the momentum?
How would you go about solving this, Specifically what formulas/equations would I need?
I've started with Hookes Law but am confused on determine a spring constant in this situation as its in space with no gravity.
My goal is to mimic something actually calculatable in terms of the restoring force in material due to electromagnetic forces.
To ask my question elegantly what happens at the exact moment when the two longitude waves meet at Ball 3?

A: You would set up Newton's Second Law for each of the five masses.  If the initial positions of each of the five masses are $x_i = 0$, and the springs are initially at their equilibrium lengths, then the force exerted by each spring will be of magnitude $k(x_i - x_{i+1})$.
Newton's Second law for each of the masses would be
\begin{align*}
m \ddot{x}_1 &= F_\text{app} - k (x_1 - x_2) \\
m \ddot{x}_2 &= -k(x_2 - x_1) - k (x_2 - x_3) \\
& \vdots \\
m \ddot{x}_5 &= F_\text{app} - k(x_5 - x_4) \\
\end{align*}
You would then need to solve these differential equations given the initial conditions $x_i(0) = \dot{x}_i(0) = 0$.  While it is possible to do this by hand, use of a computer (either to solve the problem numerically or exactly) would be a great help.  Once you have this solution, you can figure out the position, velocity, and acceleration of any mass at any particular time.


text:
Q: How Do You Pass VGA/VESA Modes with GRUB2? One of my machines has a 3 TB HD setup to triple boot into Mint 14 (Ubuntu 12.10 variant), Slackware 14.1 and Arch Linux. The HD is formatted using the GPT/Guid system. The Grub2 technically "belongs" to the Linux Mint install but is used to triple boot all 3 systems. Setting it up about 1 year ago was an extremely painful procedure and required 2-3 days of wrestling with it, and tweaking it, to allow it to recognize the Slackware and Arch installs; it always recognized the Mint Linux install easily.
I need to be able to pass VGA/VESA modes to Slackware and Arch. I use Slackware and Arch from the command line and therefore console resolution and font size are important factors.

A: In GRUB2 the preferred method of setting framebuffer resolution (to GRUB and the kernel) is to edit /etc/default/grub to contain these variables:

*

*GRUB_GFXMODE sets the resolution of GRUB

*GRUB_GFXPAYLOAD_LINUX controls whether the linux kernel will keep the resolution, and if you want the linux kernel to use different resolution than GRUB, you can set it with this variable in form widthxheight.

To show all modes you can use:

*

*hwinfo --framebuffer in linux terminal

*vbeinfo in GRUB prompt

Sample configuration of framebuffer resolution
These lines are inserted to /etc/default/grub:
GRUB_GFXMODE=1024x768x32
GRUB_GFXPAYLOAD_LINUX=keep

In order to generate the changes, run
# grub-mkconfig -o /boot/grub/grub.cfg

Excerpt from GNU GRUB Manual 2.00

'GRUB_GFXMODE'
Set the resolution used on the 'gfxterm' graphical terminal. Note that you can only use modes which your graphics card supports via VESA BIOS Extensions (VBE), so for example native LCD panel resolutions may not be available. The default is 'auto', which tries to select a preferred resolution. See gfxmode.
'GRUB_GFXPAYLOAD_LINUX'
Set to 'text' to force the Linux kernel to boot in normal text mode, 'keep' to preserve the graphics mode set using 'GRUB_GFXMODE', 'widthxheight'['xdepth'] to set a particular graphics mode, or a sequence of these separated by commas or semicolons to try several modes in sequence. See gfxpayload.
Depending on your kernel, your distribution, your graphics card, and the phase of the moon, note that using this option may cause GNU/Linux to suffer from various display problems, particularly during the early part of the boot sequence. If you have problems, set this option to 'text' and GRUB will tell Linux to boot in normal text mode.

References

*

*ArchWiki's page about GRUB.

*GNU GRUB Manual 2.00.

A: In legacy grub, we used to pass VGA/VESA mode in kernel line as VGA=1024x768
In grub2, same can be achieved by line gfxpayload=1024x768
Follow more info here


text:
Q: GitHub Dependabot Doesn't Have Permissions To Publish to GHCR How Can I Give It Access I have a repository that builds, tags, and publishes container images to GitHub's ghcr.io, however it fails to publish on dependabot actions and breaks all of my pipelines that are doing the build, tag, and release of each container image. Here is the dependabot code I originally had:
version: 2
updates:
- package-ecosystem: github-actions
  directory: "/"
  schedule:
    interval: monthly
    time: "13:00"

Now I read the following documentation on how to give it access to a registry:

*

*Configuring Dependabot - Registries
And I thought I would try this:
version: 2
registries:
  ghcr: # Define access for a private registry
    type: docker-registry
    url: ghcr.io
    username: ${{ github.repository_owner }}
    password: ${{secrets.GHCR_REGISTRY_TOKEN}}
updates:
- package-ecosystem: github-actions
  directory: "/"
  registries:
    - ghcr
  schedule:
    interval: monthly
    time: "13:00"

Unfortunately, it still doesn't like it and subsequently breaks all of my pipelines.
How do I configure Dependabot to be able to push to ghcr.io for all of my container packges?

A: Dependabot secrets are stored separately on the secret section of the repo, please follow this doc to configure it


text:
Q: TestCafe Authentication results in a 401 - Unauthorized: Access is denied.... error Issue:
I am trying to get TestCafe to open an internal website that triggers a windows authentication pop up on opening, but the TestCafe built in Authentication feature doesn't work for some weird reason and the website complains with "401 - Unauthorized: Access is denied due to invalid credentials."
Note manually I can open the website with the same login credentials.
Also note the Authentication feature does work for other websites, and I am doing this at work, so there is a work proxy.
The site that TestCafe is failing to open up:
Is made up of a server name & port only & lives internally eg.
http://[ServerName]:[Port]
The Code:
Made up of 2 files....
The Test Script:
import {Selector} from 'testcafe';

fixture('My Test')
    .page('http://[ServerIP]:[Port]/')  // Also tried ('http://[ServerName]:[Port]')
    .httpAuth({
        username: 'domain\name',
        password: 'password_here'

    })

test ('Opening this internal site', async t => {

    await t

    .debug()

});

The Runner file:
const createTestCafe = require('testcafe');
let testcafe           = null;

createTestCafe('localhost', '8081')
    .then(tc => {
        testcafe = tc;
        const runner = testcafe.createRunner();

        return runner
            .src([
                'My_Test.js'
             ])
            .browsers('chrome')
            .useProxy('webproxy01:8080', '[ServerIP]:[Port]') // I tried including the website that I want to test incase it needs to be ByPassed
            .run({
                skipJsErrors: true,
                concurrency: 1
            })
    })
    .then(failedCount => {
        console.log(`Tests failed: ` + failedCount);
        testcafe.close();
    });

Just to add I've tried this too and it doesn't work either:
.httpAuth({
        username: 'name',
        password: 'password_here',
        domain: 'domain_here',
        workstation: 'computer_name'
    })

Many thanks!


text:
Q: Merge 2 columns on separate sheets into one column I have 2 lists on two separate sheets and I am trying to combine them into a third sheet. These lists auto-populate based on user input, so the number of rows within the list can vary. So once it detects nothing in the first column of sheet one, it starts populating the list on sheet 3 with the columns in sheet 2, like this
Sheet 1
Make    Model     License Plate
Ford    Escape    UVC345
Honda   Civic     KD2YR9

Sheet 2
Make    Model    License Plate
Dodge   Charger  34TRLS2
VW      Passat   V70YTR

Sheet 3
Make    Model    License Plate
Ford    Escape   UVC345
Honda   Civic    KD2YR9
Dodge   Charger  34TRLS2
VW      Passat   V70YTR

Update:
The problem I'm running into when I use VBA to copy and paste, is that it is pasting and identifying the formulas that are used to autopopulate the initial list on sheet 1. Because it is pasting the formulas, it is not correctly identifying where the last cell is on sheet 3.
Sub Copy_Alternatives()

Worksheets("CNA eTool Alternatives").Range("A:A").Copy
Worksheets("Repair Replacement Recom").Range("A:A").PasteSpecial xlPasteValues
Worksheets("CNA eTool Alternatives").Range("B:B").Copy
Worksheets("Repair Replacement Recom").Range("B:B").PasteSpecial xlPasteValues
Worksheets("CNA eTool Alternatives").Range("C:C").Copy
Worksheets("Repair Replacement Recom").Range("C:C").PasteSpecial xlPasteValues

End Sub

Sub Copy_Paste_Range()

Dim lNewRow As Long
Dim lDataRow As Long

ThisWorkbook.Activate

lNewRow = Worksheets("CNA eTool Addit. Alternatives").Cells(Worksheets("CNA eTool Addit. Alternatives").Rows.Count, "H").End(xlUp).Row

lDataRow = Worksheets("Repair Replacement Recom").Cells(Worksheets("Repair Replacement Recom").Rows.Count, 1).End(xlUp).Row
lDataRow = lDataRow + 1

Worksheets("CNA eTool Addit. Alternatives").Range("H2:J" & lNewRow).Copy
Worksheets("Repair Replacement Recom").Range("A" & lDataRow).PasteSpecial

End Sub

A: You can make it with worksheet functions.
Lets say your first Sheet is Sheet1 and the second is Extra1
Put the following formula on your merged sheet on A2, then copy paste to the other cells:
=IF(ROW()>COUNTA(Sheet1!A:A)+COUNTA(Extra1!A:A)-1,"",INDIRECT(IF(ROW()<=COUNTA(Sheet1!A:A),"Sheet1!","Extra1!")&SUBSTITUTE(ADDRESS(1,COLUMN(),4),1,"")&ROW()-IF(ROW()<=COUNTA(Sheet1!A:A),0,COUNTA(Sheet1!A:A)-1)))
How this works:

*

*Checks if the current line is higher than the number of lines on the first sheet + the second sheet minus one(Because both have headers);

*If the current line is greater, show empty. Else, goes to next step;

*Prepares an INDIRECT. If the current line is lower than the lines on the first sheet, gets the first sheet name. Otherwise it gets the second sheet name;

*It uses the SUBSTITUTE + ADDRESS trick to return the current letter of the column. It is good because then it uses the same formula on all fields, and accepts even when the column becomes AA

*Finally, it gets the current line if the current line is lower than the number of items on the first sheet, otherwise it gets the current line MINUS the count of lines of the first sheet, minus one, to return the starting line of sheet two.

I know it is kinda overwhelming and harder to read, but formulas sometimes are better than VBA.
Edit: Welp, I got an epiphany and got a working VBA version
Sub merge()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Set ws1 = Sheets("Sheet1") 'First sheet to get merged
Set ws2 = Sheets("Extra1") 'Second sheet to get merged
Set ws3 = Sheets("Merged") 'Name of the sheet you want results
Dim lr As Long 'To return the number of the last row
Dim arrayone As Variant
lr = ws1.Cells(Rows.Count, 1).End(xlUp).Row
arrayone = Range(ws1.Cells(2, 1), ws1.Cells(lr, 3)).Value 'From Row 2 onwards, considering it has headers
Dim arr2 As Variant
lr = ws2.Cells(Rows.Count, 1).End(xlUp).Row
arr2 = Range(ws2.Cells(2, 1), ws2.Cells(lr, 3)).Value 'From Row 2 onwards, considering it has headers
Dim arr3 As Variant
ReDim arr3(1 To UBound(arrayone, 1) + UBound(arr2, 1), 1 To 3)
For i = 1 To UBound(arr3, 1)
    For j = 1 To 3
        If i <= UBound(arrayone, 1) Then
            arr3(i, j) = arrayone(i, j)
        Else
            arr3(i, j) = arr2(i - UBound(arrayone, 1), j)
        End If
    Next j
Next i
Range(ws3.Cells(2, 1), ws3.Cells(UBound(arr3) + 1, 3)).Value = arr3
End Sub


text:
Q: Trying to send POST Request in Angular on NavigationEnd/ngOnDestroy I'm trying to send a list of data objects to a database to save when I leave the navigation. I've tried putting it in ngOnDestroy(), but it seemed like half the times the request made it through to the database before the reference to the list is destroyed, and half the times it sent a null value. This is what I've been trying.
this._routerSub = this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
      console.log("We have just triggered NavigationEnd! We are now calling .SaveNewJiras()");
      this.sprintListService.SaveNewJiras(this.NewIssues, this.sprintNum).subscribe((result) => {
        this.NewIssues = [];
      }, error => console.log('CALL TO SAVENEWJIRAS() DID NOT WORK!'));
    }
  });

and with this in the ngOnDestroy() method.
this._routerSub.unsubscribe();

What I was encountering was that if I didn't call .unsubscribe(), then it would successfully write to the database. However, navigating back and forth between other pages and that pages would "stack up" NavigationEnd events (which became  a problem because of writing records with primary keys). When I did call .unsubscribe(), it would unsubscribe() the event and the data would never get written to the database. Does anybody have any ideas on how to solve this problem? Thank you so much!


text:
Q: Use IN clause in python django and cursor execute I have a list named "critical_severity_list" as below:[30, 40]
I want to execute a select with IN clause as below:
cursor = connection.cursor()

que = 'select * from tm_txn_age_severity_config where txn_state_id = %s and txn_type_id = %s and txn_age_severity_id in ( %s)'

in_ids = ', '.join(map(lambda x: '%s', critical_severity_list))

que = que % ('%s', in_ids)

bind_var_list = []

bind_var_list.append(rec[1])

bind_var_list.append(rec[2])

bind_var_list.extend(critical_severity_list)

cursor.execute(que, bind_var_list)

result = cursor.fetchall()

I am getting this error:
not enough arguments for format string
Can someone help me with the solution....??

A: The error occurs here:
que = 'select * from tm_txn_age_severity_config where txn_state_id = %s and txn_type_id = %s and txn_age_severity_id in ( %s)'
in_ids = ', '.join(map(lambda x: '%s', critical_severity_list))
que = que % ('%s', in_ids)

You're formatting que using several arguments but you're not providing enough arguments. In que there are three occurrences of %s but you're only providing two arguments when you use the % operator to format the string.
For example:
>>> "%s %s" % "a"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

(one argument is provided, two are expected)

A: I hope this is what you want:
critical_severity_list=[30,40]
temp=['%s']+critical_severity_list
que = 'select * from tm_txn_age_severity_config where txn_state_id = %s and txn_type_id = %s and txn_age_severity_id in ( %s)'
que = que % tuple(i for i in temp)
print(que)

output:
select * from tm_txn_age_severity_config where txn_state_id = %s and txn_type_id = 30 and txn_age_severity_id in ( 40)


text:
Q: Can numpy strides stride only within subarrays? I have a really big numpy array(145000 rows * 550 cols). And I wanted to create rolling slices within subarrays. I tried to implement it with a function. The function lagged_vals behaves as expected but np.lib.stride_tricks does not behave the way I want it to -
def lagged_vals(series,l):
# Garbage implementation but still right
    return np.concatenate([[x[i:i+l] for i in range(x.shape[0]) if i+l <= x.shape[0]] for x in series]
                          ,axis = 0)

# Sample 2D numpy array
something = np.array([[1,2,2,3],[2,2,3,3]])
lagged_vals(something,2) # Works as expected

# array([[1, 2],
#     [2, 2],
#     [2, 3],
#     [2, 2],
#     [2, 3],
#     [3, 3]])

np.lib.stride_tricks.as_strided(something,
                               (something.shape[0]*something.shape[1],2),
                               (8,8))

# array([[1, 2],
#        [2, 2],
#        [2, 3],
#        [3, 2], <--- across subarray stride, which I do not want
#        [2, 2],
#        [2, 3],
#        [3, 3])

How do I remove that particular row in the np.lib.stride_tricks implementation? And how can I scale this cross array stride removal for a big numpy array ?

A: Sure, that's possible with np.lib.stride_tricks.as_strided. Here's one way -
from numpy.lib.stride_tricks import as_strided

L = 2 # window length
shp = a.shape
strd = a.strides

out_shp = shp[0],shp[1]-L+1,L
out_strd = strd + (strd[1],)

out = as_strided(a, out_shp, out_strd).reshape(-1,L)

Sample input, output -
In [177]: a
Out[177]:
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])

In [178]: out
Out[178]:
array([[0, 1],
       [1, 2],
       [2, 3],
       [4, 5],
       [5, 6],
       [6, 7]])

Note that the last step of reshaping forces it to make a copy there. But that's can't be avoided if we need the final output to be a 2D. If we are okay with a 3D output, skip that reshape and thus achieve a view, as shown with the sample case -
In [181]: np.shares_memory(a, out)
Out[181]: False

In [182]: as_strided(a, out_shp, out_strd)
Out[182]:
array([[[0, 1],
        [1, 2],
        [2, 3]],

       [[4, 5],
        [5, 6],
        [6, 7]]])

In [183]: np.shares_memory(a, as_strided(a, out_shp, out_strd) )
Out[183]: True


text:
Q: how to create a unique constraint I have a programming situation in which I have to check the uniqueness of a column of the table.
Say My table is employee table and I have added a column that is code. Now I have to prevent the insertion of MGR and mgr.
So that means I can not have 2 rows having case insensitive values.
How to add the check constraints ?

A: If you are using Oracle, you may add a unique index on the lowercase of your column.
create unique index <index_name> on <tablename>(lower(<column_name>))


text:
Q: C# length 1 array versus single value, performance and memory overhead Question:
What is the performance and memory overhead of using an array with the length of 1 instead of the value directly?
private Item[] item = new Item[1];
   vs.
private Item item;

Usage:
I have an abstract base class ItemHolder which is beeing inherited both by the SingleItemHolder and MultipleItemHolder classes. The first holding a single item as the main value while the other holds a list. To access the value I see three possibilities:
Adding two methods to the base class
public abstract Item GetItem();
public abstract Item[] GetItems(int amount);

drawback beeing the SingleItemHolder has the unnecessary method to get multiple items while having only one per definition.
Another method would be to only implement the second method and passing the single value as a length 1 array
public override Item[] GetItems()
{
    return new[] { storedItem };
}

or storing the single value as a length 1 array in the first place
private Item[] item = new Item[1];
public override Item[] GetItems()
{
    return item;
}

Both the multiple as well as the single item holders are used equally as often and quite often in general. The methods in question could very well be called dozends of times per game frame from all over the gameworld. Therefor I am wondering which version the most efficient would be, or, to be more general, what difference in overhead a length 1 array has over a single value.

A: Just a short note. In the .NET world the big performance issue is the GC that may easily lock the app for 50-100ms. You will likely not see a big difference in reading data from an object or single value array. But you will likely get a penalty if you need to create such object a lot. You certainty should avoid creating objects from the getters code.
I think that this article may be helpful: https://michaelscodingspot.com/avoid-gc-pressure/. Also consider usage of some Profile tool to check how much time it actually takes. I prefer using the PerfView provided by MS. It may take some time to start using it, but you certainly get benefits in results.

A:
What is the performance and memory overhead of using an array with the length of 1 instead of the value directly?

That depends entirely on how compiler Optimisations, JiT compiler and Index accessor pruning feel about that array today. At it's core, everything is a pointer. The process does not care if it points to a function, a single int or the beginning of a int array. Aside from the jump into the Indexer function and maybe the Indexer sanity checks, there should be no performance impact. And even that one Indexer access could pruned, or at least inlined.
It is theoretically possible that the optimsations see your new int[1] and decide a basic int would do there. The JiT could even do that if the size is only defined at runtime. However, this is rather unlikely.
If you need a array there, you need a array there. The odd case that it is sometimes 1, is nothing to worry about. Even if the size 1 array is somehow common, having a path with a basic int would be a micro-optimisation. It would just fall under the speed rant: https://ericlippert.com/2012/12/17/performance-rant/
If you have two function overloads - one taking a int and one taking a int[] - you should propably only code out the int[] version. It is pretty trivial to chain the int version to call the array version.


text:
Q: Where to store a Doctrine variable created in a component so that it's accessible anywhere? Note I am referring to one request, and not several requests and sessions.
I have several components that require Doctrine user object, some are located in layout, others are located in templates. Sometimes I need that Doctrine user object in action. Currently I have added a function to sfUser class that loads that object from database, which means every time I call that function I make a call to db. I'd like to know where to store this object so that I can access it without having to query db every time I need it. Again, we're talking about a single request, not several requests or something that would require session.
Can I save it in sfContext somehow? Any other places so that it can be available everywhere?

A: You can store it in your model's Table class, because tables are always accessed as singletones.
class sfGuardUserTable extends PluginsfGuardUserTable
{
  protected $specialUser = null;

  public function getSpecialUser()
  {
    if (null === $this->specialUser)
    {
      $this->specialUser = $this->findOneById(1);
    }
    return $this->specialUser;
  }
}

Now, you can use this in actions and components like this:
$u = sfGuardUserTable::getInstance()->getSpecialUser();

And you will always end up with one query.

A: you can configure Doctrine cache so that the result of this specific request is always cached. What if so good about it is that if you use, say, the APC backend, you will have it cached across requests. You also get query caching as a bonus (this is not result caching, read the link I provided carefully)!


text:
Q: Compute Mixed Volume with Respect to Some Regular Sets Let $( \mathbb{R}^n, \mathcal{B}, \gamma)$ be a measure space where $\mathcal{B}$ is the Borel sigma algebra and $\gamma$ is a continuous measure. For $A, B\in \mathcal{B}$ that are convex, the mixed volume of $A$ and $B$ are defined by
\begin{align}
MV(A,B) = \lim_{\epsilon \rightarrow 0+} \frac{ \gamma( A \oplus \epsilon \cdot B) - \gamma(A) }{\epsilon},
\end{align}
where $\oplus$ denotes Minkovski addition of two sets.
It is known that if $B= \mathbb{B}_2^n$, which is the Euclidean $\ell_2$-ball in $\mathbb{R}^n$, we have
\begin{align}
MV(A, \mathbb{B}_2^n) = \int_{  \partial A} \mathrm{d} \sigma_{\gamma},
\end{align}
where $\partial A$ is the surface of $A$ and $\mathrm{d} \sigma_{\gamma}$ is the surface measure induced by $\gamma$.
I wonder how to compute the mixed volume with respect to $\ell_p$ balls $MV(A, \mathbb{B}_{p}^n) $ in general. Here $p \in [1, \infty]$.
This problem is connected to the anti-concentration problems in probability. In http://arxiv.org/abs/1301.4807 it is shown that for $A $ to be the intersection of linear hyperplanes,
we have $MV(A, \mathbb{B}_{\infty}^n) = MV(A, \mathbb{B}_2^n)$. But their derivation is not geometric and may not be able to extend to the general case.


text:
Q: Parse wordpress blog data using json api and ajax I have seen lots of responses to how to extract data from wordpress blog posts using the json api plugin. Many uses $.getJSON, $.ajax, .responseData.feed.entries, success function() etc.
What is the correct way to parse JSON API datas from wordpress, post the result to a content div page in a jQuery mobile listview.
I have the following codes but unable to get the intended result:
HTML
<!DOCTYPE html>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />

Sysads Posts

Home

Disclaimer

.js:
$( document).ready(function (){
    url = 'http://hopexxx.com/category/daily-devotion/feed/' ;
    $.ajax({
        type: "GET",
        url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
        dataType: 'json',
        error: function(){
            alert( 'Unable to load feed, Incorrect path or invalid feed' );
        },
        success: function(data ){
            var postlist = data.responseData.feed.entries;
            var html = '
' ;
            for (var i = 0 ; i < 10 ; i++) {
                var entry = postlist[i];
                html += '
';
                html += '';
                html += '
' + entry.title + '
' ;
                html += '
' + entry.author + '
' ;
                html += '
' + entry.publishedDate + '
';
                html += '
' + entry.contentSnippet + '
';
                html += '';
                html += '
';
            }
            html += '
';
            $( "#postlist" ).append(html);
           $( "#postlist ul[data-role=listview]" ).listview();

        }});
    });

I hope my question is not outside the site rule.

A: Got this working: Added html += '';
html += '
';
html += '';
html += '
' + entry.title + '
' ;
html += '
' + entry.author + '
' ;
html += '
' + entry.publishedDate + '
';
html += '
' + entry.contentSnippet + '
';
html += '';
html += '
';


text:
Q: How to get object reference dynamically by name? I am newbie in C# and I have a question.
I have that objects:
PictureBox field1;
PictureBox field2;
PictureBox field3;

And the question:
Is this possible to get that objects "dynamically" using its names?
I mean something like that:
for(int i = 0; i < 3; i++) {
     // instead of that:
     string tmp1 = field1.Name;
     string tmp2 = field2.Name;
     string tmp3 = field3.Name;

     // i need something like that:
     string tmp = "and this is a string parameter".Name;
}


text:
Q: Why does exec 2>file.txt redirect the standard input? I am trying to understand exec, which is used for redirection of stdio as far as I understood. Now, if I enter:
exec 2>file.txt

My shell changes to only showing a text cursor icon. Now everything I type is redirected to file.txt, including the "user@computer:directory$" part of the shell. This is confusing to me, since I thought that 2> redirects only the stderr (while >, or 1> redirects the stdout). So why does exec 2> redirect everything?


text:
Q: using `when` and `in` inside of IF clause Would using a when and in clause work when using IF clauses?
E.g
IF (when regexp_replace(lower(value), '\s+$', '') in (
     'some string',
     'another string'
 )) then

   // do stuff

A: No, and you don't need to combine different conditionals in the same statement. Stick to one of them, e.g. IF. You can test it yourself using an anonymous code block:
DO $$
DECLARE value text := 'another string';
BEGIN
 IF (regexp_replace(lower(value), '\s+$', '') IN
    ('some string','another string')) THEN
    -- do something
  END IF;
END;
$$


text:
Q: why 'grails war' generate different war file every time Today I found a phenomenon which made me confused.Grails is new to me.My evn just like:
| Grails Version: 3.3.0
| Groovy Version: 2.4.11
| JVM Version: 1.8.0_144

When finished coding,I executed grails command "run"and got a war package.I unzipped it and got a lot of .class files. Subsequently I executed grails command "clean" and "war", then I got another war package. I unzipped it too. I found the 2 batches of domain .class files are different from each other. I compared two domain .class files(each unzipped from one war) in intelij. Their methods' orders are different.Just like this:
.class file compare picture
You might ask why I unzipped the war package? I do this just because I don't want to deploy files that have not changed in order to save internet traffice(which of course costs).I want to send only the changed files to our server, expecting svn would ignore the .class files that have not changed.
I found the content of domain class is not changed, but the order of functions changed.Does anyone know why?Thank you.


text:
Q: Programmatically determine using the UTC time at what offset a day/time is I have a cron job that fires hourly.  In my database I have rows that contain UTC offsets.  I'm trying to do the following programmatically.
function returnThisHourOffset($timeofday){
    //using the current UTC hour gmdate('G'), determine at what offset from the UTC the $timeofday currently exists (**and which day**).
}

I've written out what happens at each UTC for midnight and 5AM.
    UTC 23:00:00, At offset +1 is 12AM the next UTC day. At offset +6 is 5AM, the next UTC day
    UTC 22:00:00, At offset +2 is 12AM the next UTC day. At offset +7 is 5AM, the next UTC day
    UTC 21:00:00, At offset +3 is 12AM the next UTC day. At offset +8 is 5AM, the next UTC day
    UTC 20:00:00, At offset +4 is 12AM the next UTC day. At offset +9 is 5AM, the next UTC day
    UTC 19:00:00, At offset +5 is 12AM the next UTC day. At offset +10 is 5AM, the next UTC day
    UTC 18:00:00, At offset +6 is 12AM the next UTC day. At offset +11 is 5AM, the next UTC day
    UTC 17:00:00, At offset +7 is 12AM the next UTC day. At offset +12 is 5AM, the next UTC day
    UTC 16:00:00, At offset +8 is 12AM the next UTC day. At offset -11 is 5AM, this UTC day
    UTC 15:00:00, At offset +9 is 12AM the next UTC day. At offset -10 is 5AM, this UTC day
    UTC 14:00:00, At offset +10 is 12AM the next UTC day. At offset -9 is 5AM, this UTC day
    UTC 13:00:00, At offset +11 is 12AM the next UTC day. At offset -8 is 5AM, this UTC day
    UTC 12:00:00, At offset +12 is 12AM the next UTC day. At offset -7 is 5AM, this UTC day
    UTC 11:00:00, At offset -11 is 12AM on the UTC day. At offset -6 is 5AM, this UTC day
    UTC 10:00:00, At offset -10 is 12AM on the UTC day. At offset -5 is 5AM, this UTC day
    UTC 09:00:00, At offset -9 is 12AM on the UTC day. At offset -4 is 5AM, this UTC day
    UTC 08:00:00, At offset -8 is 12AM on the UTC day. At offset -3 is 5AM, this UTC day
    UTC 07:00:00, At offset -7 is 12AM on the UTC day. At offset -2 is 5AM, this UTC day
    UTC 06:00:00, At offset -6 is 12AM on the UTC day. At offset -1 is 5AM, this UTC day
    UTC 05:00:00, At offset -5 is 12AM on the UTC day. At offset 0 is 5AM, this UTC day
    UTC 04:00:00, At offset -4 is 12AM on the UTC day. At offset +1 is 5AM, this UTC day
    UTC 03:00:00, At offset -3 is 12AM on the UTC day. At offset +2 is 5AM, this UTC day
    UTC 02:00:00, At offset -2 is 12AM on the UTC day. At offset +3 is 5AM, this UTC day
    UTC 01:00:00, At offset -1 is 12AM on the UTC day. At offset +4 is 5AM, this UTC day
    UTC 00:00:00, At offset 0 is 12AM on the UTC day. At offset +5 is 5AM, this UTC day

So, for example returnThisHourOffset(5)  at UTC 8AM should return -3 with today's UTC date.  While returnThisHourOffset(5) at UTC 9PM (21:00:00) should return 8 with tomorrow's UTC date (since it's 9AM today and 8 hours later it's 5AM tomorrow).
Obviously, I'm not playing much with daylight savings or offsets > 12.  Just trying to keep it simple and it's still looking very complex.
This is my code which is strictly for getting the offset where midnight occurs or what could be returnThisHourOffset(0)  I'm looking for any time of day (0-23).
if(gmdate('A') == 'PM'){
        $offset = (24 - gmdate('G'));
        $today = gmdate("Y-m-d\T00\:00\:00", strtotime('tomorrow UTC'));
    } else {
        $offset = -1*(gmdate('G'));
        $today = gmdate("Y-m-d\T00\:00\:00", strtotime('today UTC'));
    }

I'm confident my code isn't the answer to this so I'm hoping someone else has tried to tackle this before in some fashion.  Any insight is appreciated.

A: This looks like it works but I'm open to better suggestions (since it's obviously very messy).
$utcHour = gmdate('G');
$timeofday = 5; // (0-23)

if($utcHour <= $timeofday){
    $offset = $timeofday - $utcHour;
    $today = gmdate("Y-m-d\T00\:00\:00", strtotime('today UTC'));
} elseif ($utcHour > $timeofday && $utcHour - $timeofday < 12){
    $offset = -1*($utcHour - $timeofday);
    $today = gmdate("Y-m-d\T00\:00\:00", strtotime('today UTC'));
} else {
    $offset = (24 - $utcHour) + $timeofday;
    $today = gmdate("Y-m-d\T00\:00\:00", strtotime('tomorrow UTC'));
}