text:
Q: General tips for showing that subspaces "vary continuously" Here is (part of) a problem from Spivak's Differential Geometry Vol. 1.

6. For a bundle map $(\tilde f,f),$ with $f:B_1\to B_2,$ let $K_p$ be the kernal of the map $\tilde f|_{\pi_1^{-1}(p)}$ from $\pi_1^{-1}(p)$ to $\pi_1^{-1}(f(p))$.
a.) If $p\mapsto \dim K_p$ is continuous, then $\ker\tilde f,$ the union of all the $K_p,$ is a bundle over $B_1.$

The solution to this problem, along with the part after it, seems to rely on the fact that the subspaces $K_p$ "vary continuously" with the variable $p.$ I'm not exactly sure how one would even go about showing this, or if that's what I should be trying to do at all (perhaps that will be an artifact of a correct solution). It seems like what I want should follow from the continuity of $f,$ but I am still unsure how to proceed.
So, my questions are how does one go about showing that the spaces $K_p$ vary in a nice way? Is there a general strategy for showing this type of thing, or do solutions vary?

A: As explained in Hunter's comments and answer, since being a bundle is a local property, it suffices to prove the following.
Claim: Let $U\subset\mathbb{R}^n$ be open and connected, and let $f:U\to M_{q\times p}(\mathbb{R})$ be continuous (or smooth, or $C^k$ for some $k$) such that the rank of $f(x)$ is constant. Then the set $\{(x,v)|x\in U,\;v\in\ker f(x)\}\subset U\times\mathbb{R}^p$ is a vector bundle over $U$.
To prove the claim, suppose first that $p\geq q$, and that the matrix $f(x)$ is of degree $q$ for every $x$. Let $x\in U$, and without loss of generality, suppose that the $q$ rightmost columns of $f(x)$ are linearly independent. Then there is a neighborhood $x\in V\subset U$ such that for every $y\in V$ the $q$ rightmost columns of $f(y)$ are linearly independent. Let us write $$f(y)=:(A(y)\;B(y)),$$where $A:V\to M_{q\times (p-q)}(\mathbb{R})$ and $B:V\to M_{q\times q}(\mathbb{R})$ are continuous (or differentiable), and $B(y)$ is everywhere invertible. Then the kernel of $f(y)$ is given by $$\begin{align}\ker f(y)&=\left\{\left.\left(\begin{array}{c}w\\z\end{array}\right)\right|w\in\mathbb{R}^{p-q},z\in\mathbb{R}^q,A(y)w+B(y)z=0\right\}\\
&=\left\{\left.\left(\begin{array}{c}w\\z\end{array}\right)\right|w\in\mathbb{R}^{p-q},z\in\mathbb{R}^q,z=-B(y)^{-1}A(y)w\right\}.\end{align}$$Hence, the set $$\{(y,v)|y\in V,v\in\ker f(y)\}$$is homeomorphic (diffeomorphic) to $V\times\mathbb{R}^{p-q}$ by $$(y,a)\mapsto\left(y,\left(\begin{array}{c}a\\-B(y)^{-1}A(y)a\end{array}\right)\right).$$The case $\mathrm{rank}(f)=q$ is thus proved.
We proceed to the general case $\mathrm{rank}(f)=r\leq q$. Let $x\in U$, and without loss of generality, suppose the upper rightmost $q\times q$ submatrix of $f(x)$ is invertible. Once again, this continues to hold on a neighborhood $x\in V\subset U$. As the rank is constant on $V$, for every $y\in V$ and $v\in\mathbb{R}^p$ we have $v\in\ker f(y)$ if and only if the first $r$ coordinates of $f(y)v$ vanish. This means that, in $V$, we may ignore the bottom $q-r$ rows of $f$, and this case follows from the previous one.

A: Fleshing out the comments from earlier.
We might as well assume the base is connected, in which case the dimension of the kernel has to be constant (continuous map from connected to discrete space). Moreover, we might as well assume the base is $\mathbb{R}^n$ and the bundles are trivial over the base, since a collection of vector spaces over a base will be a vector bundle iff it is a vector bundle locally. So the morphism of bundles is just a $p$ by $q$ matrix, varying smoothly over the points.
Now say that you have a smooth function $\phi: \mathbb{R}^n \to M_{p \times q}(\mathbb{R})$ such that the dimension of the kernel of the image of a point is constant. The claim is that $x \mapsto \ker \phi(x)$ is a vector bundle over $\mathbb{R}^n$. Again we can prove that it's a bundle over a bunch of open subsets that cover $\mathbb{R}^n$.
We may think of $\phi$ as a matrix of smooth functions $\phi_{ij}$. Elementary row operations don't change the kernel of $\phi(x)$, so we are free to manipulate the matrix by elementary row operations. Elementary column operations do change the kernel, but don't change the isomorphism class of the bundle $x \mapsto \ker \phi(x)$ (because an invertible p by p matrix $\psi$ gives an isomorphism from $\ker \phi \circ \psi$ to $\ker \phi$.)
The kernel bundle is trivial over an open set if the matrix of functions is constant on that set.
We are going to induct on the product $pq$ of the dimensions of the matrix. If the matrix is one by one then it is either identically zero or nowhere zero by the assumption on the rank, and the result is clear in either case.
Let $U_{ij}$ be the subset of $\mathbb{R}^n$ where $\phi_{ij}$ doesn't vanish. We can assume that the $U_{ij}$ cover $\mathbb{R}^n$ since otherwise $\phi$ is the zero matrix identically at some point, hence at every point by our assumption on the dimension of the kernel, and in that case the claim is obvious. So it suffices to prove the result over the $U_{ij}$.
Now on $U_{ij}$, we can divide row $i$ by $\phi_{ij}$, and use it to eliminate the remainder of column $j$ and row $i$, then move it into position $(1, 1)$. Our bundle is thus isomorphic to the kernel of a bundle of the form
$$
\begin{pmatrix}
1 & 0 & \ldots & 0\\
0 & \widetilde{\phi}_{22} & \ldots & \widetilde{\phi}_{2q} \\
\vdots & \ddots & \ldots & \vdots \\
0 & \widetilde{\phi}_{p2} & \ldots & \widetilde{\phi}_{pq}
\end{pmatrix}.
$$
which itself is isomorphic to the kernel bundle for the lower-right submatrix, and so we get the result by induction.


text:
Q: Android Studio Layout. won't match parent Everything looks fine in my previews but when I open the app in an emulator the layout doesn't match parent for length or width. Everything is where it should be within the layout it just doesn't stretch overall with the screen. This is happening in every layout in the app(I'm using fragments). To explain better heres pix:
** What is in the preview(and is what i want)

** What I have

here is the XML.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="center"
        android:src="@drawable/hlineand"/>

    <TextView
        android:id="@+id/userTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="User"
        android:textAlignment="center"
        android:textAppearance="@android:style/TextAppearance.Material.Small"
        android:textColor="@android:color/darker_gray"
        android:textSize="30dp"/>

    <TextView
        android:id="@+id/updateTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:text="----"
        android:textAlignment="center"/>

    <EditText
        android:id="@+id/emailEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:hint="e-mail"
        android:inputType="textEmailAddress"
        android:layout_below="@+id/userTextView"
        android:layout_centerHorizontal="true"/>

    <EditText
        android:id="@+id/passwordEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/emailEditText"
        android:layout_below="@+id/emailEditText"
        android:layout_marginTop="24dp"
        android:ems="10"
        android:hint="password"
        android:inputType="textPassword"/>

    <Button
        android:id="@+id/loginButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/passwordEditText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Login"/>
</RelativeLayout>

This is my content main.xml. Like the first commenter mentioned, it was in there. It worked great when I put in match parent & match parent but not its resizing to some like width 344px & height 590px. Any way I can keep that as match parent??
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.a2.reach.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="344dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>

A: Fixed the content main XML by changing the width height to 0dp instead of match parent & adding the 4 constraints on the bottom of the frame layout. Thank you guys and thank you as well to @Du.fantasy for pointing me in the right direction so fast
<FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="0dp"
        android:layout_height="0dp"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

A: change the FrameLayout to match_parent from fix width and height
 <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.a2.reach.MainActivity"
        tools:showIn="@layout/app_bar_main">

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout_editor_absoluteY="8dp"
            tools:layout_editor_absoluteX="8dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

    </android.support.constraint.ConstraintLayout>

A: As per my knowledge, In your first XML, Your are giving orientation="vertcial" to relative layout. If you want that it should work then you should use Linear layout and use orientation for that layout.
Try using like this in you content XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_blood_g_activity"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Mature Diabetic Patient"
    android:layout_gravity="center"
    android:textSize="15dp"/>

<View
    android:layout_width="wrap_content"
    android:layout_height="30dp"/>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Your current Blood Sugar"/>
    <View
        android:layout_width="20dp"
        android:layout_height="60dp"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cbs"
        android:inputType="number"
        android:hint="mg/dl"/>

</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Your Target Blood Sugar"/>
    <View
        android:layout_width="20dp"
        android:layout_height="60dp"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tbs"
        android:inputType="number"
        android:hint="mg/dl"/>

</LinearLayout>
 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Humalog/Novalog"
        android:id="@+id/btnhnbs"
        android:layout_gravity="center"/>
  </LinearLayout>

A: in my variant change size parent Layout - fixed my problem

    <FrameLayout
        android:id="@+id/map_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    </FrameLayout>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing Slack CURL call into PowerShell I've in the middle of writing a translation of a working Slack script from Bash to Powershell, and I'm stumbled on what is literally the meat of the problem; how to use Invoke-WebRequest to replace curl.
This is the curl command that works successfully in Bash on *nix systems:
curl \
-X POST \
-H "Content-type: application/json" \
--data "{
   \"attachments\":
   [
      {
         \"mrkdwn_in\": [\"text\"],
         \"color\": \"$COLOUR\",
         \"text\": \"$MESSAGE\",
      }
   ]
}" \
https://hooks.slack.com/services/tokenpart1/tokenpart2

Note the $COLOUR and $MESSAGE variables are derived from elsewhere in the script (not the section I'm having trouble with).
I can't get it to work in PowerShell. My translation so far is:
$Body = @{
   "attachments" = "[
      {
         "mrkdwn_in": ["text"],
         "color": "$Colour",
         "text": "$Message",

   ]"
}

$BodyJSON = $Body |convertto-JSON

Invoke-WebRequest -Headers -Method Post -Body "$BodyJSON" -Uri "https://hooks.slack.com/services/tokenpart1/tokenpart2" -ContentType application/json

This results in the following error:
At C:\path-to-file-etc.ps1:53 char:11
+          "mrkdwn_in": ["text"],
+           ~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'mrkdwn_in": ["text"],
         "color": "$COLOUR",
         "text": "$MESSAGE",
      }
   ]"' in expression or statement.
At C:\path-to-file-etc.ps1:53 char:11
+          "mrkdwn_in": ["text"],
+           ~
The hash literal was incomplete.At
C:\path-to-file-etc.ps1:53 char:11
+          "mrkdwn_in": ["text"],
+           ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
   ception
    + FullyQualifiedErrorId : UnexpectedToken

Process exited with code 1
Process exited with code 1
Step Notify (PowerShell) failed

I have pretty much zero experience in Powershell. Also because this script has to be able to dropped onto a whole variety of boxes,I won't use any libraries or custom cmdlets or anything like that. Out of box methods or die.

A: Since you're using ConvertTo-Json anyway, it's simpler to construct the entire input as a (nested) custom object / hashtable, and let ConvertTo-Json handle all JSON formatting:
$Body = [pscustomobject] @{
  attachments = , [pscustomobject] @{
    mrkdwn_in = , 'text'
    color = $Colour
    text = $Message
  }
}

$BodyJson = $Body | ConvertTo-Json -Depth 3

Note: You could substitute [ordered] for [pscustomobject] to use a hashtable with ordered keys instead; even omitting either would work, though seeing the entries in the resulting JSON in different order may be confusing.
Note the use of ,, the array-construction operator, to ensure that the attachments and mrkdwn_in entries are treated as arrays.
Additionally, since ConvertTo-Json only fully serializes to a default depth of 2 levels, -Depth 3 must be used to ensure that the value of entry mrkdwn_in is serialized as an array.

As for what you tried:
Your immediate problem (in addition to the missing } that Jeff Zeitlin points out in a comment on the question): You've neglected to escape the embedded " chars. in your multi-line string.
Therefore, as documentation topic Get-Help about_Quoting_Rules discusses, you can either use `" to embed double quotes inside "..." or use a here-string (@"<nl>....<n>"@).
Even with the syntax problems fixed, your code wouldn't work as intended, however, because ConvertTo-Json wouldn't preserve the pre-formatted JSON in the attachments entry and instead treat the string value as a string literal that needs escaping; here's a simple example:
@{
    foo = "[
      1,
      2
    ]"
 } | ConvertTo-Json

The above yields:
{
  "foo": "[\n    1, \n    2 \n   ]"
}


text:
Q: Finding Duplicates in Access with more than 2 columns as basis and results I have an access table with 11 columns.

*

*PeriodYear

*PeriodCycle

*PeriodZone

*PHSRCode

*LastName

*FirstName

*PRC

*Specialty

*HCPType

*Class

*Institution

I want to find duplicate entries for it using Lastname, Firstname, and Institution as the basis where to find the duplicates.
Example Table:
    PeriodYear  PeriodCycle  PeriodZone  PHSRCode  Lastname  Firstname  PRC  Specialty  HCPType  Class  Institution

    2013        1            1           SF1-01    Almeda    Sancho     111  GP         CON      A      PGH
    2013        1            2           SF1-01    Almeda    Sancho     111  GP         CON      A      LPDH
    2013        1            3           SF1-01    Almeda    Sancho     222  GP         CON      A      PGH

The result should be:
    PeriodYear  PeriodCycle  PeriodZone  PHSRCode  Lastname  Firstname  PRC  Specialty  HCPType  Class  Institution

    2013        1            1           SF1-01    Almeda    Sancho     111  GP         CON      A      PGH
    2013        1            3           SF1-01    Almeda    Sancho     222  GP         CON      A      PGH

The query will be based on the fields PeriodYear, PeriodCycle, and PHSRCode, which will come from variables.
Is this possible?

A: First create a "pointer" query that determines all records that have dupes:
SELECT LastName, FirstName, Institution, Sum(1) as CNT
FROM MyTableName
GROUP BY LastName, FirstName, Institution
HAVING (Sum(1) > 1)

Call that Query1 or something.
Then LEFT JOIN Query1 to MyTableName on those fields, and use a WHERE clause to only keep the data you want based on your variables:
SELECT B.*
FROM Query1 A
LEFT JOIN MyTableName B
ON A.LastName = B.LastName
AND A.FirstName = B.FirstName
AND A.Institution = B.Institution
WHERE B.PeriodYear = Forms!frmMyForm!txtPeriodYear
AND B.PeriodCycle = Forms!frmMyForm!txtPeriodCycle
AND B.PHSRCode = Forms!frmMyForm!txtPHSRCode

You will obviously have to do some tweaking, but this should give you the right idea.


text:
Q: Best way to format a string in C# I have two formats and they are shown below.
Format 1 :
printstring = printstring & "---------------------------------------" & vbNewLine

Format 2 :
printstring = String.Format("{0}---------------------------------------{1}", printstring, vbNewLine)

It was recommended to follow Format 2 by a Code Optimization Tool.
Is there any specific reason for this? Like memory consumption or some other reason?

A: Your code is suffering from SQL injection.
String formats are more efficient with large strings than string concatenations. They are also slightly easier to read. Both are perfectly valid.
To fix your SQL injection issue, you will want to parametrize your query:
using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
    //
    // The name we are trying to match.
    //
    string dogName = "Fido";
    //
    // Use preset string for connection and open it.
    //
    string connectionString =
        ConsoleApplication1.Properties.Settings.Default.ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        //
        // Description of SQL command:
        // 1. It selects all cells from rows matching the name.
        // 2. It uses LIKE operator because Name is a Text field.
        // 3. @Name must be added as a new SqlParameter.
        //
        using (SqlCommand command = new SqlCommand(
        "SELECT * FROM Dogs1 WHERE Name LIKE @Name", connection))
        {
        //
        // Add new SqlParameter to the command.
        //
        command.Parameters.Add(new SqlParameter("Name", dogName));
        //
        // Read in the SELECT results.
        //
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            int weight = reader.GetInt32(0);
            string name = reader.GetString(1);
            string breed = reader.GetString(2);
            Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",
            weight,
            name,
            breed);
        }
        }
    }
    }
}

Output
(This varies depending on your database contents.)
Weight = 130, Name = Fido, Breed = Bullmastiff

A: I may be wrong here, but it looks like "grd.CurrentRow.Cells(1).Value" will resolve to a value in your c# code. You then intend to send this to the database. In other words your Format 2 will replace "grd.CurrentRow.Cells(1).Value" with a value before it goes to the database. Your Format 1 won't so is most likely incorrect and will not work.
In terms of performance, parameterizing queries is always recommended as it allows SQL Server's (if that is the database you are using) built in optimizer to build a query plan to optimise regular run queries. It will store this plan in a cache, so if you keep making the same types of queries, SQL Server should know the best way to call it after you have made one\more calls. Using Entity Framework or Stored Procedures to do data access will help you out here rather than building hard coded sql statements.
See these links for more information:

*

*Simple Parameterization

*Parameters and Execution Plan Reuse


text:
Q: Run script on Awesome WM startup I'm trying to run a script on Awesome WM start after the login screen (not on the awesome --replace or awesome.restart()).
Does anyone knows the way? No matter is it some kind of /etc/rc.* script or the ~/.config/awesome/rc.lua solution.
Thanks!

A: As a workaround, adding those signals handlers into ~/.config/awesome/rc.lua:
awesome.connect_signal(
    'exit',
    function(args)
        awful.util.spawn('touch ~/.awesome-restart')
    end
)

awesome.connect_signal(
    'startup',
    function(args)
        awful.util.spawn('bash -c "rm ~/.awesome-restart || ~/script-to-run-on-startup.sh"')
    end
)

Explaining:
- on the exit signal, that performs only on awesome restart we're creating a flag file, that tells to the startup signal that this startup is going immediately after the awesome restart
- on the startup signal fired we're removing this flag and if it doesn't remove successfully (doesn't exist) - we're running our startup-only script.
PS: Checked - the exit signal doesn't fire on sudo reboot, so it won't be inappropriately fired on full system restart.


text:
Q: Problem joining 2 tables and aggregate function I got an issue joining 2 tables using the sum function. The aggregate returns the total sum for the whole period not dividing it based on the columns from the joined table. Any idea what to do to get revenue per day and retail? Thank you.
Syntax:
Select Date, Retailname, sum(Revenue)
From table1 t1
Join table2 t2
On t1.primarykey = t2.primarykey
Group by Date, Retailname

Result:
Date    Retailname    Revenue
X          Name1.          224
X.         Name2.          224
X.         Name3.          224
X.         Name4.          224

........
Desires result:
Date    Retailname    Revenue
X          Name1.          25
X.         Name2.          75
X.         Name3.          96
X.         Name4.          28

........
I tried correlated subquery from select clause but it returns the same result.

A: For joining process your data will be duplicate, so for that you sum function calculated sum from duplicated records. You can firstly sum your table before joining, and after summing and grouping you can join second table, or vice versa.
Some examples:
select t1.* from (
    select id, sum(val) from table1
    group by id
) t1 inner join table2 t2 on t1.id = t2.id

or
select t1.* from table2 t2
inner join
(   select id, sum(val) from table1
    group by id
) t1 on t1.id = t2.id

And for not viewing duplicate records you can use distinct.


text:
Q: Why am I getting 404 not found? I am using the mean stack and I am trying to delete pictures but having a problem and I am getting a '404 not found' error. Everything seems to line up correctly but for some reason it's not working. Can anyone see why? Here is what I have:
HTML

 <button class="button btn btn-warning" ng-click="deletePics(photo._id)">Delete</button>

Angularjs
  $scope.deletePics = function(id){
    $http.delete('/api/admin/photos/' + id)
        .then(function successCallback(response){
            console.log(response);
            },
            function errorcallback(error){
                console.log(error);
            });

  };

Nodejs/Expressjs
//delete photos
apiRoutes.delete('/admin/photos/:id'),function(req,res){
    console.log('deleted photos');
    res.send('this works');

};

Also, api index.js is using apiroutes as api
var apiRoutes = require('./apiRoute');
app.use('/api',apiRoutes);


text:
Q: Are empty synchronized blocks optimized out by Java compiler? Suppose somewhere in my code I write an empty synchronized block:
synchronized(obj){
   //No code here
}

So as the synchronized block does not contain any code, will JIT compiler optimize that out by not locking on obj as it will be of no use?
Java compiler does similar tricks such as Lock coarsening but will this synchronized block be also optimized out?
EDIT:
As per the point made by assylias,
synchronized(new Object()){
   //empty block
}

will the JIT compiler now be able to optimize this out, since I am using an Object which doesn't escape my method?

A: This can't be optimized away on the basis of the Java Memory Model semantics. The lock acquisition-release operation may be replaced by something else, but even an empty synchronized block has consequences on the visibility of actions taken by other threads acquiring the same lock.
Specifically, there is a guarantee that all write actions done by one thread before releasing the lock are visible to the other thread after it acquires the same lock.
Regarding your EDIT
This is a very different case: a lock is obtained on an object which can be proved by escape analysis that no other thread will ever be able to fetch it. In this case it doesn't matter what the contents of the synchronized block are: the point is only in the lock used. The code can look as you posted it, or even like this:
Object o = new Object();
synchronized(o) {
   // any operations you like, as long as they don't let o escape the method scope
}

This can be acted upon by the transformation known as lock elision: the JVM can pretend it never saw the synchronized block. This is because the JMM semantics refer only to the cases of acquiring the one and the same lock.


text:
Q: Scheme "mcar: contract violation" (define (create-polygon ptlist)
  (if (null? ptlist) 0
      (append (list (make-seg (car ptlist) (cadr ptlist))) (create-polygon (cdr ptlist)))))

My problem is whenever I try to run this program it gives contract violation error. I know that you can't car or cdr empty lists but I'm checking if it's empty or not. So what is the problem here?

A: Consider the following:
(define lst '(1))

(null? lst)
=> #f

(cadr lst)
=> cadr: contract violation

As you can see, the contract violation occurs because (null? lst) only checks whether the list is currently empty. But if you use cadr, which is (car (cdr lst)), then you have to check whether (cdr lst) is empty as well.
So, your if statement needs to check both (null? ptlist) and (null? (cdr ptlist)), preferrably using cond.


text:
Q: position of hyperlink when ppt with hyperlink to image I will try to convert ppt to image using program(C# or Java).
I can search this solution in the Stackoverflow but the problem is the following:
The ppt has some hyperlink such as "go to next Page" and "go to specific slide".
How can I know where the hyperlink is at the image when I convert ppt to image?
Any Language is Ok....if I can find out the position of hyperlink at image.

A: Each slide has a hyperlinks collection that contains all of the hyperlinks on the slide.
Look at each hyperlink's .Type property.
If .Type = msoHyperlinkShape, you can get the hyperlink's coordinates by walking the .Parent chain up to the parent shape; use the shape's coordinates.
If .Type = msoHyperlinkRange, the hyperlink has been applied to text rather than to a shape, so you walk up the .Parent chain to the textrange that represents the hyperlinked text.  The text range will have BoundLeft, BoundTop, BoundHeight, BoundWidth properties that give you the coordinates of the hyperlink.
From there, it's ratios ...
LinkLeft / SlideWidth = x / ImageWidthInPixels
Solve for x to get the distance in pixels from the left of the image to the left of the hyperlink position.


text:
Q: How many self-injective quiver algebras are there? Given a fixed finite quiver $Q$ over a field $K$ (possibly finite), is there a quick way to determine how many self-injective quiver algebras $KQ/I$ (with admissible ideal) of Loewy length at most $m \geq 2$ exist up to isomorphism ($Q$ and $m$ are fixed)?
Recall that a quiver algebra being self-injective is a purely combinatorial condition—self-injectivity holds iff there exists a permutation $\pi$ such that ${\mathrm {soc}}(S_{\pi(i)})={\mathrm {top}}(P(S_i))$, where $S_j$ denotes a simple module and $P(S)$ the projective cover.
The answer is infinite if the field is the complex numbers and $m=3$ when $Q$ consists of one point and two loops.
So in general there might be infinitely many (except when the field is finite) and the problem might be too complicated. If this is the case, I'm also interested in special cases; for example, if $Q$ is the quiver of a preprojective algebra of type A or D.
As a concrete example (a quiver of a preprojective algebra of type A), let $a_{n,m}$ be the number of self-injective quiver algebras up to isomorphism with Loewy length at most $m \geq 2$ and the underlying quiver $Q$ having $n$ points and one arrow from $i$ to $i+1$ and one from $i+1$ to $i$ for $i=1,2,...,n-1$. What is $a_{n,m}$? As an example, $a_{2,m}=1$. It might be that the answer in this case is independent of the field; this occurs if $Q$ is an oriented cycle. Are there other cases?


text:
Q: In how many ways can we place $k$ distinct objects into $n$ identical boxes if each box contains atmost one object
In how many ways can we place $k$ distinct objects into $n$ identical
  boxes if each box contains at most one object?

Interpreting it as permuting n objects taken k at a time.So,there are $\binom{k}{n}\times n!$ ways.
Am i correct?

A: Informally:
Each object goes into a box by itself.  This can only be done one way if $k\leq n$ and zero ways if $k>n.$

More Formally:
We are counting the number of partitions of $\{1,2,\ldots,k\}$ with at most $n$ parts and each part has at most one element.
Since each part has at most one element, there is only one such candidate: $$\{\{1\}, \{2\}, \ldots, \{k\}\}$$

*

*If $k \leq n,$ then this partition satisfies the requirements of the problem, so there is exactly one such partition.

*If $k > n,$ then this partition has too many parts, so there are zero such partitions.


text:
Q: Slicing each line from data CSV file I have a movie dataset that looks like this:
1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy
2,Jumanji (1995),Adventure|Children|Fantasy
3,Grumpier Old Men (1995),Comedy|Romance
4,Waiting to Exhale (1995),Comedy|Drama|Romance
5,Father of the Bride Part II (1995),Comedy
6,Heat (1995),Action|Crime|Thriller
7,Sabrina (1995),Comedy|Romance
8,Tom and Huck (1995),Adventure|Children

I want to extract only the last part (genres part, e.g, Adventure|Animation|Children|Comedy|Fantasy) and store them in a list list[Adventure, Animation, Children, Comedy, Fantasy]. However, I am still stuck at slicing step. I don't know how to do that since line[:-1] doesn't slice. I use Python 2.7
with open(path + 'movie.csv') as f:
    for line in f:
        print line[:-1]

A: with open(path + 'movie.csv') as f:
    for line in f:
        print line.split(',')[:-1].rstrip('\n').split('|')

A: Your slice will return the last character of each line, since the lines are not splitted when you read the file in regular manner. You should read the file using csv module that separates the lines automatically with ',' delimiter. Then split the result with |.
import csv
with open(path + 'movie.csv') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print(row[-1].split('|'))


text:
Q: style function called twice in openlayers I wonder why my style function is called twice for each cluster added to the layer. This is the code I have:
function calculateClusterInfo(feature, resolution) {
    //This function called twice
    var style, size, circleRadius, circleFill, zoomMapID;
    size = feature.get('features').length;
    var style = styleCache[size];
    if (!style) {
    if (size > 1) {
        if (size < 10) { // small cluster
            circleRadius = 30;
            circleFill = new ol.style.Fill({
                color: [181, 226, 140, 0.6]
            });
        }
        style = [new ol.style.Style({
            image: new ol.style.Circle({
                radius: circleRadius,
                fill: circleFill
            }),
            text: new ol.style.Text({
                textAlign: "start",
                textBaseline: "middle",
                font: "bold 12px helvetica",
                text: size,
                fill: new ol.style.Fill({color: "#000000"}),
                stroke: new ol.style.Stroke({color: "#ffffff", width: 4}),
                offsetX: 0,
                offsetY: 0,
                rotation: 0
            })
        })];
        return style;
    } else {
        style = [feature.get('features')[0].getStyle()];
        return style;
    }
    }
};

I cannot figure out why style function is called twice.


text:
Q: Improving performance of a while loop (C# code) calling a T-SQL stored procedure The following SqlCommand works fine with no apparent performance issues, when the stored procedure SelectNewObjects returns few (~500) records. However, when it returns more than 1,000 records, I start experiencing performance issues:
using (SqlCommand cmdAddNewObject = new SqlCommand("SelectNewObjects", con))
{
    cmdAddNewObject.CommandType = CommandType.StoredProcedure;
    cmdAddNewObject.Parameters.AddWithValue("@parameter1", parameter1);
    using (SqlDataReader rdrAddNewObject = cmdAddNewObject.ExecuteReader())
    {
        while (rdrAddNewObject.Read())
        {
            if (rdrAddNewObject.GetString(0) != null)
            {
                try
                {
                    addObject(parameter1, rdrAddNewObject.GetString(0), rdrAddNewObject.GetString(0).Length / 4, rdrAddNewObject.GetString(0).Substring(0, 2),
                        rdrAddNewObject.GetString(0).Substring(2, 2), rdrAddNewObject.GetString(1));
                    if (rdrAddNewObject.GetString(1) == "No description found")
                    {
                        // Do something
                    }
                    else
                    {
                        // Do something else
                    }
                }
                catch (Exception ex)
                {
                    // Throw exception
                }
            }
        }
    }
}

In simple words, what I am doing here is call a method (addObject) for each record that is returned by SelectNewObjects.
A couple of details:

*

*SelectNewObjects returns records from a temporary table created off Table1.

*In the if / else block I am updating a field of Table1 of the related record in the temporary table after the execution of addObject completes.

*The addObject method inserts each record found in the SQL temporary table in a separate Oracle system through the use of SOA (Service-Oriented Architecture). I was not given access to the underlying DB, so I had to settle with this way of doing things instead.

*There are times when the temporary table is expected to have more than 20,000 records (only two fields each: Name and Description) so this can quickly become a nightmare.
At one point, the application pool will fail with the following two errors (taken from the IIS 7 Windows Event Viewer):

*

*Event ID 5013: A process serving application pool '.NET v4.5' exceeded time limits during shut down. The process id was '5616'.

*Event ID 5138: A worker process '5616' serving application pool '.NET v4.5' failed to stop a listener channel for protocol 'http' in
the allotted time.  The data field contains the error number.
The description of those event IDs in technet.microsoft.com and support.microsoft.com do not shed too much light on this performance issue and is not conclusive as to its root cause.
That said, is there any way to improve the C# code to handle tens of thousands of records returned by the SP, and perform an action on each one faster?

A: I'm assuming this is because it's taking a long time to insert into the oracle DB over the wire as well as keeping your SQL connection open longer than it should be open. Therefore you will want to store your data in a temp collection THEN either loop through the list or send it as bulk (if you do the latter you will need to break it up or you will hit a limit)
eg
    List<ObjectToStoreInOracle> items = new List<ObjectToStoreInOracle>();

    using (SqlCommand cmdAddNewObject = new SqlCommand("SelectNewObjects", con))
    {
        cmdAddNewObject.CommandType = CommandType.StoredProcedure;
        cmdAddNewObject.Parameters.AddWithValue("@parameter1", parameter1);
        using (SqlDataReader rdrAddNewObject = cmdAddNewObject.ExecuteReader())
        {
            while (rdrAddNewObject.Read())
            {
                if (rdrAddNewObject.GetString(0) != null)
                {
                    try
                    {
                        // add items to temp array list
                        items.Add(new ObjectToStoreInOracle(parameter1, rdrAddNewObject.GetString(0), rdrAddNewObject.GetString(0).Length / 4, rdrAddNewObject.GetString(0).Substring(0, 2), rdrAddNewObject.GetString(0).Substring(2, 2), rdrAddNewObject.GetString(1))))

                        if (rdrAddNewObject.GetString(1) == "No description found")
                        {
                            // Do something
                        }
                        else
                        {
                            // Do something else
                        }
                    }
                    catch (Exception ex)
                    {
                        // Throw exception
                    }
                }
            }
        }
    }

    AddToOracleDB(items)

    private void AddToOracleDB(List<ObjectToStoreInOracle> items){

    //do stuff here to add to the Oracle DB
    }


text:
Q: to assign value to a particular cell of datagridview I have a datagridview view which has quantity and price whose multplied value should be displayed in amount column of the dgview. I am pasting the code tried so far.But it throws error in the following line.
 dgvpricelist.Rows[i].Cells["totalamount"].Value = totalprice;

The error thrown is "Stack overflow exception error".Have no idea why the error is thrown
 public void totalcalculation()
    {

        if (dgvpricelist.Rows.Count > 1)
        {
            double TAmount = 0;

            for (int i = 0; i < dgvpricelist.Rows.Count; i++)
            {
                int quantity = Convert.ToInt32(dgvpricelist.Rows[i].Cells["quantity"].Value);
                double itemPrice = Convert.ToDouble(dgvpricelist.Rows[i].Cells["intpricelvl1"].Value);

                totalprice = quantity * itemPrice;
                dgvpricelist.Rows[i].Cells["totalamount"].Value = totalprice;

                edittotalprice = Convert.ToDouble(dgvpricelist.Rows[i].Cells["totalamount"].Value);
                TAmount += edittotalprice;
                //txtboxtaxvalue.Text = tax.ToString();
                //txtboxtotalvalue.Text = total.ToString();
                //TAmount = edittotalprice;
            }

            int roundedtotal = (int)Math.Round(TAmount);
            txtboxstotalvalue.Text = TAmount.ToString();
            txtboxtotalvalue.Text = roundedtotal.ToString();
        }

May I know what is the correct way to achieve my objective?


text:
Q: How to find day light time saving is active and save time in SQL for UK? I am looking to save current UK time and problem is they have two timezone GMT and BST accordingly day saving light ?
I am saving time in SQL date time column from mobile app and SQL server. I am insert time using SQL.


text:
Q: How to safely give my function without making my main form stuck I have made a WPF application which has a button to move some files attached
to the column cells from one column to another column. The moment when I press
the button it shows  a nice animation and moves all files to the next column's cells.
But my real problem is once I give my function color_check(),
my application is getting stuck. I really don't know why. Is there
any help I can get out for this?
Code:
 private void button3_Click(object sender, EventArgs e)
    {
        Hide();
        bool done = false;
        ThreadPool.QueueUserWorkItem((x) =>
        {
            using (var splashForm = new Form4())
            {
                splashForm.Show();
                while (!done)

                    Application.DoEvents();
                splashForm.Close();
            }
        });

        move(); //file moving function
        //color_check();  if i give this fn, my form stucks and comes to live after 10 - 20 sec
        done = true;
        MessageBox.Show("TEST FINISHED");
        Show();
    }

 public void color_check()  //this is my problem making fn
    {
        dataGridView1.Refresh();
         string strVal = ini.ReadValue("Action", "Doc-Controller");

        bool authenticated = true;

        if (authenticated == UserInCustomRole(strVal))
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                // Application.DoEvents();
                string fName1 = System.IO.Path.GetFileNameWithoutExtension(row.Cells[3].Value.ToString());
                string fName2 = System.IO.Path.GetFileNameWithoutExtension(row.Cells[4].Value.ToString());
                if (!string.IsNullOrEmpty(fName1) && !string.IsNullOrEmpty(fName2))
                {
                    var f1 = GetValue(fName1.ToCharArray()[fName1.Length - 2]) * 16 + GetValue(fName1.ToCharArray()[fName1.Length - 1]);
                    var f2 = GetValue(fName2.ToCharArray()[fName2.Length - 2]) * 16 + GetValue(fName2.ToCharArray()[fName2.Length - 1]);
                    //if (System.IO.Path.GetFileName(fName1) != System.IO.Path.GetFileName(fName2))
                    if (f1 > f2)
                    {
                        //MessageBox.Show(fName1);
                        DataGridViewCellStyle style = new DataGridViewCellStyle();
                        style.BackColor = Color.Yellow;
                        row.Cells[3].Style = style;
                    }
                    else if (f2 > f1)
                    {
                        //MessageBox.Show(fName1);
                        DataGridViewCellStyle style = new DataGridViewCellStyle();
                        style.BackColor = Color.Yellow;
                        row.Cells[4].Style = style;
                    }

                    if (f1 == f2)
                    {
                        DataGridViewCellStyle style = new DataGridViewCellStyle();
                        style.BackColor = Color.Plum;
                        row.Cells[4].Style = style;
                        row.Cells[3].Style = style;
                    }
                }
            }

    }

A: The issue is that your code which is invoked on button3_click() is blocking the UI thread. That's why it appears to freeze for a while - the code is executing, and once it's complete the UI thread becomes responsive again.
The way to resolve this is to perform your actions asynchronously on another thread. In .NET 4 and beyond, you can use Tasks and the async/await keywords to help you manage this. If you are working on a version older than .NET 4, then you'll want to take a look at BackgroundWorker or other threading options compatible with your version of .NET.
Note that if you want to modify the GUI in your async method, you may need to use a Dispatcher.Invoke() to do so safely.
Here are some links to help you understand some approaches available to you
C# Blog on Understanding a simple async program
MSDN reference for async/await
Related StackOverflow question on how to use BackgroundWorkers
Related StackOverflow question on how to access the UI thread directly

A: In a normal UI application, no 2 functions that work on the GUI will run at the same time. This would result in a lot of issues otherwise, which usually would cause the program to crash. For example there could be 2 functions running at the same time that each check if the same list has at least one element and then remove an element - because they run at the same time they first both check if the list has 1 element.
That's why GUI functions all run in the same thread, meaning they run only one at a time. While color_check runs, other functions don't run.
You can launch additional threads and do work on them that is executed in parallel, of you can speed up the color_check function, for example by breaking it up into parts which run at lower priority one at a time, using a dispatcher
Take this:
public void color_check()  //this is my problem making fn
{
    dataGridView1.Refresh();
    string strVal = ini.ReadValue("Action", "Doc-Controller");

    bool authenticated = true;

    if (authenticated == UserInCustomRole(strVal))
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
           ProcessRow(row);
        }
    }
}

and change it to this:
public void color_check()  //this is my problem making fn
{
    dataGridView1.Refresh();
    string strVal = ini.ReadValue("Action", "Doc-Controller");

    bool authenticated = true;

    if (authenticated == UserInCustomRole(strVal))
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
           Dispatcher.BeginInvoke(DispatcherPriority.Background, ()=>{Process(row);});
        }
    }
}

In this code, Dispatcher.BeginInvoke tells the UI thread that it should run Process(row), as soon as it finds the time. This might result in 200 Process(row) calls that are waiting to be executed. It's still all executed on the UI thread and only one thing at a time. If a mouse click happens after the first hundred have been completed, the GUI thread will first finish number onehunderd and one, and then handle the mouseclick, before picking up the remaining calls to process.
There's a disadvantage to this approach. By allowing other functions to be executed in between different calls to Process(row), you may get surprising results. Especially if these other processes also change the cell styles.


text:
Q: ElasticSearch searching on List using Nest C# I used to have type Person with field Guid MetroStation, and I was searching in elastic:
.Query(q => q.Term(tr => tr.Field(fl => fl.MetroStation).Value(MyMetroStation))

Now am changing Guid to List<Guid>. How can I search in elastic for this?

A: You won't need to change your search in any way if you are looking to find Person documents where the MetroStation Guids contain the Guid in the query.
If you're looking for Person documents where the MetroStation Guids contain exactly what is in the query, then you might consider also indexing the number of Guids in the collection to also query on. You can achieve this without indexing the count by using a script query, but if you're looking for performance, then indexing the count will likely perform better (measure it for your use case).


text:
Q: After home button and returning, it does not return to previous activity Activity A is a splash screen.
Activity B is a menu screen that is singleTask.
Activity C is a screen with noHistory that selects a photograph from the gallery with the built-in intent for choosing a photograph.
Activity D is a screen that manipulates photographs.
The problem that I have is that when I am in Activity D and select the home button, if I choose the application to be launched once more it returns me to Activity A to launch Activity B again instead of launching Activity D where I left off.  If I use the recent apps however, it switches back to Activity D just fine as expected.  So, there must be something slightly error prone in the way that I have it setup.  But, I should expect it to return to Activity D in both cases so that the user can keep coming back to the Photo viewing screen (Activity D).
Thoughts?
    <activity
        android:name="ActivityA"
        android:theme="@style/Theme.CustomDefaultStartup"
        android:noHistory="true"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:screenOrientation="sensorLandscape"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="ActivityB"
        android:theme="@style/Theme.CustomDefault"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name"
        android:launchMode="singleTask">
        <intent-filter>
            <action  android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        </intent-filter>
        <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                   android:resource="@xml/device_filter" />
    </activity>
    <activity
        android:name="ActivityC"
        android:theme="@style/Theme.CustomDefault"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name">
    </activity>
    <activity
        android:name="ActivityD"
        android:theme="@style/Theme.CustomDefault"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name">
    </activity>

A: Apparently it was the android:launchMode="singleTask" on Activity A that was causing the problems. Once, the singleTask from the splash screen was removed, the behavior returned as was expected.  Not sure where the singleTask for the splash screen came from, but it was probably an error left in place for a while in the application.
Once that was removed, Activity D no longer launched the splash screen and the following menu after a home button press and return to the application.  While I do not follow this completely as to why this would cause it in the lifecycle of events, this resolved the issue for me.


text:
Q: Can you please explain to the last step of this proof of the euclidean algorithm? This is the proof of the euclidean algorithm my CS professor taught us last lecture:
For $a\gt b: \gcd(a,b) = \gcd(a-b,b)$
Let $g=\gcd(a,b), g'=\gcd(a-b,b)$
Then:
$a=q_a \cdot g$ and $a-b = q'_\left(a-b\right) \cdot g'$
$b=q_b \cdot g $ and $b = q'_b \cdot g'$
$a-b=\left(q_a-q_b\right) \cdot g$ and $a =\left(q'_\left(a-b\right)-q'_b\right)\cdot g'$
That means:
$g$ divides $a-b,b$ and $g'$ divides $a,b$
Thus: $g \le g'$ and $g' \le g$ $\Rightarrow g = g' $
I don't understand how to arrive from "$g$ divides $a-b,b$ and $g'$ divides $a,b$" to "$g \le g'$ and $g' \le g$". Can you please explain that to me?

A: This goes back to the formal definition of gcd.  In words, the formal definition says that if $d=\gcd(a,b)$, then $d$ is a divisor of both $a$ and $b$, and any other number that is a divisor of $a$ and $b$ is less than or equal to $d$.  (That is, to be pedantic, that $d$ is the greatest of all of the common divisors of $a$ and $b$.)
What your professor showed is that $g$ is a common divisor of $a-b$ and $b$, but they already defined $g'$ to be the greatest common divisor of those two numbers.  Therefore, $g\leq g'$.  At the same time, $g'$ was a common divisor of $a$ and $b$, but $g=\gcd(a,b)$, so $g'\leq g$.

A: Perhaps the same proof with a different twist helps:
If $d$ is any common divisor of $a$ and $b$, then $d$ is also a divisor of $a-b$ (for if $a=rd$ and $b=sd$, then $a-b=(r-s)d$). The same goes in the other direction, i.e., the set of common divisors of $a$ and $b$ is the same as the set of common divisors of $a-b$ and $b$. Therefore also the greatest elements of these equal sets are equal.


text:
Q: Como fazer um repositório GIT voltar a ser uma pasta comum do sistema? Boa noite, estou aprendendo GIT. No início eu criei como repositório a pasta da minha área de trabalho. Que contém diversos arquivos que não tem nada haver com meus projetos. Então, gostaria de saber se tem como desfazer isso, não quero apagar a pasta minha área de trabalho. Só quero que ela volte a ser uma pasta comum do sistema e não um repositório GIT. Como faço isso?

A: Quando você roda o comando git init um novo repositório é criado. Isso nada mais é do que a criação de uma pasta oculta chamada .git. Todas as informações relativas ao git estão contidas nesse diretório.
Na sua área de trabalho existe essa pasta. Se você a deletar, esse diretório deixará de ser considerado um repositório Git. Se você não a consegue ver, é porque seu sistema operacional está com a configuração de esconder arquivos e pastas ocultos. Você pode desmarcar essa configuração e deletar manualmente.
Uma outra opção é abrir o prompt de comando do Windows ou o Terminal do Linux/Mac na área de trabalho e deletar essa pasta por lá.
Para referência, no Mac/Linux o comando seria o seguinte:
rm -rf .git

Para mais informações sobre como visualizar arquivos ocultos ou um passo a passo mais detalhado, veja esta resposta (em inglês).

A: git restore --source=HEAD --staged --worktree -- aDirectory
# or, shorter
git restore -s@ -SW  -- aDirectory

Com o Git 2.23 (agosto de 2019), você tem o novo comando "git restore"
Isso substituiria o índice e a árvore de trabalho pelo conteúdo HEAD
Observe que:
git checkout -- <path>

não faz uma reinicialização completa: substitui o conteúdo da árvore de trabalho pelo conteúdo preparado.
git checkout HEAD -- <path>

faz uma redefinição definitiva para um caminho, substituindo o índice e a árvore de trabalho pela versão do commit HEAD.
Se você tiver arquivos extras na árvore de trabalho que não existem no HEAD, um git checkout HEAD -- <path> não os removerá.
Nota: Com o git checkout --overlay HEAD -- <path> (Git 2.22, Q1 2019), os arquivos que aparecem no índice e na árvore de trabalho, mas não em <tree-ish> são removidos, para fazer com que correspondam exatamente a <tree-ish>.


text:
Q: Redirect third level domain This seems easy enough but I can't seem to find the exact solution online and to get it to work.  I want to redirect all the links e.g.
user1.example.com
user2.example.com
user3.example.com etc.

to
example.com/search.html?user=user1
example.com/search.html?user=user2
example.com/search.html?user=user3 etc.

in my .htaccess I have
RewriteCond %{HTTP_HOST} !^(www\.)?example.com$ [NC]
RewriteCond %{HTTP_HOST} ^([\.]+)\.example.com$ [NC]
RewriteRule .* /search.html?user=% [L]

I want to redirect all the user "subdomains" (they don't really exist on the server) except if the domain is prefix with www.  The "user" field consists of alphabets, numeric, - (dash), _ (underscore) and possibly space.  I am getting the Server Not Found error with the above .htaccess with for example, user1.example.com   What am I doing wrong? Can this be done without the real existence of these third level domains?  Thanks in advance.

A: Try this :
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ [NC]
RewriteRule .* /search.html?user=%1 [R,L]

A: You can use negative lookahead in your condition while capturing first part of domain and use the back-reference as %1 later:
RewriteCond %{HTTP_HOST} ^((?!www\.)[^.]+)\.example\.com$ [NC]
RewriteRule !^search\.html$ /search.html?user=%1 [L,QSA,NC]


text:
Q: enumitem newlist with etaremune I am entering my publications into the CV. Currently, I am using enumitem to define a new enumerate list as follows:
\makeatletter
\newlength{\bibhang}
\setlength{\bibhang}{1em}
\newlength{\bibsep}
 {\@listi \global\bibsep\itemsep \global\advance\bibsep by\parsep}
\newlist{bibenum}{enumerate}{3}
\setlist[bibenum]{label=[\arabic*],resume,leftmargin={\bibhang+\widthof{[999]}},%
    itemindent=-\bibhang,
    itemsep=\bibsep,parsep=\z@,partopsep=0pt,
    topsep=0pt}
\let\oldendbibenum\endbibenum
\def\endbibenum{\oldendbibenum\vspace{-.6\baselineskip}}
\makeatother

And add the publications as follows:
\begin{bibenum}
\item \bibentry{pub1}
\item \bibentry{pub2}
\end{bibenum}

It works fine (an example shown below)

but gives the numbers in increasing order. Instead I want them in decreasing order. So, I tried using the etaremune package as follows
\makeatletter
\newlength{\bibhang}
\setlength{\bibhang}{1em}
\newlength{\bibsep}
 {\@listi \global\bibsep\itemsep \global\advance\bibsep by\parsep}
\newlist{bibenumr}{etaremune}{3}
\setlist[bibenumr]{label=[\arabic*],resume,leftmargin={\bibhang+\widthof{[999]}},%
    itemindent=-\bibhang,
    itemsep=\bibsep,parsep=\z@,partopsep=0pt,
    topsep=0pt}
\let\oldendbibenumr\endbibenumr
\def\endbibenumr{\oldendbibenumr\vspace{-.6\baselineskip}}
\makeatother

But it gives an error of undefined control sequence...Package enumitem Error: Unknown list type 'etaremune'). Any ideas what is wrong? Is it possible to use etaremune with enumitem package?
EDIT: As pointed out by egreg, I cannot use etaremune with enumitem. Does anyone know any other way to do it? Basically a reverse numbered list with flexibility of defining the way it looks (like square brackets, indentations, separations etc.
Following is a minimum working example. I started from a template I found online and tried to remove all the unnecessary commands. Any help?
\documentclass[11pt]{article}

% This is a helpful package that puts math inside length specifications
\usepackage{calc}

% Layout: Puts the section titles on left side of page
\reversemarginpar

%% Use these lines for letter-sized paper
\usepackage[paper=letterpaper,
            marginparwidth=1.2in,     % Length of section titles
            marginparsep=.05in,       % Space between titles and text
            margin=1in,               % 1 inch margins
            includemp]{geometry}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% DEFINE THE "bibenum" list using enumitem package
%%% Need to modify this such that "bibenum" gives reverse numbering instead
\usepackage[shortlabels]{enumitem}

\makeatletter
\newlength{\bibhang}
\setlength{\bibhang}{1em}
\newlength{\bibsep}
 {\@listi \global\bibsep\itemsep \global\advance\bibsep by\parsep}
\newlist{bibenum}{enumerate}{3}
\setlist[bibenum]{label=[\arabic*],resume,leftmargin={\bibhang+\widthof{[999]}},%
        itemindent=-\bibhang,
        itemsep=\bibsep,parsep=\z@,partopsep=0pt,
        topsep=0pt}
\let\oldendbibenum\endbibenum
\def\endbibenum{\oldendbibenum\vspace{-.6\baselineskip}}
\makeatother
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage{hyperref}

%%% SECTION HEADINGS
\renewcommand{\section}[1]{\pagebreak[3]%
    \vspace{1.3\baselineskip}%
    \phantomsection\addcontentsline{toc}{section}{#1}%
    \noindent\llap{\smash{\parbox[t]{\marginparwidth}{\hyphenpenalty=10000\raggedright #1}}}%
    \vspace{-\baselineskip}\par}

\begin{document}

\section{\textbf{Journal Publications}}

\begin{bibenum}
    \item pub1
    \item pub2
    \item pres1
    \item pres2
\end{bibenum}

\end{document}

A: etaremune is customizable similarly to enumitem. Here's an emulation.
\documentclass[11pt]{article}

% This is a helpful package that puts math inside length specifications
\usepackage{calc}

% Layout: Puts the section titles on left side of page
\reversemarginpar

%% Use these lines for letter-sized paper
\usepackage[paper=letterpaper,
            marginparwidth=1.2in,     % Length of section titles
            marginparsep=.05in,       % Space between titles and text
            margin=1in,               % 1 inch margins
            includemp]{geometry}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% DEFINE THE "bibenum" list using enumitem package
%%% Need to modify this such that "bibenum" gives reverse numbering instead
\usepackage[shortlabels]{enumitem}
\usepackage{etaremune}

\makeatletter
\newlength{\bibhang}
\setlength{\bibhang}{1em}
\newlength{\bibsep}
 {\@listi \global\bibsep\itemsep \global\advance\bibsep by\parsep}
\newlist{bibenum}{enumerate}{3}
\setlist[bibenum]{label=[\arabic*],resume,leftmargin={\bibhang+\widthof{[999]}},%
        itemindent=-\bibhang,
        itemsep=\bibsep,parsep=0pt,partopsep=0pt,
        topsep=0pt}
%\let\oldendbibenum\endbibenum
%\def\endbibenum{\oldendbibenum\vspace{-.6\baselineskip}}

\newenvironment{bibenum*}
  {\renewcommand\labelenumi{[\theenumi]}%
   \etaremune[
     topsep=0pt,
     itemsep=\bibsep,
     parsep=0pt,partopsep=0pt,
     itemindent=-\bibhang,
     leftmargin={\bibhang+\widthof{[999]}}]}
  {\endetaremune}

\makeatother
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage{hyperref}

%%% SECTION HEADINGS
\renewcommand{\section}[1]{\pagebreak[3]%
    \vspace{1.3\baselineskip}%
    \phantomsection\addcontentsline{toc}{section}{#1}%
    \noindent\llap{\smash{\parbox[t]{\marginparwidth}{\hyphenpenalty=10000\raggedright #1}}}%
    \vspace{-\baselineskip}\par}

\begin{document}

\section{\textbf{Journal Publications}}

\begin{bibenum}
    \item pub1
    \item pub2
    \item pres1
    \item pres2
\end{bibenum}

\section{\textbf{Reverse order}}

\begin{bibenum*}
    \item pub1
    \item pub2
    \item pres1
    \item pres2
\end{bibenum*}

\end{document}


text:
Q: Keras Tensor Shaping Problems (slicing) add_loss zero suppression loss I implemented an autoencoder which takes as an input real images, the latent space should be an black and white encoding of the states of this image. (it's a boardgame)
I'm trying to create a new loss using the Layer class.
I want to implement the zero suppression loss.
My problem is in the line, where the slicing happens. (line 7 here)
Can anyone help me to solve the slicing problem
class Zero_Suppress(Layer):
    def __init__(self, rate=1e-2):
        super(Zero_Suppress, self).__init__()
        self.rate = rate

    def call(self, inputs):
        loss = K.mean(inputs, axis = [0,1])
        loss = K.mean(loss[:, 1:], axis =1)
        #loss = K.reshape(loss, (-1,1,1))
        self.add_loss(loss * self.rate)
        return inputs

The error code I receive:
ValueError: in user code:

    min_paper.py:17 call  *
        loss = K.mean(loss[:, 1:], axis =1)
    ValueError: Index out of range using input dim 0; input has only 0 dims for '{{node zero__suppress/strided_slice}} = StridedSlice[Index=DT_INT32, T=DT_FLOAT, begin_mask=1, ellipsis_mask=0, end_mask=3, new_axis_mask=0, shrink_axis_mask=0](zero__suppress/Mean, zero__suppress/strided_slice/stack, zero__suppress/strided_slice/stack_1, zero__suppress/strided_slice/stack_2)' with input shapes: [], [2], [2], [2] and with computed input tensors: input[3] = <1 1>.```


text:
Q: Org-mode for emacs: python sessions Emacs 27
Python 3.6
Windows 10
I have an issue working with sessions that causes org-mode to fail exporting.
Here is an illustration as an org-mode ecxerpt:
#+begin_src python :session one :results file
   #return 'filename.png'   --- DNU in session mode
   import numpy as np
   import matplotlib.pyplot as plt
    x = np.arange(-2*np.pi, 2*np.pi, 0.01)
    y = np.sin(x)
    fig = plt.plot(x,y)
    filename = 'filename.png'
    plt.savefig(filename)

    filename
#+end_src

Inside same session:

#+begin_src python :session one :results value
  z = -1
  z
#+end_src

Yet inside same session again:

#+begin_src python :session one :results value
  z = z - 3
  z
#+end_src

The issue is that if I run the first block code it works fine and I get the correct output,  but then when running following 2 block code, it causes org-mode to stall for ever - no error message.
However if I run only the last 2 block codes, everything works as expected.
Any lead on what could be causing the problem would really be appreciated,
Thanks!

A: Sharing my finding and solving.
The issue seems to reside in matplotlib that needs to use the 'Agg' backend.
Org-mode code would look like:
#+begin_src python :session one :exports results  :results file
  import numpy as np
  import matplotlib
  matplotlib.use('Agg')
  import matplotlib.pyplot as plt
  x = np.arange(-2*np.pi, 2*np.pi, 0.01)
  y = np.sin(x)
  fig = plt.plot(x,y, color='red')
  filename = 'filename.png'
  plt.savefig(filename)
  filename
#+end_src

Now, continuing on the same :session one:
#+begin_src python :session one :exports results
  f'The last value of x is: {x[-1]}'
#+end_src

Produces the desired results. Hoping someone will find this helpful.
Thanks


text:
Q: Natural join query - SQL (postgresql) I'm new to SQL and I have the following problem:
Given the following relations from HR:
Employee(Eid, Ename, salary)
Project(Pid, Pname, requiredWorkers)
WorksOn(Eid, Pid)
I want to return the Eids of employees for which all projects on which they work have precisely the same name (given the fact that several projects may have the same name and yet different Pids). I want to only return employees who work on at least one project.
I'm trying this:
SELECT DISTINCT t1.Eid
FROM (Employee NATURAL JOIN WorksOn NATURAL JOIN Project) AS t1, (Employee NATURAL JOIN WorksOn NATURAL JOIN Project) AS t2
EXCEPT
SELECT DISTINCT t1.Eid
FROM (Employee NATURAL JOIN WorksOn NATURAL JOIN Project) AS t1, (Employee NATURAL JOIN WorksOn NATURAL JOIN Project) AS t2
WHERE t1.Pname <> t2.Pname
ORDER BY t1.Eid ASC

without success. Everything I try gives me different errors.
Do you have any idea how can I do it?
Thanks a lot.

A: select e.Eid, e.Ename
from
    Employee e
    inner join
    WorksOn using (Eid)
    inner join
    Project p using (Pid)
group by 1, 2
having count(distinct p.Pname) = 1


text:
Q: Updating a String In Sql I'm looking to update a word in a number of strings for a particular column.
For example;
Update Column A = 'This is a line of text.'
To 'This is a string of text.'

Where Column A might appear a number of times in the DB. Obviously I can just say;
Update
    TABLE
Set
    A = 'This is a string of text.'
Where
    A = 'This is a line of text.'

But I'm curious to a nicer way of doing in, perhaps using regex? Something along the lines of;
Update
    TABLE
Set
    A = [First Part of A] + 'string' + [Second Part of A]
Where
    A = 'This is a line of text.'

A: Use this:
A = REPLACE(A, 'string', 'line') WHERE A LIKE '%line%'


text:
Q: Flutter - Don't override a method to do a super method with the same parameters In my Flutter pubspec.yaml, I updated my lint to 2.0.1 and now the following code gives me a warning

Don't override a method to do a super method with the same parameters

 @override
void dispose() {
  super.dispose();
}

I see this same code frequently used on the net. Is it safe to just remove this code block?

A: Yes, if you are going to leave the method blank, you can remove it and it will not effect your app


text:
Q: Debugging parallel python and SCOOP interactively I have come from a background of debugging mpi4py code interactively such that the python instance experienced by each of the different CPUs is displayed in a different instance of an xterm window. Following the advice at the link below, I have been able to execute my code using a command such as $mpirun -np 4 xterm -e "ipython -i script.py", which I learned from the following source: debugging mpi4py interactively
Executing parallel python code in this manner means that if I insert break points with pdb.set_trace(), bugs in the code that relate to the context of a each single processor become very transparent, and this approach greatly facilitates monkey patching.
I have now moved from mpi4py to SCOOP, and I am wondering if there is any similar way that I can launch the python processors corresponding to different CPUs in different xterm instances? The reason for the switch is because now I am using a python module DEAP, which is designed to work well with SCOOP.
Also I am wondering if the Wakari IPcluster approach can be combined with SCOOP or mpi4py as well?
Note: I added the tag ZeroMQ as I believe that SCOOP is built on top of ZeroMQ.


text:
Q: subset in geom_point SOMETIMES returns full dataset, instead of none I ask the following in the hope that someone might come up with a generic description about the problem.Basically I have no idea whats wrong with my code.
When I run the code below, plot nr. 8 turns out wrong. Specifically the subset in geom_point does not work the way it should. (update: With plot nr. 8 the whole dataset is plottet, instead of only the subset).
If somebody can tell me what the problem is, I'll update this post.
SOdata <-     structure(list(id = 10:55, one = c(7L, 8L, 7L, NA, 7L, 8L, 5L,
7L, 7L, 8L, NA, 10L, 8L, NA, NA, NA, NA, 6L, 5L, 6L, 8L, 4L,
7L, 6L, 9L, 7L, 5L, 6L, 7L, 6L, 5L, 8L, 8L, 7L, 7L, 6L, 6L, 8L,
6L, 8L, 8L, 7L, 7L, 5L, 5L, 8L), two = c(7L, NA, 8L, NA, 10L,
10L, 8L, 9L, 4L, 10L, NA, 10L, 9L, NA, NA, NA, NA, 7L, 8L, 9L,
10L, 9L, 8L, 8L, 8L, 8L, 8L, 9L, 10L, 8L, 8L, 8L, 10L, 9L, 10L,
8L, 9L, 10L, 8L, 8L, 7L, 10L, 8L, 9L, 7L, 9L), three = c(7L,
10L, 7L, NA, 10L, 10L, NA, 10L, NA, NA, NA, NA, 10L, NA, NA,
4L, NA, 7L, 7L, 4L, 10L, 10L, 7L, 4L, 7L, NA, 10L, 4L, 7L, 7L,
7L, 10L, 10L, 7L, 10L, 4L, 10L, 10L, 10L, 4L, 10L, 10L, 10L,
10L, 7L, 10L), four = c(7L, 10L, 4L, NA, 10L, 7L, NA, 7L, NA,
NA, NA, NA, 10L, NA, NA, 4L, NA, 10L, 10L, 7L, 10L, 10L, 7L,
7L, 7L, NA, 10L, 7L, 4L, 10L, 4L, 7L, 10L, 2L, 10L, 4L, 12L,
4L, 7L, 10L, 10L, 12L, 12L, 4L, 7L, 10L), five = c(7L, NA, 6L,
NA, 8L, 8L, 7L, NA, 9L, NA, NA, NA, 9L, NA, NA, NA, NA, 7L, 8L,
NA, NA, 7L, 7L, 4L, NA, NA, NA, NA, 5L, 6L, 5L, 7L, 7L, 6L, 9L,
NA, 10L, 7L, 8L, 5L, 7L, 10L, 7L, 4L, 5L, 10L), six = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("2010-05-25",
"2010-05-27", "2010-06-07"), class = "factor"), seven = c(0.777777777777778,
0.833333333333333, 0.333333333333333, 0.888888888888889, 0.5,
0.888888888888889, 0.777777777777778, 0.722222222222222, 0.277777777777778,
0.611111111111111, 0.722222222222222, 1, 0.888888888888889, 0.722222222222222,
0.555555555555556, NA, 0, 0.666666666666667, 0.666666666666667,
0.833333333333333, 0.833333333333333, 0.833333333333333, 0.833333333333333,
0.722222222222222, 0.833333333333333, 0.888888888888889, 0.666666666666667,
1, 0.777777777777778, 0.722222222222222, 0.5, 0.833333333333333,
0.722222222222222, 0.388888888888889, 0.722222222222222, 1, 0.611111111111111,
0.777777777777778, 0.722222222222222, 0.944444444444444, 0.555555555555556,
0.666666666666667, 0.722222222222222, 0.444444444444444, 0.333333333333333,
0.777777777777778), eight = c(0.666666666666667, 0.333333333333333,
0.833333333333333, 0.666666666666667, 1, 1, 0.833333333333333,
0.166666666666667, 0.833333333333333, 0.833333333333333, 1, 1,
0.666666666666667, 0.666666666666667, 0.333333333333333, 0.5,
0, 0.666666666666667, 0.5, 1, 0.666666666666667, 0.5, 0.666666666666667,
0.666666666666667, 0.666666666666667, 0.333333333333333, 0.333333333333333,
1, 0.666666666666667, 0.833333333333333, 0.666666666666667, 0.666666666666667,
0.5, 0, 0.833333333333333, 1, 0.666666666666667, 0.5, 0.666666666666667,
0.666666666666667, 0.5, 1, 0.833333333333333, 0.666666666666667,
0.833333333333333, 0.666666666666667), nine = c(0.307692307692308,
NA, 0.461538461538462, 0.538461538461538, 1, 0.769230769230769,
0.538461538461538, 0.692307692307692, 0, 0.153846153846154, 0.769230769230769,
NA, 0.461538461538462, NA, NA, NA, NA, 0, 0.615384615384615,
0.615384615384615, 0.769230769230769, 0.384615384615385, 0.846153846153846,
0.923076923076923, 0.615384615384615, 0.692307692307692,     0.0769230769230769,
0.846153846153846, 0.384615384615385, 0.384615384615385, 0.461538461538462,
0.384615384615385, 0.461538461538462, NA, 0.923076923076923,
0.692307692307692, 0.615384615384615, 0.615384615384615, 0.769230769230769,
0.0769230769230769, 0.230769230769231, 0.692307692307692, 0.769230769230769,
0.230769230769231, 0.769230769230769, 0.615384615384615), ten = c(0.875,
0.625, 0.375, 0.75, 0.75, 0.75, 0.625, 0.875, 1, 0.125, 1, NA,
0.625, 0.75, 0.75, 0.375, NA, 0.625, 0.5, 0.75, 0.875, 0.625,
0.875, 0.75, 0.625, 0.875, 0.5, 0.75, 0, 0.5, 0.875, 1, 0.75,
0.125, 0.5, 0.5, 0.5, 0.625, 0.375, 0.625, 0.625, 0.75, 0.875,
0.375, 0, 0.875), elleven = c(1, 0.8, 0.7, 0.9, 0, 1, 0.9, 0.5,
0, 0.8, 0.8, NA, 0.8, NA, NA, 0.8, NA, 0.4, 0.8, 0.5, 1, 0.4,
0.5, 0.9, 0.8, 1, 0.8, 0.5, 0.3, 0.9, 0.2, 1, 0.8, 0.1, 1, 0.8,
0.5, 0.2, 0.7, 0.8, 1, 0.9, 0.6, 0.8, 0.2, 1), twelve = c(0.666666666666667,
NA, 0.133333333333333, 1, 1, 0.8, 0.4, 0.733333333333333, NA,
0.933333333333333, NA, NA, 0.6, 0.533333333333333, NA, 0.533333333333333,
NA, 0, 0.6, 0.533333333333333, 0.733333333333333, 0.6, 0.733333333333333,
0.666666666666667, 0.533333333333333, 0.733333333333333, 0.466666666666667,
0.733333333333333, 1, 0.733333333333333, 0.666666666666667, 0.533333333333333,
NA, 0.533333333333333, 0.6, 0.866666666666667, 0.466666666666667,
0.533333333333333, 0.333333333333333, 0.6, 0.6, 0.866666666666667,
0.666666666666667, 0.6, 0.6, 0.533333333333333)), .Names = c("id",
"one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "elleven", "twelve"), class = "data.frame", row.names = c(NA,
-46L))

iqr <- function(x, ...) {
  qs <- quantile(as.numeric(x), c(0.25, 0.5, 0.75), na.rm = T)
  names(qs) <- c("ymin", "y", "ymax")
  qs
}

magic <- function(y, ...) {
high <- median(SOdata[[y]], na.rm=T)+1.5*sd(SOdata[[y]],na.rm=T)
low <-  median(SOdata[[y]], na.rm=T)-1.5*sd(SOdata[[y]],na.rm=T)
ggplot(SOdata, aes_string(x="six", y=y))+
stat_summary(fun.data="iqr", geom="crossbar", fill="grey", alpha=0.3)+
geom_point(data = SOdata[SOdata[[y]] > high,], position=position_jitter(w=0.1, h=0),col="green", alpha=0.5)+
geom_point(data = SOdata[SOdata[[y]] < low,], position=position_jitter(w=0.1, h=0),col="red", alpha=0.5)+
stat_summary(fun.y=median, geom="point",shape=18 ,size=4, col="orange")
}

for (i in names(SOdata)[-c(1,7)]) {
p<- magic(i)
ggsave(paste("magig_plot_",i,".png",sep=""), plot=p, height=3.5, width=5.5)
}

A: The problem is that when y="eight", then there are no y values above high, so SOdata[SOdata[[y]] > high,] is an empty data set. Apparently giving geom_point an empty data set will make it use the original data set instead, so all points are plotted. A possible solution would be to check for this condition (and same with no points below 'low'), and only add the points when there are points to add.

A: http://github.com/hadley/ggplot2/issues/labels/data#issue/31


text:
Q: Facebook social plugin doesn't working on internet explorer I'm new on facebook developer and i have created a page tab which contains a login using facebook php sdk (works on all browsers), and like button + feed dialog using facebook javascript sdk (works on all browsers -chrome, FF, safari- except IE).
After 4h of research and tests, I have created a simple page test.html which displays a like button. When I opened it directly outside facebook it worked on all browsers except IE. The IE console shows no error message in this page test.
I use IE 11 but when i emulated IE11- the problem is still here.
Note 1 : in the code, i call window.fbAsyncInit and IE doesn't show the alert.
Note 2 : the domain is in https
The entire code of the page test.html :
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

test

A: There were online discussions that IE doesn't support the MIME type value of "application/javascript". I was hoping that at this time and age it should especially with the recent version of IE you are using.
Try changing it to:


text:
Q: Sorting on various fields in a list I have a class called ProviderOfficeData.  It has a lot of fields but the ones I am interested in:
`boolean primary;
String add1;
String add2;
boolean isPrimaryAddress() { return primary; }
String getAddress1() { return add1; }
String getAddress2() { return add2; }`

I want to sort alphabetically but primary (there is only 1) first.  I made the following sort and tried it but the primary was not at the top.  Any idea if there is a problem with the sort?
`public static class sortPrimaryFirst implements Comparator<ProviderOfficeData> {
        @Override
        public int compare(ProviderOfficeData cur, ProviderOfficeData nxt) {
            if (cur.isPrimaryAddress()) {
                return -1;
            }
            String curAdd = cur.getStreetAddress1() + "|" + cur.getStreetAddress2();
            String nxtAdd = nxt.getStreetAddress1() + "|" + nxt.getStreetAddress2();
            return curAdd.compareTo(nxtAdd);
        }
}`

Thanks

A: Since you don't know in which order sorting method will put arguments in Comparator#compare(), your isPrimaryAddress check should involve both of them:
if (cur.isPrimaryAddress() && !nxt.isPrimaryAddress()) {
    return -1;
} else if (!cur.isPrimaryAddress() && nxt.isPrimaryAddress()) {
    return 1;
} else {
    // compare other fields
}

Even if you know exactly, that only one instance with mentioned property exists in entire collection, this particular instance can be cur as well as nxt when compare(cur, nxt) is called.


text:
Q: Flash stream player (tutorial?) I'm working at a radio station in my free time. I host a radio show there and currently were building a new website for the show. There is a audio stream available but there's no flahs player or what so ever, so i decided to build one for the new website. I know a bit about flash, i can create animations etc but i have no knowledge about actionscript... Could someone tell me where i could find a tutorial about this stuff?
This is the content of the asx file from the stream (http://content.streamone.nl/livestream/ne48FnM3kp.asx) :
<ASX version = "3.0">

  <Abstract>Served by StreamOne - Streaming Media Platform</Abstract>
  <Title>Seaport FM</Title>
  <Author>NA</Author>
  <Copyright>Copyright</Copyright>
  <Param NAME="Prebuffer" Value="True" />

  <Entry>
    <Ref href="http://icecast.streamone.nl/ne48FnM3kp" />
    <Title>Seaport FM</Title>
    <Author>NA</Author>
    <Copyright>Copyright</Copyright>
    <Abstract></Abstract>
  </Entry>

</ASX>

I have searched on google etc but i cant find anything i can understand
Greetz, rutgerinc

A: two simple examples.
and reference: flash.media.Video, flash.net.NetConnection and flash.net.NetStream


text:
Q: jQuery.animate() in a for loop I have the following code:
$("." + selectedOption + ":eq(0)").show().animate({
    left: 0 + $(".option1:visible").outerWidth(),
    opacity: 1
}, 700, function() {
    $("." + selectedOption + ":eq(0)").animate({
        top: 0
    }, 700);
});

This works just as I want it to... but I want to repeat this animation numerous times over, each time animating the next "selectedOption", i.e. :eq(1), :eq(2), :eq(3).  So I thought putting the above code within a for loop would work:
for(i = 0; i < 5; i++) {
    //code here
}

When I did it doesn't work.  Any ideas why?
Thanks

A: Instead of the foor loop use https://api.jquery.com/each/ and you will need to change that that :eq()
Or simply add class to the item which you have to animate and remove it after finishing it

A: You need a recursive function. Something like this:
var count = 0;
function animateNextOption() {
  $("." + selectedOption + ":eq(" + count++ + ")").show().animate({
    left: 0 + $(".option1:visible").outerWidth(),
    opacity: 1
  }, 700, animateNextOption);
}
animateNextOption();

A: Try using .queue() , .promise()

var selectedOption = "selectedOption";

$({}).queue("_fx", $.map($("." + selectedOption), function(el) {
  return function(next) {
    return $(el).animate({
      opacity: 1
    }, 700, function() {
      $(this).animate({
        top: 0
      }, 700)
    }).promise().then(next)
  }
})).dequeue("_fx")
.selectedOption {
  position: relative;
  opacity: 0;
  top: 50px;
}

1

2

3


text:
Q: CefSharp get result from existing Javascript function I'm trying to get the result from an existing Javascript function on a local html page, by using CefSharp in a Windows Form application.
The html page source is:
<!DOCTYPE html>

A Paragraph.

My C# code is:
private void ChromeBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
    if (!args.IsLoading)
    {
        string result = RunScriptParamAsync("myFunction").ToString();
    }
}

public string RunScriptParamAsync(string scriptName)
{
    string script = "";
    script = scriptName;
    //script = string.Format("(function myFunction() {{ document.getElementById('demo').innerHTML = \"{0}\"; return 1 + 1; }})();", scriptName);
    chromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
    {
        var response = x.Result;
        if (response.Success && response.Result != null)
        {
            dynamic result = response.Result;
            return ((int)result).ToString();
        }
        else
        {
            return string.Empty;
        }
    });
    return string.Empty;
}

If I use the commented line
//script = string.Format("(function myFunction() {{ document.getElementById('demo').innerHTML = \"{0}\"; return 1 + 1; }})();", scriptName);

then I'm getting the correct result (2), but the idea is to use a Javascript function already existing on a web page.
A breakpoint inside the function reveals this:

I've also tried
chromeBrowser.GetMainFrame().EvaluateScriptAsync(script)

but with same results.
Any ideas?

A: You are getting exactly what you are asking for, a reference to the function.You need to append (); to actually execute the function.
//Will return a IJavascriptCallback, which is effectively a function pointer, which is what you have asked for
await browser.EvaluateScriptAsync("myFunction");

//To execute the function you must append ();
await browser.EvaluateScriptAsync("myFunction();")


text:
Q: Python3 Relative Imports inside a package I realize that there are a lot of questions about this on StackOverflow already, but I find the solutions to be entirely unclear and often contradicting of each other.
I have the following scenario: I am writing a python (Python 3.4) package with the following structure:
mypackage/
    __init__.py (empty file)
    mydir1/
        __init__.py (empty file)
        mymodule1.py
    mydir2/
        __init__.py (empty file)
        mymodule21.py
        mymodule22.py
    mydir3/
        __init__.py (empty file)
        mymodule31.py
        mymodule32.py
    tests/
        __init__.py (empty file)
        test_something_in_mydir1.py
        test_something_in_mydir2.py
        test_something_in_mydir3.py

I want the files within the tests/ directory to contain unit tests of everything inside the package. The problem is that no matter which approach I try, I get this error:
SystemError: Parent module '' not loaded, cannot perform relative import
I should note that I want this to work "out of the box" which means that I do not want to import things using their absolute paths and I do not want to change my path variable. None of these solutions seem very pythonic and its driving me slowly up the wall. Is there really no way to do this?
I've tried a bunch of stuff already, including examples below, but they all seem to produce the same result:
from ..mydir1.mymodule1 import *
from .mypackage.mydir1.mymodule1 import *
from ...mypackage.mydir1.mymodule1 import *

And I've tried overwriting the __all__ variable in each of the __init__.py files as well as doing the imports as shown here: https://docs.python.org/3/reference/import.html#submodules
Can anyone tell me how to structure the imports (for example) in the file test_something_in_mydir1.py in such a way as to have access to all the classes/functions that are found in mymodule1.py for unit testing the package?

A: If test_something_in_mydir1.py contains:
import unittest
from ..mydir1 import mymodule1

class Test1(unittest.TestCase):
    def test1(self):
        self.assertEqual(mymodule1.x,1) # mymodule1 trivially contains x=1

And if the unit tests were launched from the directory containing the package (in this case, C:\Test) using the following command:
py -m unittest discover -v

The tests are discovered and run correctly with relative imports:
C:\Test>tree /f
Folder PATH listing
Volume serial number is CE8B-D448
C:.
└───mypackage
    │   __init__.py
    │
    ├───mydir1
    │       mymodule1.py
    │       __init__.py
    │
    ├───mydir2
    │       mymodule21.py
    │       mymodule22.py
    │       __init__.py
    │
    ├───mydir3
    │       mymodule31.py
    │       mymodule32.py
    │       __init__.py
    │
    └───tests
            test_something_in_mydir1.py
            __init__.py

C:\Test>py -m unittest discover -v
test1 (mypackage.tests.test_something_in_mydir1.Test1) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK


text:
Q: Call method from another component VueJS version 1 I want to call the method from another component in let's say parent component... So, let's say I have notie.vue and there's my method named 'flash' and I want to call that after API request when I get success.
So let's say this is the case: after get API I want to call something like this with parameters ---> notie.success('notification type', 'notification message')
Here's the code:
Props are defined like this
props: {
    type: {
        default: 'info',
        required: false
    },
    content: {
        default: 'This is just demo text',
        required: false
    },
    visible: {
        type: Boolean,
        default: false
    }
}

Here's data
data: function () {
    return {
        show: true
    }
}

Here's method
methods: {
    flash: function () {
        this.show = true;
    }
}

Here's HTML code

Here for example i want to call my notie component
submit: function () {
    this.$http.post('/api/books/add', {
        data: this.data,
    }).then(function (response) {
        // I want to use notie component right here to notice to users.
    }, function (response) {
    });
}

So my question is how can I call flash() after API request on success or error?


text:
Q: using awk script to print last n rows of a text file I need a script to print last n rows of a text file. the text file names and number of rows can be varied and I want to call only script to print last n rows of any text files. I know for first n row I can use NR < n; print but how can I do it for last n row as number of rows can be varied.- thanks

A: There is a unix tool for exactly that purpose, called tail. To get the last 100 rows of file, you would use tail -n 100 file, then use the output directly or pipe it to other programs like awk.

A: To do this natively in awk, you have to remember the lines as you see them:
awk -v n=10 '
    {line[NR]=$0}
    END {for (i=NR-(n-1); i<=NR; i++) print line[i]}
' file

To save memory, we don't need to remember the whole file; use
    {line[NR]=$0; if (NR>n) delete line[NR-n]}

However it is simpler to reverse the file, print the first n lines, and re-reverse the output
tac file | awk -v n=10 'NR <= n' | tac

But using tail is much simpler that all that

A: as an exercise, there is another version trading space vs time to achieve the same
$ awk -v n=10 'NR==FNR{a=NR;next} FNR>(a-n)' file{,}

scan the files first to get the number of lines and use to filter last n rows second time.

A: $ cat file
1
2
3
4

$ cat tst.awk
{ rec[NR % n] = $0 }
END {
    for (i=NR+1+(n<NR?0:n-NR); i<=(NR+n); i++) {
        print rec[i % n]
    }
}

$ awk -v n=2 -f tst.awk file
3
4

The complexity when setting the starting value of i is to accommodate cases where you ask to print more records than exist in the file, e.g.:
$ awk -v n=6 -f tst.awk file
1
2
3
4

A: Give this script a try:
{
  lines[(i=(++i%n))]=$0;
}
END {
  if (NR>=n) {
    linessize=n;
  } else {
    linessize=NR;
    i=0;
  }
  for(j=1;j<=linessize;j++) {
    print lines[(i+j)%n];
  }
}

File is parsed only once.
An array with n elements  only is used to buffer the lines read.
The tests:
$ printf "one line\n2nd line\n" | ./tail-awk.awk -f script.awk -v n=10
one line
2nd line
$ ./tail-awk.awk  -f script.awk -v n=10 <(man bash)
       attempted.  When a process is stopped, the shell immediately executes the next command in the sequence.  It  suffices  to
       place the sequence of commands between parentheses to force it into a subshell, which may be stopped as a unit.

       Array variables may not (yet) be exported.

       There may be only one active coprocess at a time.

GNU Bash-4.1                                            2009 December 29                                                 BASH(1)
$ ./tail-awk.awk -f script.awk -v n=5 /etc/apt/sources.list

deb http://archive.debian.org/debian-archive hamm main

deb ftp://ftp.debian.org/debian squeeze contrib

$


text:
Q: c# propertygrid, how to refresh the specific property? i have question c# propertygrid about refresh item of combobox.
now combobox item is "a","b", then pressed the btn1, i want to visible "1","2","3" in combobox.
first view my source.
public partial class Window1 : Window
{
    private MyObject instance;
    public string[] str = new string[] { "a", "b" };

    public Window1()
    {
        InitializeComponent();
        instance = new MyObject(this);
        this.propertyGrid1.SelectedObject = instance;

    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        str = new string[] { "1", "2", "3" };
    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
        this.propertyGrid1.Refresh();
    }
}

public class MyObject
{

    public Window1 refF;

    public MyObject(Window1 f)
    {
        this.refF = f;
    }

    private string objectName;

    [TypeConverter(typeof(ObjectNameConverter))]
    public string ObjectName
    {
        get {
            return objectName;
        }

        set {
            objectName = value;
        }

    }
}

public class ObjectNameConverter : StringConverter
{
    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true;
    }

    public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        MyObject refMyObject = context.Instance as MyObject;

        return new StandardValuesCollection(refMyObject.refF.str);
    }
}

when btn1 pressed, don't change item.
but i pressed btn2, changed item to my wants.
how can i change to combobox list item automatically not using refresh?
please help me.
thanks.


text:
Q: Как менять класс div по данному событию? Вот есть пример, как по событию менять класс и оставлять только один класс например
 а не стакать их в один класс например
 (как разультат на примере)

A: ну как вариант, используя ваш код


text:
Q: Remove double-quotes from a json_encoded string on the keys I have a json_encoded array which is fine.
I need to strip the double-quotes on all of the keys of the json string on returning it from a function call.
How would I go about doing this and returning it successfully?
Thanks!
I do apologise, here is a snippet of the json code:
{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}

Just to add a little more info:
I will be retrieving the JSON via an AJAX request, so if it would be easier, I am open to ideas in how to do this on the javascript side.

A: EDITED as per anubhava's comment
$str = '{"start_date":"2011-01-01 09:00","end_date":"2011-01-01 10:00","text":"test"}';
$str = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $str);
echo $str;

This certainly works for the above string, although there maybe some edge cases that I haven't thought of for which this will not work. Whether this will suit your purposes depends on how static the format of the string and the elements/values it contains will be.

A: TL;DR: Missing quotes is how Chrome shows it is a JSON object instead of a string. Ensure that you have Header('Content-Type: application/json; charset=UTF8'); in PHP's AJAX response to solve the real problem.
DETAILS:
A common reason for wanting to solve this problem is due to finding this difference while debugging the processing of returned AJAX data.
In my case I saw the difference using Chrome's debugging tools.  When connected to the legacy system, upon success, Chrome showed that there were no quotes shown around keys in the response according to the debugger.  This allowed the object to be immediately treated as an object without using a JSON.parse() call.  Debugging my new AJAX destination, there were quotes shown in the response and variable was a string and not an object.
I finally realized the true issue when I tested the AJAX response externally saw the legacy system actually DID have quotes around the keys.  This was not what the Chrome dev tools showed.
The only difference was that on the legacy system there was a header specifying the content type.  I added this to the new (WordPress) system and the calls were now fully compatible with the original script and the success function could handle the response as an object without any parsing required.  Now I can switch between the legacy and new system without any changes except the destination URL.


text:
Q: How to combine strings to use as php var? While using Advanced Custom Fields for Wordpress I got to call some vars using get_field('my-custom-field');
I got this code which I would like to store in a function:
<img src="<?php the_sub_field('image-1'); ?>">
<?php $target_post = get_sub_field('target-1'); ?>
<?php echo get_the_title($target_post); ?>

All I need to replace inside my function is the -1 to -2, -3, etc. How can I do this?
I have tried this, which does not work:
function imageBlock($fieldID = '1') {
   <img src="<?php the_sub_field('image-$fieldID'); ?>">
   <?php $target_post = get_sub_field('target-$fieldID'); ?>
   <?php echo get_the_title($target_post); ?>
}

How can I pass the fieldID to the get_field('my-custom-field-1'); function?

A: You're trying to pass a variable into a single quoted string which will take the literal $ as part of the string, not the start of a variable. There are two ways to correct this.
Either with;
get_sub_field("target-$fieldID"); // double quotes

or
get_sub_field('target-' . $fieldID); // concat

So your function would be;
function imageBlock($fieldID = '1') {
    ?>
    <img src="<?php the_sub_field("image-$fieldID"); ?>">
    <?php $target_post = get_sub_field("target-$fieldID"); ?>
    <?php
    echo get_the_title($target_post);
}

Having said that, I would split the logic out so that you were just returning the string of HTML like the other functions you're calling;
function imageBlock($fieldID = '1') {
    $sub_field = the_sub_field("image-$fieldID");
    $target_post = get_sub_field("target-$fieldID");
    $the_title = get_the_title($target_post);

    return " $the_title";
}

and you can echo the result, ie;
echo imageBlock(2);


text:
Q: Unable to install PHPUnit and Pear Packages on My Windows System using Xampp When am installing the phpunit below error being displayed
'D:\XAMPP\htdocs\Selenium_Test>pear install phpunit.de/PHPUnit
Attempting to discover channel "phpunit.de"...
Attempting fallback to https instead of http on channel "phpunit.de"...
unknown channel "phpunit.de" in "phpunit.de/PHPUnit"
invalid package name/package file "phpunit.de/PHPUnit"
install failed'

And also for Channel is:
'D:\XAMPP\php>pear channel-discover pear.phpunit.de
Discovering channel pear.phpunit.de over http:// failed with message: channel-ad
d: Cannot open "http://pear.phpunit.de/channel.xml" (File http://pear.phpunit.de
:80/channel.xml not valid (received: HTTP/1.1 410 Gone))
Trying to discover channel pear.phpunit.de over https:// instead
Discovery of channel "pear.phpunit.de" failed (channel-add: Cannot open "https://pear.phpunit.de/channel.xml" (Connection to `pear.phpunit.de:443' failed:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.))'

As soon as possible please help me with this problem.

A: The PEAR installation Method is abbandoned (as described here ).
Follow the instruction for install on windows here.
A simply way is:

*

*Download the phpunit.phar here and save in the current directory folder.

*Make a script files for lauch it: echo @php "%~dp0phpunit.phar" %* > phpunit.cmd

*launch it, as example phpunit --version
Hope this help