text:
Q: specify exact plot location on letter size paper I am using R and I am trying to create a plot with elements that are at exactly locations on an 8.5x11 page. For example, I need a point at .25 inches from the left of the page and .75 inches from the top of the page. When I save the plot to a pdf, the point is close, but not quite where it should be. What setting in par() do I need to adjust to get the points and lines in the right, exact location?
The following code:

pdf(file = "H:/temp/plots/demo.pdf", paper = 'letter', width=8.5, height = 11,
    pagecentre = FALSE)
par(mar = c(0,0,0,0))
par(mai = c(0,0,0,0))
par(mgp = c(0,0,0))
par(oma = c(0,0,0,0))
par(omi = c(0,0,0,0))
par(pin = c(8.5, 11))
par(xaxs = 'i')
par(yaxs = 'i')
par(xpd=TRUE)
par(pty='m')
plot(x=.25, y=10.75, type = 'p', ylab="", yaxt="n", bty="n",
     xlab="", xaxt = "n",
     xlim = c(0,8.5), ylim = c(0,11))
    lines(x=c(.25,.25), y=c(0,11))
    lines(x=c(0,8.5), y=c(10.75,10.75))
dev.off()

Produces a plot with a vertical line, a horizontal line, and point. The lines and the point should cross at .25 inches from the left and .75 inches from the top. It's close, but zooming in and the lines and point are off by fractions of an inch.

A: The main thing is: don't use the paper argument. From ?pdf:

The paper argument sets the '/MediaBox' entry in the file, which defaults to width by height. If it is set to something other than "special", a device region of the specified size is (by default) centred on the rectangle given by the paper size: if either width or height is less than 0.1 or too large to give a total margin of 0.5 inch, it is reset to the corresponding paper dimension minus 0.5.

In other words, if you specify paper there will always be inserted some margin that will mess things up.
Here is a minimal code that should be sufficient, no need to set up everything:
pdf(file="demo.pdf", width=8.5, height=11)
par(mar=c(0,0,0,0), xaxs='i', yaxs='i')
frame()
plot.window(xlim=c(0, 8.5), ylim=c(0, 11))
points(.25, 10.75)
lines(x=c(.25, .25), y=c(0, 11))
lines(x=c(0, 8.5), y=c(10.75, 10.75))
dev.off()


text:
Q: Launching WPF app from UnitTest on TFS starts process but does not launch app I am trying to Launch a WPF App from within a unit test in order for that unit test to carry out tests on the UI.
Executing the test on my local environment works as expected - App is launched, tests are carried out and App is closed. Executing the tests through a TFS build however, seems to do something strange. The Solution builds successfully and tests start but the App never launches. There is a Process running for the App but the UI never makes an appearance.
The server environment is Windows Server 2012 and TFS 2013. The App process runs as a Background Process rather than an App.
Can anyone provide any insight to why my App is not launching properly?

A: Your build agent needs to be running in Interactive mode.
https://msdn.microsoft.com/en-us/library/ms181712.aspx
However, I would recommend against doing UI testing on a build agent. This will drastically slow your build and it will no longer be a quick CI. You should instead use Release Management to deploy your application to a client and execute the tests through that. If you use MS Test as the orchestrator (use Selenium, CUIT, or whatever as the engine) you can associate the test and the results with a Test Case. This gives you some pretty cool reporting capabilities as you can now see UI coverage against builds...
http://nakedalm.com/execute-tests-release-management-visual-studio-2013/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relative import error/maximum recursion depth exceeded with py2exe using matplotlib I am trying to create an .exe-file from a script using py2exe (WinPython 3.4.4 in Windows 7). In this script I am using different backends of the matplotlib package (Version 1.5.2). All of my attempts resulted with the error:

... name = self._resolve_name(name, package, level)
    File "M:\Python\WinPython-32bit-3.4.4.4Qt5b1\python-3.4.4\lib\site-packages\py2exe\mf3.py", line 213, in _resolve_name
      raise ValueError('attempted relative import beyond top-level package')
  ValueError: attempted relative import beyond top-level package

With other packages, that are on the same directory-level as matplotlib, there is no problem. I read all the posts concerning this topic, but couldn't find a solution yet (including pyinstaller). Can anybody help me?
"setup.py":
from distutils.core import setup
import py2exe
import matplotlib

setup(console=['skript.py'],
options={
   "py2exe":{
             "packages":   ['matplotlib.pyplot','matplotlib.backends.backend_pdf'], # List of all the modules you want to import
            }
        },
data_files=matplotlib.get_py2exe_datafiles(),
)

UPDATE
I now installed matplotlib version 2.0.0. I import the packages in my script with
from matplotlib import pyplot, dates
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.ticker import MaxNLocator

Running the script in spyder works well. The error message when using py2exe now changed to:

File "M:\Python\WinPython-32bit-3.4.4.4Qt5b1\python-3.4.4\lib\site-packages\py2exe\hooks.py", line 291, in getattr
      self.__finder.safe_import_hook(renamed, caller=self)
  RuntimeError: maximum recursion depth exceeded

A: I seems you use py2exe the wrong way.
You first need to have a sunning python script that you want to convert to exe, say you call it script01.py.
Then in script01.py do
import matplotlib.pyplot as plt

And then you write a setup.py script to convert sctipy01.py to exe like this, in its most simple form:
from distutils.core import setup
import py2exe

setup(console=['script01.py'])


text:
Q: How to land cleanly in Steep? Most of my jumps with snowboard and skis land harshly (the rider stumbles and the game's g-force meter spikes). Is there anything I can do to ensure a clean landing?
About jumps:

*

*prepare the jump with the Right Trigger and let it
  go exactly before the jump

*When in air you can perform all kinds of rotations -- in this case you need to use the Sticks' axis on your controller (Up, Down, left,
  Right or Diagonal).

*if you want to grab your board in the air, you need to use the Left Trigger for your left hand and the Right Trigger for your
  right one

*while grabbing the board you can rotate the Right Stick and add even more style to your tricks.

http://www.gameskinny.com/cy9fx/steep-beginners-guide-tips-and-tricks-for-conquering-the-slopes

A: In Steep there are a few things that can help you get cleaner landings when getting air.
The first and most important thing to know is that when you let go of your grabs helps with your landing. If you hold your grab until you almost hit the ground you will have a better chance of having a clean landing than if you let go of your grab mid jump. This is because of the falling animation that your character will perform when jumping a long distance. If you get this animation to occur you will most likely have a harsher landing.
Also it is of course important to make sure when you are going in for your landing you try and get your board as close to parallel to the ground as possible. The farther you are away from having your board in a parallel position to the ground the higher the chance of you taking a harsh landing and losing G's on your gauge.
The last and probably most obvious tip for better landings, don't jump off cliffs or land on rocks. I say this should be obvious if you since jumping 500 feet to the ground or landing on some rocky patch on a mountain is never going to give you a smooth landing. You might get lucky if you hold your board until you nearly land, make your board parallel to the ground, and land on snow after a large jump, but massive jumps are extremely difficult to perform cleanly so don't expect them that often. Landing on rocks of course is bad and pretty much always a harsh landing, you may be able to squeeze out a clean landing every once and awhile but don't bet on it.
Hope these tips help.

A: Let go of the left stick so you can land "cleaner" but it mostly depends on the angle of the board and the ground below you.


text:
Q: FB Comments fed code Is there another link to the page "https://developers.facebook.com/tools/comments"
This page doesn't work and comes up with a 500 error.
I am looking to be the moderator to edit posts and approve them. Is this broken page where I need to go for this?

A: The page was showing up as blank for me as well. I had to have administrator role in the facebook app, not just developer.


text:
Q: why is ubuntu incorrectly detecting my graphics card? So in my ubuntu I was using the latest mesa drivers from the ppa. I also had the amdgpu and radeon xorg drivers installed. I was running a 16.04 gnome version of ubuntu. Maybe I am reading the terminal output wrong also, but my r9 390 has 8GB of memory and ubuntu doesnt seem to be reporting that.
ubuntu is not installed at the moment since I had to reinstall windows to make sure it just wasnt some issue with the card I never noticed.
why does my card show up as a 290 in linux (incorrect) and a 390 in windows (correct)?

A: You can first update the PCI ID database on Ubuntu by running sudo update-pciids in a terminal to see if this helps to correct the name.
From the latest database snapshot:
1002  Advanced Micro Devices, Inc. [AMD/ATI]
    67b0  Hawaii XT [Radeon R9 290X]
        1043 046a  R9 290X DirectCU II
        1043 046c  R9 290X DirectCU II OC
        1043 0474  Matrix R9 290X Platinum
        1043 0476  ARES III
        1458 227c  R9 290X WindForce 3X OC
        1458 2281  R9 290X WindForce 3X OC
        1458 228c  R9 290X WindForce 3X
        1458 228d  R9 290X WindForce 3X OC
        1458 2290  R9 290X WindForce 3X
        1458 22c1  Grenada PRO [Radeon R9 390]

It looks like that the Radeon R9 390 is only specific to a card with 1458 22c1 as its subclass ID, you can check the ID of your card with lspci -nnv
This lookup table is maintained by the community, if the information is not correct, you can make changes here: http://pci-ids.ucw.cz/


text:
Q: Как ограничить ViewPager чтоб листать только вправо? Можно ли как-то ограничить возможность пролистывания в одну из сторон? Нужно дать юзеру возможность листать только вправо, допустим.

A: Вам нужно переопределить пару методов во ViewPager:
Для начала, создайте enum, который будет определять, в каком направлении ViewPager может работать:
public enum SwipeDirection {
    all, left, right, none ;
}

Теперь к самому ViewPager:
public class CustomViewPager extends ViewPager {

    private float initialXValue;
    private SwipeDirection direction;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.direction = SwipeDirection.all; //поумолчанию разрешить листание в любом направлении
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (this.IsSwipeAllowed(event)) {
            return super.onInterceptTouchEvent(event);
        }

        return false;
    }

    private boolean IsSwipeAllowed(MotionEvent event) {
        if(this.direction == SwipeDirection.all) //Усли разрешено все
            return true;

        if(direction == SwipeDirection.none ) //если листание запрещено
            return false;

        //запоминаем начальную позицию тач ивента
        if(event.getAction()==MotionEvent.ACTION_DOWN) {
            initialXValue = event.getX();
            return true;
        }

        //рассчитываем направление свайпа, и запрещаем\разрешаем его
        if(event.getAction()==MotionEvent.ACTION_MOVE) {
            try {
                float diffX = event.getX() - initialXValue;
                if (diffX > 0 && direction == SwipeDirection.right ) {
                    // свайп влево запрещен
                    return false;
                }else if (diffX < 0 && direction == SwipeDirection.left ) {
                    // свайп вправо запрещен
                    return false;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        return true;
    }

    public void setAllowedSwipeDirection(SwipeDirection direction) {
        this.direction = direction;
    }
}

Теперь добавляем его в разметку вместо обычного ViewPager
<тут_ваш_пакедж.CustomViewPager
     android:id="@+id/customViewPager"
     android:layout_height="match_parent"
     android:layout_width="match_parent" />

И теперь в коде выставляем разрешение/запрет на свайп:
mViewPager.setAllowedSwipeDirection(SwipeDirection.right);

Так будет свайпать только вправо.

A: подвесить к нему OnPageChangeListener, и следить что бы новое значение не оказалось больше (или меньше) текущего

A: Можно попробовать переопределить метод performDrag класса ViewPager:
private boolean performDrag(float x) {
    boolean needsInvalidate = false;

    final float deltaX = mLastMotionX - x;
    mLastMotionX = x;

    // начало нового кода
    if (deltaX < 0) {
        return false;
    }
    // окончание нового кода

    float oldScrollX = getScrollX();
    ...

}


text:
Q: mySQL responses "array" at PHP page (PDO) I have mySQL Database. I'm making request inside of it.
SELECT proc from an_vac WHERE   publ=1

Result is 48.
Now I have to display Request result (unique value) at the webpage (I'm using PDO connection).
I request:
<?php $result = $db->select("SELECT proc from an_vac WHERE  publ=1");
$value=$result[0];
echo    $value; ?>

Result is array.
What's wrong from my side?

A: You are using some sort of wrapper for working with MySQL, since $db->select(...) is not part of PHP or its default extensions. But I can guess that $result is an array of rows, and each row is an array of row values by column name. Replace $value=$result[0]; with:
$value=$result[0]['proc'];

A: Perhaps this will work better:
$proc = getProc();

function getProc() {
    try {
        $db = new PDO("mysql:host=192.168.0.1;charset=utf8", "username", "password");
        $cmd = $db->prepare("
            SELECT proc from an_vac WHERE  publ=1;
        ");
        $cmd->execute();
        $result = $cmd->fetch();
        return $result[0];
    } catch (Exception $e) { echo $e->getMessage(); return; }
}


text:
Q: Using VLookup or Index/Match from two tabs in excel I wanted to perform the following using a VLOOKUP:

*

*If value in column E (MMA Uploader sheet tab) is found in column B (MMA Product List sheet tab)...

*Paste value of column A (MMA Product List sheet tab) into column D (MMA Uploader sheet tab)

Here is a visual example:

*

*MMA Uploader tab:

*

*MMA Product List tab:

*

*Places appropriate ID (in MMA Uploader tab) since VLOOKUP has found a matching name:

This is what I have so far with my VLOOKUP function (testing it in cell D2 of the MMA Uploader tab):
=IFERROR(VLOOKUP("*"&E2&"*",'MMA Product List'!$A:$B,1,FALSE), "N/A")

This is what I have so far with my INDEX MATCH function (testing it in cell D2 of the MMA Uploader tab):
=IFERROR(INDEX('MMA Product List'!$A:$A,MATCH("*"&E3&"*", 'MMA Product List'!$B:$B,0)), "N/A")

Neither of the functions I wrote above result in a value, they both return #N/A.
As always, thank you for your help!

A: If you're using VBA, you can use Range.Find and work with the sheet objects directly, instead of going through formulas to retrieve values.
Here is an example of a simple loop through column E, using Range.Find to look in the other sheet's column B and copy over values:
Dim wsUp As Worksheet
Set wsUp = Sheets("MMA Uploader")

Dim wsPL As Worksheet
Set wsPL = Sheets("MMA Product List")

'Finding the last non-blank cell in Uploader Column E
Dim LastRow As Long
LastRow = wsUp.Cells(wsUp.Rows.Count, 5).End(xlUp).Row

'Loop though Uploader Column E from row 2 till the last non-blank cell
Dim i As Long
For i = 2 To LastRow
  Dim rFind As Range
  'Looking in Product List column B for each value of Uploader column E
  Set rFind = wsPL.Columns(2).Find(what:=wsUp.Cells(i, 5), LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True)

  'If a value is found, then copy from column A into Uploader column D
  If Not rFind Is Nothing Then
    wsUp.Cells(i, 4).Value = rFind.Offset(0, -1).Value
  End If
Next i


text:
Q: Deleting files smaller than a certain size with batch Is there any way to delete all files in a specific folder that are smaller than x MB using a batch file? I looked at the forfiles command, but it seems like with it you can only delete files that are older than x days.

A: This is possible by using a for /f statement. The below script will all delete files below 100KB (100,000 bytes) Try this:
@echo off
setlocal
:: Size is in bytes
set "min.size=100000"

for /f  "usebackq delims=;" %%A in (`dir /b /A:-D *.*`) do If %%~zA LSS %min.size% del "%%A"


text:
Q: How to make property value serialize nested into element named after property? I want to be able to serialize
class A {
   Base Prop{ get; set; }
}
class B:Base { [XmlText] string Foo {get;set; }
class C:Base { [XmlText] string Bar {get;set; }

to

  <Prop>
    blah
  </Prop>

However, the default behavior gives me

  <Prop xsi:type="B">blah</Prop>

So basically, I want to discriminate type of the property's value by nesting an element instead of using xsi:type.
Is it possible to do with XML serialization attributes, or do I have to resort to IXmlSerializable?


text:
Q: What's the convention to define backbone models class properties/fields I want to define which properties a class has. We use backbone for OOP. I've read that backbone model gets its properties when initialized, and only methods are defined for the class using extend. But I think that having explicitly defined class fields adds to readability. Is there some convention on how to do that?

A: From the fine manual:

extend Backbone.Model.extend(properties, [classProperties])
  [...] as well as optional classProperties to be attached directly to the constructor function.

Similarly for collections, routers, and views.
To define a class method on a model:
var M = Backbone.Model.extend({
    // instances methods and properties go here...
}, {
    some_class_method: function() { ... }
});

M.some_class_method(); // Then this will work.

A: Backbone models hold data in the attributes key so
model = new Backbone.Model({foo:'bar'});
model.attributes.foo === 'bar';

and you should access data with model.get() model.set() which will manage events firing.
you can also hook into Backbone models creations using initilize method or by rewriting constructor (you may look at MarionetteJS views for an inspiration).


text:
Q: Is there any metaprogramming patterns catalog for Python? I have just read Python Cookbook. The book is amazing.
I think the best use of this book is that it provides lots of examples that show python in real problem applications. Many of the idioms include metaprogramming techniques.
I wonder if there is any catalog that summarizes metaprogramming idioms in Python?
Python Cookbook is very rich in examples and techniques. But I think there is also a need for a pattern catalog that gives specific names for each technique and that abstracts the main features of the solution technique from the concrete application area as the Design Patterns book of Gang of Four does.

A: *

*A Primer on Python Metaclass Programming.

*http://www.ibm.com/developerworks/linux/library/l-pymeta.html


text:
Q: How can I create a directory in a directory getting its name as input? If for example I get as input filename and dirname and I want to create new directory with name filename at dirname.
How can I do it?
I tried to do it with mkdir but it's creates the directory only in the current directory (and doesn't allow me to choose how to create the new directory).

A: Not sure fully if you are looking for this, you could try it and let me know if this helps you.
cat script.ksh
filename="$1"
directory="$2"

if [ ! -d "$directory" ]
then
        mkdir -p "$directory/$filename"
else
        echo "There seems to be directory already present, please enter some other directory name."
fi

From man mkdir:

   -p, --parents
          no error if existing, make parent directories as needed


text:
Q: Numerical solution of a singular integral equation I am looking to approximate the solution u of the following equation using discretization method or any other idea. Is there any way on how to find a numerical solution for it:
u[t]-Integrate[Abs[t - s]^(-1/2)*u[s], {s, 0, 1}] == 1/3 (-2 Sqrt[1 - t]+3t-4 Sqrt[1-t]t-4t^(3/2)) where 0<t<1.
The solution is u[x]=x but I am assuming that I dont know the answer and we need to find approximation for it.

A: Not an answer, only an idea to solve the problem.
I tried to solve your integral equation iterativ  using NestList:
sol = NestList[
Function[fu,
FunctionInterpolation[
 1/3 (-2 Sqrt[1 - t] + 3 t - 4 t Sqrt[1 - t] - 4 t^(3/2)) +
  NIntegrate[fu[s]/Sqrt[Sqrt[(t - s)^2]] , {s, 0, 1},
   Method -> "LocalAdaptive" ], {t, 0, 1 }]
] , 0 &,  (* initial function *)5];

Unfortunately the Picarditeration doesn't converge in your case:
    Plot[Map[#[t] &, sol], {t, 0, 1}

Perhaps you have additional system knowhow to force a convergent iteration?

A: I will add another method that is not as accurate as method @Roman, but faster.  It uses expression describing the integral Integrate[1/Sqrt[Abs[t-s]], {s, 0, 1}]
ker[s_, t_] := If[t > s, -2*Sqrt[t - s], 2*Sqrt[s - t]]

Then everything is as usual
np = 51; points = fun = Table[Null, {np}];
Table[points[[i]] = i/np, {i, np}];
sol = Unique[] & /@ points;

Do[fun[[i]] =
   1/3 (-2 Sqrt[1 - t] + 3 t - 4 Sqrt[1 - t] t - 4 t^(3/2)) /.
    t -> points[[i]], {i, np}];

sol1 = sol /.
   First@Solve[
     Table[sol[[j]] -
        Sum[.5*(sol[[i]] +
            sol[[i + 1]])*(ker[points[[i + 1]], points[[j]]] -
            ker[points[[i]], points[[j]]]), {i, 1, np - 1}] ==
       fun[[j]], {j, 1, np}], sol];

u = Transpose[{points, sol1}];

Show[Plot[t, {t, 0, 1}], ListPlot[u]]

A: Here's a general solution that works by interpolation. I'll present the method in a very slow way, and we can work on speeding it up later on if desired.
First, we make an ansatz for the function $u(t)$ on the interval $[0,1]$. Here I use a grid of $n+1$ equidistant points and a linear interpolation scheme:
n = 10;
tvalues = Subdivide[n];
uvalues = Unique[] & /@ tvalues;  (* we don't care what these variables are called *)
tupairs = Transpose[{tvalues, uvalues}];
u[t_] = Piecewise@BlockMap[{((t-#[[2,1]])#[[1,2]]-(t-#[[1,1]])#[[2,2]])/(#[[1, 1]]-#[[2, 1]]),
          #[[1,1]]<=t<=#[[2,1]]}&, tupairs, 2, 1]

Check that this interpolation scheme has indeed the values uvalues on the grid points tvalues:
u /@ tvalues == uvalues
(* True *)

Define the integral $\int_0^1 ds\,u(s)/\sqrt{\lvert t-s\rvert}$:
uint[t_] := Integrate[u[s]/Sqrt[Abs[t-s]], {s, 0, 1}]

Evaluate this integral on the same grid of tvalues: here is the slow part of this calculation, and could probably be sped up dramatically,
uintvalues = uint /@ tvalues
(* long output where every element is a linear combination of the uvalues *)

The right-hand side of the integral equation, evaluated on the same grid of tvalues:
f[t_] = 1/3 (-2 Sqrt[1 - t] + 3 t - 4 Sqrt[1 - t] t - 4 t^(3/2));
fvalues = f /@ tvalues
(* long output *)

Solve for the coefficients of $u(t)$: a linear system of equations for the grid values uvalues, found by setting the left and right sides of the integral equation equal at every grid point in tvalues,
solution = tupairs /.
  First@Solve[Thread[uvalues - uintvalues == fvalues] // N, uvalues]

{{0, 5.84947*10^-16}, {1/10, 0.1}, {1/5, 0.2}, {3/10, 0.3}, {2/5, 0.4}, {1/2, 0.5}, {3/5, 0.6}, {7/10, 0.7}, {4/5, 0.8}, {9/10, 0.9}, {1, 1.}}

This confirms your analytic solution $u(t)=t$ but is much more general.
You don't need the // N in the last step if you prefer an analytic solution; however, numerical solution is very much faster.
ListLinePlot[solution, PlotMarkers -> Automatic]

Update: much faster version
To speed up this algorithm, the main point is to speed up the calculation of the uintvalues from the uvalues. Instead of doing piecewise integrals, this calculation can be expressed as a matrix multiplication, uintvalues == X.uvalues, with the matrix X defined as
n = 10;
X = N[4/(3 Sqrt[n])]*
  SparseArray[{{1,1} -> 1.,
               {-1,-1} -> 1.,
               Band[{2,2}, {-2,-2}] -> 2.,
               Band[{2,1}, {-1,1}, {1,0}] ->
                 N@Table[(i-2)^(3/2)-(i-1)^(3/2)+3/2*(i-1)^(1/2), {i,2,n+1}],
               Band[{1,-1}, {-2,-1}, {1,0}] -> N@Reverse@Table[(i-2)^(3/2)-(i-1)^(3/2)+3/2*(i-1)^(1/2), {i,2,n+1}],
               Sequence @@ Table[Band[{1,a}, {1+n-a,n}] -> N[a^(3/2)-2*(a-1)^(3/2)+(a-2)^(3/2)], {a,2,n}],
               Sequence @@ Table[Band[{a+1,2}, {n+1,n+2-a}] -> N[a^(3/2)-2(a-1)^(3/2)+(a-2)^(3/2)], {a,2,n}]},
              {n+1, n+1}] // Normal;

(The coefficients follow from the Piecewise ansatz and analytic integration.)
With this matrix defined, the algorithm becomes simply
tvalues = Subdivide[n];
f[t_] = 1/3 (-2 Sqrt[1 - t] + 3 t - 4 Sqrt[1 - t] t - 4 t^(3/2));
fvalues = f /@ tvalues;
solution = Inverse[IdentityMatrix[n+1] - X].fvalues
ListLinePlot[Transpose[{tvalues, solution}]]

In this way, $n=1000$ grid points can be achieved in a few seconds, most of which is still spent in assembling the X-matrix. The next step would be to write down a faster way of assembling X.


text:
Q: datagrid lost connection with DataSource after datatable.copy I have two datatable
 DataTable dt = new DataTable();
 DataTable dt1 = new DataTable();

then I add data to "dt" datatable and set it as source for datagridview
        dt.Columns.Add("id", typeof(int));
        dt.Columns.Add("name", typeof(string));

        dt.Rows.Add(1, "One");
        dt.Rows.Add(2, "Two");
        dt.Rows.Add(3, "Three");
        dataGridView1.DataSource =dt;

then i copy dt to dt1 and clear data in dt
        dt1 = dt.Copy();
        dt.Clear();

now after copy back dt1 to dt the datagrid lost the source:
dt = dt1.Copy();

the datagrid now showing nothing  even though dt had data,but when reassign datagrid to dt again the data show up
 dataGridView1.DataSource =dt;

My question here why datagrid lost source after copying and is there a way to copy from data table without reassigning datasource

A: I suppose it is because DataTable.Copy does return a new instance of DataTable.
So when you do this: "dt = dt1.Copy()" you are actually replacing dt with a new reference.
Your datagrid however still uses the old reference of "dt" (they are completely different objects now, where the "old" one was just cleared by you...hence no data).
Update (after "is there a way" comment): yes there is. MSDN is your friend. Did not know that off the top of my head either. DataTable.Merge does what you want (probably - cause we do not know what you want hehe)


text:
Q: SSRS - Why the sub-report is printed multiple times? I'm new to SSRS and know little about groupings in SSRS.
I've an order confirmation report. The report has two groups (orderHead and orderLines). I've added a table row at the bottom of the report to contain a sub-report (that must run for some clients). This sub-report is not part of the grouping, but just sit at the bottom of the table.

The problem I'm facing is that if the order has multiple lines, this sub-report is printed as many times as the order lines. How can I restrict it to print exactly once?

A: If you don't want the subreport to print for each detail item, move it out of the detail group. I'd think you'd want it as a report footer, or possibly on the footer for group 1.


text:
Q: How to position images in CSS I'm not sure how to describe exactly what I am asking, basically I need to align the image to the left however in from the left by 6px (line 38, margin: 10px 10px 10px 6px).
Code is as follows:

.rounded {
 width:100%;
 height:100px;
 background-color:#95b7fd;
 border-radius:100px;
 z-index:0;
}

.rounded-input {
 margin-top:5px;
 width:90px;
 height:90px;
 border-radius:100px;
 border:0;
 margin-left:-80px;
 font-weight:700;
 background-color:#fff;
}

.rounded-box {
 width:98.4%;
 height:90px;
 border-radius:100px;
 border:0;
 background-color:#3574f9;
 opacity:1;
 text-align:center;
 color:#FFF;
 margin-left:auto;
 margin-right:auto;
}

.icon {
 height:80px;
 width:auto;
 position:absolute;
 border-radius:100px;
 margin:10px 10px 10px 6px;
}

  <title>LsrW's Go2 Links</title>
  <link href="css/style.css" rel="stylesheet" type="text/css">

   <form method="get" action="http://www.google.co.uk/search" class="rounded">

     <input name="q" maxlength="255" class="rounded-box"><input value="Search" type="submit" class="rounded-input">
   </form>
   <form method="get" action="http://www.google.co.uk/search" class="rounded">

     <input name="q" maxlength="255" class="rounded-box"><input value="Search" type="submit" class="rounded-input">
   </form>

Preview the issue here: link (http://lsrw.co.uk/slider/).
As you can see in the link (or if you preview the code, which may or may not display correctly anyway depending on the size of the window), the first search box works correctly with the image on the left, however the second does not.
Anyone have any ideas how you would fix this? (additional: I am open to suggestions of how to improve much of this, I'm relatively new to CSS).
Thanks,
- Luke
EDIT: This was pretty simple to fix, sorry for the dumb question- I had completely forgotten that I had added a  tag, closing that within the form fixed it completely.

A: The problem is that both  tags are not closed. This leads to undefined behaviour.
Try to close both center tags:
        <form method="get" action="http://www.google.co.uk/search" class="rounded">

                <input name="q" maxlength="255" class="rounded-box"><input value="Search" type="submit" class="rounded-input">

        </form>
        <form method="get" action="http://www.google.co.uk/search" class="rounded">

                <input name="q" maxlength="255" class="rounded-box"><input value="Search" type="submit" class="rounded-input">

        </form>


text:
Q: How to use a socks 5 proxy in socket.io I'm trying to use a socks 5 proxy in a socket.io node.js client, and i already tried this:
var io = require('socket.io-client')

var SocksProxyAgent = require('socks-proxy-agent');
var agent = new SocksProxyAgent('socks5://165.227.174.249:33080');

const socket = io('http://localhost:3000', {agent: agent})

socket.on('connect',() => {
console.log('connected')
})

and it just hang up and did nothing.
Any ideas of why?


text:
Q: Optimizing a box I'm learning the use of derivatives and I have found a problem:

Supposing we want to build a box of $4000\, \textrm{cm}^3$ of volume without
  top and a square base. Which are the measures so we can use less material?

I have no idea where to start :C, Any hint would be appreciated, thank you.

A: Since the base is square, there are two important dimensions: the length of each side of the base, which I'll call $x$, and the height, which I'll call $y$. The volume of the box is $x^2y$, and we know that this is $4000$, so we have the equation $x^2y=4000$. That equation completely determines the relationship between $x$ and $y$: if we know one, we can use the equation to find the other.
The amount of material used is the area of the base together with the combined areas of the four upright sides; that's $x^2+4xy$, and we want to choose $x$ and $y$ to minimize this. At this point we want to get rid of one of the variables $x$ and $y$, so that we have the area in terms of just one of them and can apply standard elementary calculus techniques to find the minimum. It's easier to solve $x^2y=4000$ for $y$ than to solve it for $x$, so we'll do that: $y=\dfrac{4000}{x^2}$. Now we can write the area (amount of material) as a function of $x$ alone:
$$A(x)=x^2+4xy=x^2+\frac{4x\cdot4000}{x^2}=x^2+\frac{16000}x\;.$$
At this point you can apply the usual technique of finding a critical point of $A(x)=x^2+\dfrac{16000}x$ and making sure that it's a minimum. That will give you the right value of $x$, and from that you can get the associated value of $y$.

A: There is a short cut here: If you had two such boxes, you could put one (inverted) on top of the other, to make a closed box with volume $8000$cm$^3$. The closed box with minimum surface area is a cube, with surface area $6 \times 20^2 = 2400$ cm$^2$. So we need $1200$cm$^2$ for each open box.


text:
Q: Least squares regression with variance-covariance matrix of observations I'm trying to fit a model of the form $Y=aX+b$ based on a number of $(X,Y)$ observations with non-independent errors in $Y$. I know the variance-covariance matrix of the errors on $Y$.

*

*How can I compute best-fit parameters $(a,b)$ and their var-cov matrix?

*Can a least squares regression take non-independent errors into account?

*Is there a more classical method to solve this kind of problem?

A: $\newcommand{\e}{\varepsilon}$Let $Y = X\beta + \e$ where $\e \sim \mathcal N(0, \Omega)$ with $\Omega$ known. Assume that $\Omega$ is not singular. Then there exists a matrix $L$ such that $L = \Omega^{-1/2}$ and we can multiply through our equation by $L$ to get
$$
LY = LX\beta + L\e
$$
and now $L\e \sim \mathcal N(0,I)$. Because we're left multiplying we're not changing $\beta$.
Since our errors are now iid we can happily apply the usual OLS procedure to get
$$
\hat \beta = \left((LX)^T(LX)\right)^{-1}(LX)^T(LY) = (X^T \Omega^{-1} X)^{-1}X^T \Omega^{-1} Y.
$$
This is generalized least squares. This answer covers exactly the point estimation of $\hat \beta$ but didn't seem to have the variance so I'll derive that next.
Because we are not estimating $\Omega$ we have
$$
E(\hat \beta) = (X^T \Omega^{-1} X)^{-1}X^T \Omega^{-1} X \beta = \beta
$$
and
$$
Var(\hat \beta) = \left((X^T \Omega^{-1} X)^{-1}X^T \Omega^{-1}\right)Var(Y)\left((X^T \Omega^{-1} X)^{-1}X^T \Omega^{-1}\right)
$$
$$
= (X^T \Omega^{-1} X)^{-1}
$$
so all together
$$
\hat \beta \sim \mathcal N\left(\beta, (X^T \Omega^{-1} X)^{-1} \right)
$$
since $\hat \beta$ is still a linear transformation of a Gaussian RV (i.e. $Y$).
Often GLS is done with $\Omega = \sigma^2 V$ where $V$ is known but $\sigma$ isn't, but here I've assumed the entire thing is known exactly.


text:
Q: Is there a more elegant way to read four bytes from a ByteBuffer and treat each byte as a char Is there a more elegant way to read four bytes from a ByteBuffer and treat each byte as a char (rather than each pair as a char) then this, Im sure there must be a more succint way.
public static String read4Chars(ByteBuffer bytes) throws IOException
    {
        StringBuffer sbuf = new StringBuffer(4);
        for (int i = 0; i < 4; i++) {
            char ch = (char) bytes.get();
            sbuf.append(ch);
        }
        return sbuf.toString();
    }

A: Elegance is quite subjective. You could try that:
public static String read4Chars(ByteBuffer bytes) throws IOException {
    byte[] b = new byte[4];
    bytes.get(b);
    return new String(b, Charset.forName("ASCII"));
}

A: If you don't have to "consume" the bytes from the buffer, you coud try:
public static String read4Chars(ByteBuffer bytes) throws IOException {
    byte[] array = bytes.array();
    return String.valueOf((char) array[0])
        + (char) array[0] + (char) array[0] + (char) array[0];
}


text:
Q: Proving $q\Rightarrow r \models (p\land q) \Rightarrow (p \land r)$ using only natural deduction. I'm trying to prove
$$q\Rightarrow r \models (p\land q) \Rightarrow (p \land r)$$
using only the natural deduction rules in this handout.
Any hints? I am not allowed to do transformational stuff, such as converting everything to CNF or DeMorgan's, unless they are proven. (I'm sure that will make things easier!).

A: $(1)\; q\rightarrow r \quad\text{premise}$

*

*$(2)\; p\land q\quad\text{Assumption}$

*

*$(3)\; p \quad\text{Conjunction Elimination}, (2)$

*$(4)\; q\quad \text{Conjunction Elimination}, (2)$

*$(5)\; r \quad \text{Modus Ponens}, (1), (4)$

*$(6)\; p\land r\quad \text{Conjunction Introduction}, (3),(5)$
$(7) \;(p \land q) \rightarrow (p\land r) \quad\text{Conditional Introduction}, (2 - 6)$
Remark:
Note that when the proposition you are asked to prove is an implication, that's almost always a sign-post that, after listing the premise(s), you'll want to begin with a sub-proof, led off by the assumption of the antecedent, with the aim of arriving at the consequent.

A: The main question here has already been answered, but in the comments you asked for natural deduction proofs of DeMorgan's laws.  I've used the rules cited in the question with two exceptions.  I'm using Fitch-style disjunction elimination ($\lor E$) and biconditional introduction ($\leftrightarrow I$) rules.
The $\leftrightarrow I$ is a trivial difference;  I cite the subproofs that start with $\phi$ and $\psi$ and end with $\psi$ and $\phi$, respectively, instead of deriving $\phi \to \psi$ and $\psi\to\phi$ individually and citing them.
The $\lor E$ is more significant.  Disjunctive syllogism ($\lnot P, P \lor Q / Q$) is perfectly valid rule, but it's not typically taken as the elimination rule for disjunction in natural deduction systems.  In the tradition of Gentzen, many natural deduction systems have an introduction and an elimination rule for each connective.  For disjunction, the introduction rule is actually pair of rules which state that from either disjunct you may infer the disjunction:
$$
\begin{array}{c} \phi \\ \hline \phi \lor \psi \end{array}\lor I_L \qquad
\begin{array}{c} \psi \\ \hline \phi \lor \psi \end{array}\lor I_R \qquad
$$
Disjunction elimination is a bit more complicated.  It says that if $\rho$ is derivable from both $\phi$ and from $\psi$ and $\phi\lor\psi$ holds, then so does $\rho$ (and the assumptions are discharged). It captures proof by case reasoning.
$$
\begin{array}{ccc}
 & [\phi] & [\psi] \\
 & \vdots & \vdots \\
\phi\lor\psi & \rho & \rho \\
\hline
& \rho
\end{array}\lor E
$$
Here is $(\lnot p \land \lnot q) \leftrightarrow \lnot(p \lor q)$:

*

*
*

*$\lnot(p \lor q)$ Assume.

*
*

*
*

*$p$ Assume.

*
*

*
*

*$p \lor q$ by $\lor I$ from 2.

*
*

*
*

*$\mathbf{false}$ by $\lnot E$ from 1 and 3.

*
*

*$\lnot p$ by $\lnot I$ from 2–4.

*
*

*
*

*$q$ Assume.

*
*

*
*

*$p \lor q$ by $\lor I$ from 6.

*
*

*
*

*$\mathbf{false}$ by $\lnot E$ from 1 and 7.

*
*

*$\lnot q$ by $\lnot I$ by 6–8.

*
*

*$\lnot p \land \lnot q$ by $\land I$ from 5 and 9.

*
*

*$\lnot p \land \lnot q$ Assume.

*
*

*
*

*$p \lor q$ Assume.

*
*

*
*

*
*

*$p$ Assume.

*
*

*
*

*
*

*$\lnot p$ by $\land E$ from 11.

*
*

*
*

*
*

*$\mathbf{false}$ by $\lnot E$ from 13 and 14.

*
*

*
*

*
*

*$q$ Assume.

*
*

*
*

*
*

*$\lnot q$ by $\land E$ from 11.

*
*

*
*

*
*

*$\mathbf{false}$ by $\lnot E$ from 16 and 17.

*
*

*
*

*$\mathbf{false}$ by $\lor E$ from 12, 13–15, and 16–18.

*
*

*$\lnot(p \lor q)$ by $\lnot I$ from 12–19.

*$\lnot(p \lor q) \leftrightarrow (\lnot p \land \lnot q)$ by $\leftrightarrow I$ from 1–10 and 11–20.

A: Assume $p \land q$.
By simplification $\land \mathcal E_1$: $p$.
By simplification $\land \mathcal E_2$: $q$.
By the premise, $q \implies r$.
By modus ponens $\implies \mathcal E$: $r$.
By conjunction $\land \mathcal I$: $p \land r$.
By implication $\implies \mathcal I$: $p \land q \implies p \land r$.

A: If your professor doesn't insist on using fully parenthesized expressions in formal proofs, then you should complain bitterly either by insisting on fully parenthesized infix expressions, or by insisting on switching to Polish notation or Reverse Polish notation.  A formal proof, after all, consists of a certain type of sequence of well-formed formulas, and if a sequence is not a sequence of well-formed formulas, it is not a formal proof.
I use Polish notation.  Apq means (p$\lor$q), Cpq means (p$\implies$q), Np means $\lnot$p, Kpq means (p$\land$q), and Epq means "p" and "q" are logically equivalent.  Correspondingly, the definition of a well-formed formula (wff... plural wffs) for the following proofs goes:
1) "p", "q", and "r" are wffs.
2) If w1 is a wff, then Nw1 is a wff.
3) If w1 and w2 are wffs, then Cw1w2, Aw1w2, Ew1w2, and Kw1w2 are wffs.
4) Anything not falling under conditions 1)-3) is not a wff for the following proofs.
To indicate a connection with more conventional terminology, X-in refers to an introduction rule for connective X, and X-out refers to an elimination rule for connective X.  For any well-formed formulas "w1" and "w2" and "w3", the rules for this natural deduction system go as follows:
K-in: From w1 and w2, infer Kw1w2.
K-out: From Kw1w2, infer w1.  From Kw1w2, infer w2.
A-in: From w1, infer Aw1w2.  From w2, infer Aw1w2.
A-out: From Aw1w2, Cw1w3, and Cw2w3, infer w3.
C-in: From a derivation that starts with w1 and ends with w2 (where w1 and w2 have the same scope), infer Cw1w2.
C-out: From w1 and Cw1w2, infer w2.
N-in: From a derivation which starts with w1 and ends with Kw2Nw2 (where w1 and Kw2Nw2 have the same scope), infer Nw1.
N-out: From a derivation which starts with Nw1 and ends with Kw2Nw2 (where Nw1 and Kw2Nw2 have the same scope), infer w1.
E-in: From Cw1w2 and Cw2w1, infer Ew1w2.
E-out: (not used here): From Ew1w2, infer Cw1w2.  From Ew1w2, infer Cw2w1.
Rule of assumption: Any assumption may get introduced so long as it the scope of assumption remains clear.  If multiple assumptions get introduced, then the scope of the (n+1)th assumption falls within the scope of the nth assumption, until assumption (n+1) gets discharged by the conditional introduction rule, the negation elimination rule, or the negation introduction rule.
Proof that "Cqr |- CKpqKpr" (you wrote "|=" instead of "|-", but if you have a formal proof you've demonstrated syntactic validity which means you have "|-", where "|=" indicates semantic entailment... syntactic validity and semantic entailment in some sense can get thought to imply each other in classical propositional logic, because of soundness and completeness, but I digress.)
 1 |  Cqr  axiom (it has a permanent status, so I call the assumption an axiom)
 2 || Kpq assumption
 3 || q  2 K-out
 4 || r 3, 1 C-out
 5 || p 2 K-out
 6 || Kpr 5, 4 K-in
 7 |  CKpqKpr 2-6 C-in

Proof of "De Morgan's" Law ENApqKNpNq (De Morgan didn't discover these laws... they go back at least to William of Ockham, if not the Stoics).
1  |    NApq assumption
2  ||   p assumption
3  ||   Apq 2 A-in
4  ||   KApqNApq 1, 3 K-in
5  |    Np 2-4 N-in
6  ||   q assumption
7  ||   Apq 6 A-in
8  ||   KApqNApq 7, 1 K-in
9  |    Nq 6-8 N-in
10 |    KNpNq 5, 9 K-in
11      CNApqKNpNq 1-10 C-in
12 |    KNpNq assumption
13 ||   Apq assumption
14 |||  p assumption
15 ||   Cpp 14-14 C-in
16 |||  q assumption
17 |||| Np assumption
18 |||| Nq 12 K-out
19 |||| KqNq 16, 18 K-in
20 |||  p 17-19 N-out
21 ||   Cqp 16-20 C-in
22 ||   p 13, 15, 21 A-out
23 ||   Np 12 K-out
24 ||   KpNp 22, 23 K-in
25 |    NApq 13-24 N-in
26      CKNpNqNApq 12-25 C-in
27      ENApqKNpNq 11, 26 E-in

Proof of "De Morgan's" Law ENKpqANpNq
1  |    NKpq assumption
2  ||   p assumption
3  |||  q assumption
4  |||  Kpq 2, 3 K-in
5  |||  KKpqNKpq 1, 4 K-in
6  ||   Nq 3-5 N-in
7  ||   ANpNq 6 A-in
8  |    CpANpNq 2-7 C-in
9  ||   Np assumption
10 ||   ANpNq 9 A-in
11 |    CNpANpNq 9-10 C-in
12 ||   NApNp assumption
13 |||  p assumption
14 |||  ApNp 13 A-in
15 |||  KApNpNApNp 12, 14 K-in
16 ||   Np 13-15 N-in
17 ||   ApNp 16 A-in
18 ||   KApNpNApNp 17, 12 K-in
19 |    ApNp 12-18 N-out
20 |    ANpNq 8, 11, 19 A-out
21      CNKpqANpNq 1-20 C-in

And the second half:
22 |    ANpNq assumption
23 ||   Kpq assumption
24 |||  Np assumption
25 |||| q assumption
26 |||| p 23 K-out
27 |||| KpNp 26, 24 K-in
28 |||  Nq 25-27 N-in
29 ||   CNpNq 24-28 C-in
30 |||  Nq assumption
31 ||   CNqNq 30-30 C-in
32 ||   Nq 22, 29, 31 A-out
33 ||   q 23 K-out
34 ||   KqNq 32, 33 K-in
35 |    NKpq 23-34 N-in
36      CANpNqNKpq 22-35 C-in
37      ENKpqANpNq 21, 36 E-in

Proof of EKpqNANpNq:
1  |    Kpq assumption
2  ||   ANpNq assumption
3  |||  Np assumption
4  |||| q  assumption
5  |||| p 1 K-out
6  |||| KpNp 5, 3 K-in
7  |||  Nq 4-6 N-in
8  ||   CNpNq 3-7 C-in
9  |||  Nq assumption
10 ||   CNqNq 9-9 C-in
11 ||   Nq 2, 8, 10, A-out
12 ||   q 1 K-out
13 ||   KqNq 12, 11 K-in
14 |    NANpNq 2-13 N-in
15      CKpqNANpNq 1-14 C-in
16 |    NANpNq assumption
17 ||   Np assumption
18 ||   ANpNq 17 A-in
19 ||   KANpNqNANpNq 18, 16 K-in
20 |    p 17-19 N-out
21 ||   Nq assumption
22 ||   ANpNq 21 A-in
23 ||   KANpNqNANpNq 22, 16 K-in
24 |    q 21-23 N-out
25 |    Kpq 20, 24 K-in
26      CNANpNqKpq 16-25 C-in
27      EKpqNANpNq 15, 26 E-in

Proof of EApqNKNpNq:
1  |    Apq assumption
2  ||   KNpNq assumption
3  |||  p assumption
4  ||   Cpp 3-3 C-in
5  |||  q assumption
6  |||| Np assumption
7  |||| Nq 2 K-out
8  |||| KqNq 5, 7 K-in
9  |||  p 6-8 N-out
10 ||   Cqp 5-9 C-in
11 ||   p 1, 4, 10 A-out
12 ||   Np 2 K-out
13 ||   KpNp 11, 12 K-in
14 |    NKNpNq 2-13 N-in
15      CApqNKNpNq 1-14 C-in

And the second half, so to speak:
16 |    NKNpNq assumption
17 ||   NApNp assumption
18 |||  p assumption
19 |||  ApNp 18 A-in
20 |||  KApNpNApNp 19, 17 K-in
21 ||   Np 18-20 N-in
22 ||   ApNp 21 A-in
23 ||   KApNpNApNp 17, 22 K-in
24 |    ApNp 17-23 N-out
25 ||   p assumption
26 ||   Apq 25 A-in
27 |    CpApq 25-26 C-in
28 ||   Np assumption
29 |||  Nq assumption
30 |||  KNpNq 28, 29 K-in
31 |||  KKNpNqNKNpNq 30, 16 K-in
32 ||   q 29-31 N-out
33 ||   Apq 32 A-in
34 |    CNpApq 28-33 C-in
35 |    Apq 24, 27, 34 A-out
36      CNKNpNqApq 16-35 C-in
37      EApqNKNpNq 15, 36 E-in

What proofs look like for the natural deductive system you've learned, even if written in Polish notation, may well differ from the proofs above, in part because the rules of inference can differ in natural deductive systems (though I don't know of any instance of the K-out rule differing between natural deductive system, some of the rules do vary).
I'll add here that anytime you have a wff which has no scope or equivalently the wff is a theorem, if you absolutely must stick only the basic (as opposed to derived rules of inference) rules of inference of a natural deduction system, then you can put the formal proof of that wff within the scope of any other assumption.  Above, some of the formal proofs have ApNp and Cpp appearing within the formal proof.  If one does several proofs where one might want them or any other theorems, then one might want to prove them as theorems, and then just introduce them as theorems with the following rule of inference:
Th-in: If w1 is a theorem, then introduce w1 at any point in any proof.
So, one might write something like the following first:
 1 |  NApNp assumption
 2 || p assumption
 3 || ApNp 2 A-in
 4 || KApNpNApNp 3, 1 K-in
 5 |  Np 2-4 N-in
 6 |  ApNp 1-5 A-in
 7 |  KApNp 1, 6 K-in
 8    ApNp 1-7 N-in

and then prove CNKNpNqApq as follows:
 1  |   NKNpNq assumption
 2  |   ApNp Th-in
 3  ||  p assumption
 4  ||  Apq 3 A-in
 5  |   CpApq 3-4 C-in
 6  ||  Np assumption
 7  ||| Nq assumption
 8  ||| KNpNq 6, 7 K-in
 9  ||| KKNpNqNKNpNq 1, 8 K-in
 10 ||  q 7-9 N-out
 11 ||  Apq 10 A-in
 12 |   CNpApq 6-11 C-in
 13 |   Apq 2, 5, 12 A-out
 14     CNKNpNqApq 1-13 C-in

Now, consider the De Morgan laws.  Since they're equivalences, you can use theorem-introduction to shorten proofs, because of the E-out and the C-out rules.  Say you want to prove CNNNKpqANpNq.
 1  |   NNNKpq assumption
 2  ||  NNKpq assumption
 3  ||  KNNKpqNNNKpq 2, 1 K-in
 4  |   NKpq 2-3 N-out
 5  |   ENKpqANpNq Th-in
 6  |   CNKpqANpNq 5 E-out
 7  |   ANpNq 4, 6 C-out
 8      CNNNKpqANpNq 1-7 C-in

Which gives us an 8-line proof instead of a 30 some line proof if we had to reprove ENKpqANpNq at line 5.


text:
Q: Copy selected row to a new row in destination sheet I want to move a selected row of data to a new row in a destination sheet.
I have the code below. It overwrites the row above the last row in the destination sheet.
I would like it to insert a new row in the destination sheet.
Sub move_row()

'Declare variables
 Dim sht1 As Worksheet
 Dim sht2 As Worksheet
 Dim sht3 As Worksheet
 Dim lastRow As Long

'Set variables
Set sht1 = Sheets("Incremental Opps")
Set sht2 = Sheets("Forecast Data")

'Select Entire Row
Selection.EntireRow.Select

'Move row to destination sheet & Delete source row
lastRow = sht2.Range("A" & sht2.Rows.Count).End(xlUp).Row

With Selection
    .Copy Destination:=sht2.Range("A" & lastRow - 1)
    .EntireRow.Delete
End With

End Sub

A: Just change this line to the following:
.Copy Destination:=sht2.Range("A" & lastRow + 1)

A: try this without new line
Sub move_row()
    ActiveCell.EntireRow.Copy Worksheets("Forecast Data").Range("A" & Worksheets("Forecast Data").Range("A" & Rows.Count).End(xlUp).Row - 1)
    ActiveCell.EntireRow.Delete
End Sub

with new line (Insert)
Sub move_row()
    Worksheets("Forecast Data").Range("A" & Worksheets("Forecast Data").Range("A" & Rows.Count).End(xlUp).Row).Insert Shift:=xlDown
    ActiveCell.EntireRow.Copy Worksheets("Forecast Data").Range("A" & Worksheets("Forecast Data").Range("A" & Rows.Count).End(xlUp).Row - 1)
    ActiveCell.EntireRow.Delete
End Sub


text:
Q: Use jQuery to Compare a class inside an ID against another class inside an ID I've been coding for ~60+ hours the past 5 days, so I apologize if, due to burn-out, this question is too trivial :-)
I have some HTML like this:

    hi

    yes

    yes

    no

All I want to do is use jQuery to:
1.) Get the CSS-equivalent value of "#blah1_1 .inner". I tried:

    alert ( $("#blah1_1 .inner").val() );

but fail.
2.) Compare #blah1_1.inner value to #blah2_1.inner value. If equal, then echo a confirmation.
3.) Double loop through the blah1_* "Array" and compare it to the blah2_* "array". If blah1_[x] = blah2_[y] then echo a confirmation. For example, compare all the blah1_*'s against blah2_1 ... then compare blah1_*'s against blah2_2, etc.
A little late-night/red-eye help, please? (TIA!)

A: your alert ( $("#blah1_1 .inner").val() ); should alert ( $("#blah1_1 .inner").text() );
then you can use Attribute selector to select both sets blah1_* and blah2_*
then use .each() jQuery method to iterate over the labels:
then for the compare:

$(document).ready(function() {
  const elms1 = $('[id^="blah1"]');
  const elms2 = $('[id^="blah2"]');

  const labels1 = elms1.find('label');
  const labels2 = elms2.find('label');

  labels1.each(function(index1, el1){
    labels2.each(function(index2, el2){
      console.log($(el2).text() === $(el1).text())
    })
  })
})

    hi

    yes

    yes

    no


text:
Q: noetherian rings $R \subset S$ Let $R \subset S$ be rings.
assume that S is finitly generated over R.
The book i'm reading states that if R is a noetherian R, than S is noetherian as wel. But their is no proof of this given.
I don't see why... can someone help me with this?

A: Assume $R$ is noetherian and $S=R[a_1,...,a_n]$.
By Hilbert's basis theorem, any polynomial ring over a noetherian ring is noetherian, so $R[X_1,...,X_n]$ is a noetherian ring since $R$ is. Then $S=R[X_1,...,X_n]/(X_1-a_1,...,X_n-a_n)$ is a quotient of noetherian rings and therefore noetherian.


text:
Q: A basic question on $\pi$-system and borel sigma algebra Let $(X,d)$ be a metric space. Is it true that there exist a $\pi$ system such that it generates the borel sigma algebra $B(X)$. If not can we find any sufficient condition on $(X,d)$ so that it holds.

A: Yes, the Borel $\sigma$-algebra $B(X)$ is itself such a $\pi$-system. Less trivially, the collection of open sets is such a $\pi$-system, as is the collection of closed sets. If $X$ is separable, then another example is the collection of all finite intersections of open balls $B(x,r)$, $x\in X$, $r>0$.


text:
Q: Is -mllrmat similar to mllr_transform I am trying to adapt my acoustic models for sphinx4 using MAP and MLLR.
I do understand that I have to use the mllr_solve binary and the bw to do one iteration.
I'd like to know if using bw's -mllrmat option is equivalent to using the mllr_transform tool to apply the baseline means before the bw call.
In other words: Can I skip the mllr_transform step if I am using the -mllrmat option in bw?

A: Yes, effect would be the same.


text:
Q: Is it possible to link lib dynamically like a DLL? This is interview question.
Is it possible to link lib dynamically like a DLL ?
For example, for DLL, we use LoadLibrary and call exported functions.
Is it possible to use lib file in same manner?

A: No. .lib library are statically linked, and that is the purpose they're created for, to resolve the name symbols at link-time by Linker, and link-time occurs before runtime. They're often referred to as "static libraries" (that is why I added this tag in your question!). That is the brief story of lib.
However, you can create a DLL wrapper, if you really want to link at runtime.

A: No. Create a DLL instead or, if you do not have the source, wrap the functionality in the .lib with own DLL interface.

A: No. It's not possible. A DLL is module with a PE32 header with all information to load it into a process. A LIB is only a archive of OBJ files.
And despite others say it's easy to wrap a DLL around it, this can be quite difficult. The reason is, that a .LIB not only resolves some dependencies but can also have unresolved externals.
As long as these unresolved externals require only the compiler's runtime library wrapping in a DLL might work. You can check this when you create a DLL project, probably with a minimal C++ source, and try to compile. Than you see, if further externals must be resolved with other libraries.
One important problem may arise with memory management. When yo link statically with a .LIB you will use all the same definitions. If your library comes with own implementation, let's say of malloc-stlye functions, this will not be linked to your application as long as you add all these symbols to the EXPORT list. Finding the list of public symbols that should be included in the EXPORT table may be a pain.

A: Yes - not directly, but with a very small amount of work.
Create a new .DLL project, link the .lib, define which functions you want to export in a .DEF file then compile.


text:
Q: How to make MediaElementJs load/download the full audio resource I have a requirement to load hours of music, to have in case of connection shortages. What we are trying to do is to have many audio tags loading in background while the first is playing.
The problem is that, although we call .load() on every audio media element; every audio is just loaded partially.
Does anyone know if there is an option to force the full load? We have tried the trick of doing pause/play to force the loading but it is not working.
(sorry for my bad English)

A: Have you tried adding preload="auto" to your audio elements?
EDIT
Also you might want to setup a Cache manifest.
Look here for more info: http://www.html5rocks.com/en/tutorials/appcache/beginner/
Also some good information from the question here:
Can't get simple html5 manifest cache to work!


text:
Q: Ubuntu OS for Win Vista 32bit Which Ubuntu OS should I download to change my Win Vista 32bit Os to Ubuntu?
I can only fid Ubuntu Os for 64 bit.

A: Check at the Intel ARK website to determine if your computer's processor supports the 64-bit instruction set. Also your computer should have at least 3GB of RAM for best results running a 64-bit operating system.
If you find that you need to install a 32-bit release, you can download Ubuntu 16.04 32-bit. Ubuntu 16.04 is a Long Term Support (LTS) release which is supported by updates until April, 2021.
Starting with Ubuntu 17.10 there is no longer a 32-bit iso file available to download, only a 64-bit iso file, however 32-bit iso files are still available for the 17.10 releases of Ubuntu MATE, Kubuntu, Xubuntu, Lubuntu, Ubuntu Budgie, Ubuntu Studio and Ubuntu Kylin.


text:
Q: Where do you update the server on a consumable in app purchase? So I have an app that has a consumable purchase and from what I have read a little more work is involved in terms of persisting some info on the server.
What I am not clear on is where does one update the server on a sucessful purchase? Is it

*

*(void)completeTransaction:(SKPaymentTransaction *)transaction;

??
If it is indeed the above mentioned function, is it just a matter of making a web call and updating the server server? I am just trying to understand best practices and would appreciate any help.
much regards

A: I don't know if this counts as a valid answer, but you should maybe check out this article.
The blog post is from 2010, so one could say it's rather outdated! But i think it's worth a look and the provided example (completeTransaction method implementation) should be valid also.
Getting in app purchases to work is a lot more painful than it should be actually.

A: I did and do it in
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
...
 case SKPaymentTransactionStatePurchased:
 case SKPaymentTransactionStateRestored:
      [self sendReceiptToServerAndValidateFurther:transaction.receiptData

it is then only a webcall to the server-side script which can validate the receipt with itunes and update its DB/send the data
btw some server php
function itunes_verify2($receiptData,$sandboxed) {
    //itunes store url -- sandbox or not :)
    $itunes_storeURL = "https://buy.itunes.apple.com/verifyReceipt";
    if($sandboxed == true) {
        $itunes_storeURL = "https://sandbox.itunes.apple.com/verifyReceipt";
    }

    log_action('itunes_verify2 using ' . $itunes_storeURL);

    $post = array("receipt-data" => $receiptData );
    $postData = json_encode($post);

    $responseData = post_doRequest( $itunes_storeURL, $postData );
    $response = json_decode($responseData);

    if($responseArray->status == 0) {
        return "YES";
    } else {
        log_action('failed to get status ok from ' . $reponseData);
        return "NO";
    }
}

A: I'll give a vote here for this SO question. Seems to have several examples.
https://stackoverflow.com/questions/4178214/ios-in-app-purchase-sample-code
From what I can tell, consumables do require your own hosting, as mentioned here:
iOS In App Purchases for Subscriptions and Consumables products
I have no personal experience with consumables, only with upgrade-type IAPs, which weren't too painful (relatively speaking).


text:
Q: angular 4 - Response for preflight is invalid (redirect) I have angular 4 project in local and i want use api to get information , i get this error
localhost/:1 XMLHttpRequest cannot load http:????. Response for preflight is invalid (redirect)

I have jquery project in local that call same api and get answer with no error
What is problem ? I see many question and answer in this site and nobody can help me.

A: This is very much the case of CORS as mentioned by Gunter. If you are requesting a resource that is on a different domain(as in your case i.e. api's domain) from the domain that you are requesting, then you get such errors.
When performing certain types of cross-domain Ajax requests, modern browsers that support CORS will insert an extra "preflight" request to determine whether they have permission to perform the action.
Please refer to this link: Cross-origin resource sharing


text:
Q: Insert Text Every 34 Character in a Text Document + MAC I'm stuck. I need a script that will read my text document and insert custom text on the 34 character. This needs to happen for every line in my text document.
Example:
INPUT TEXT
`12345678912345678912345678912345  ABCD`
`12345678912345678912345678912345  EFGH`
`12345678912345678912345678912345  IJKL`
`12345678912345678912345678912345  MNOP`

OUTPUT TEXT
`12345678912345678912345678912345 custom text hereABCD`
`12345678912345678912345678912345 custom text hereEFGH`
`12345678912345678912345678912345 custom text hereIJKL`
`12345678912345678912345678912345 custom text hereMNOP`

I've provided below the script I can get working within Terminal.  However, if there is a way to get it to work in Applescript so when I drop my file on the application it will prompt and ask what text I would like to insert (this would be "custom text here") and then upon hitting OK it would run.
If it isn't possible to do in Applescript, Automator would work too however, I cannot seem to get Automator to work with the script.  Process for Automator is:
1. Get Specified Finder Items
2. Run Shell Script

This runs fine, but it does not change the document.  Help?

A: In Bash you can use while read -r -N 34 to read 34 characters repeatedly. Untested example:
while IFS= read -r -N 34 || [[ -n "$REPLY" ]]
do
    printf '%s' "$REPLY"
    printf '%s\n' " custom text here"
done < input-file

Update: Looks like OP wants to discard characters after #34 on each line:
while IFS= read -r || [[ -n "$REPLY" ]]
do
    printf '%s' "${REPLY:0:34}"
    printf '%s\n' " custom text here"
done < input-file

UPDATE: OP here and I've figured out based on your wonderful knowledge everything I need to do!
while IFS= read -r || [[ -n "$REPLY" ]]
do
    printf '%s' "${REPLY:0:34}"
    printf '%s' "  Faux_Folder/"
    printf '%s\n' "${REPLY:36}"
done < input-file > output-file

A: Not sure if this work on OSX (works on ubuntu at least.):
sed -n -E '1h;2,$H;${g;s/.{34}/& custom text here\n/gp}' input.txt

Basically, it reads till the end of file & then inserts " custom text here\n" after every 34 characters.


text:
Q: Mapping two components according to same method in react Here I have map <Popover.Button> according to a categoryObj I want to map the below <Popover.Panel> also according to that categoryObj.
but the problem is I cannot map those two at once. I want to do that separately. how can I do that ?
import { Fragment, useState } from "react";
import { Popover, Transition } from "@headlessui/react";
import Dropdown from "./dropdown";

function classNames(...classes) {
  return classes.filter(Boolean).join(" ");
}

import { categoryObj } from "../../components/item/categoriesobj";

export default function Example() {
  const [mainCatArray, setMainCatArray] = useState([]);
  return (
    <>
      <Popover className="z-0 relative">
        {({ open }) => (
          <>

                {categoryObj.map((singleMainCategory) => (
                  <Popover.Button
                    className={classNames(
                      open ? "text-gray-900" : "text-gray-500",
                      "group bg-white rounded-md inline-flex items-center text-base font-medium hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    )}
                  >
                     {
                        setMainCatArray(singleMainCategory.subCategory);
                      }}
                    >
                      {singleMainCategory.name}

                  </Popover.Button>
                ))}

            <Transition
              as={Fragment}
              enter="transition ease-out duration-200"
              enterFrom="opacity-0 -translate-y-1"
              enterTo="opacity-100 translate-y-0"
              leave="transition ease-in duration-150"
              leaveFrom="opacity-100 translate-y-0"
              leaveTo="opacity-0 -translate-y-1"
            >
              <Popover.Panel className="absolute z-10 inset-x-0 transform shadow-lg ">

                  <Dropdown subCategory={mainCatArray} />

              </Popover.Panel>
            </Transition>
          </>
        )}
      </Popover>
    </>
  );
}


text:
Q: Shared Preferences Android I have the following problem:
I have coded an android app which contains 2 activities. The first Activity is the main activity, the second is for settings.
In the settings Activity you can enter your name with an EditText box, the name should be showed in the first Activity as greeting.
How can I do this in an very simple way?

A: You want to do it with SharedPreferences? This is how you save your data from the settings activity. Add a button to save your preferences once you introduced the name and put this code on click listener:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString("NAME", yourEditText.getText().toString());
editor.commit();

And then in your main activity, add a button and a textview to show the name. Add the following code to the button:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString("NAME", null);
yourTextView.setText(name); //Add the name to your textview

Hope it helps!!

A: You have two ways for this.
First: onActivityResult
In Main Activity:
Use startActivityForResult(intent, ACTIVITY2)
and add this method
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent intent)
{
    if (resultCode == Activity.RESULT_OK)
    {
        String string_1 = intent.getStringExtra ("my_value_from_second_activity", "");
    }
}

In Settings Activity:
Intent intent = new Intent ();
intent.putExtra ("my_value_from_second_activity", "hello");
activity.setResult (Activity.RESULT_OK, intent);

Second: SharedPreferences, the good way
Setting Activity:
SharedPreferences settings = getSharedPreferences("config", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("my_value", edttext.getText().toString());
editor.commit();

Main Ativity:
SharedPreferences settings = getSharedPreferences("config", 0);
String value        = settings.getString("my_value", "");

A: You can pass data through intent from one activity to to another
 You can also use constant class with static variable to store value
and shared prefrenct store data till apk is installer so u can either use of one


text:
Q: replace href link text Is my code correct?
 function replace_stuff() {
  document.body.innerHTML = document.body.innerHTML.replace(/oldtexts/g,'');
 }

I am trying to remove the string "oldtexts" between an a href tag like
this oldtexts but i still see oldtexts and nothing gets replaced

A: I didn't try this one, but this may work. (uses jQuery)
$('a[href]').each(function(i){
 if($(this).html()=="oldtext") $(this).html(" ");
});

or
$('a[href]').each(function(i){
 $(this).html($(this).html().replace(/regex/g,"blahblah"));//warning : if replaced text contains nothing(""), then this will not work.
});

A: You have tagged jQuery, so I would suggest to use it:
$(function(){
    $('a').each(function(){
        var $this = $(this);
        $this.html($this.html().replace(/oldtext/g, ''));
    });
});

A: Use Jquery :)
$(document).ready(function(){
             $('#idofatag').text('replacevalueofoldtexts');
});

if you want to trigger this change on a click of a button,
$(document).ready(function(){
        $('#someButtonid').click(function(){
             $('#idofatag').text('replacevalueofoldtexts');
        });
});

http://jquery.com/

A: What happens if you try using /\b(oldtexts)\b/g or the jQuery .replace?

A: Since you seem to be using jQuery, the cleanest solution seems to be using a function for .html().
$('a').html(function (index, oldhtml) {
    return oldhtml.replace(/oldtexts/g, '');
});

jsFiddle Demo
If you want to write a reusable function, you can do that of course:
function replace_stuff(index, oldhtml) {
   return oldhtml.replace(/oldtexts/g, '');
}

And then you can invoke it on any jQuery object: $('a').html(replace_stuff);.


text:
Q: Getting "Element.setCapture() is deprecated" warning on console while using on:click function of Svelte JS I have a code block like this,
{#if categoryArray}

        {#each categoryArray as catName, index}

            {catName}

        {/each}

{/if}

I want a container to be opened under it when the "li" element is clicked on mobile phones. When I tried it in Chrome, safari browser, there was no problem, but when I tried it from Firefox browser on my computer, I got this error and the subcategory does not open.

I'm just using on:click. I don't understand why this error occurs. Can anybody help me ? Thanks :)

A: That code is injected by the dev tools to simulate touch interactions (as the name of the file in the warning indicates). You can click that file link and see the exact code used.
The click should still work, though, at least I cannot reproduce the issue. This is not an error.
(By the way, in general you should only add click handler to interactive elements that are supposed to be clicked, i.e. form elements like button. Otherwise the result will be not accessible.)


text:
Q: training Parallel models in keras vs sequentially I have the following code which is training the same model with different datasets in parallel. I want to know what is the difference between the result I get in this code vs if I train the model one by one using the corresponding datasets.Any help is greatly appreciated.
from keras.layers import *
from keras.models import Model, Sequential
import numpy as np
import random
import test
index=[]
for i in range(10):
    index.append(random.sample(range(0, 201), 10))
x_tr=[]
y_tr=[]
x_te=[]
y_te=[]

aa = test.train_data(index[0])
X_train0, Y_train0, X_Test0, Y_Test0 = test.ddata(aa)
aa = test.train_data(index[1])
X_train1, Y_train1, X_Test1, Y_Test1 = test.ddata(aa)
aa = test.train_data(index[2])
X_train2, Y_train2, X_Test2, Y_Test2 = test.ddata(aa)
aa = test.train_data(index[3])
X_train3, Y_train3, X_Test3, Y_Test3 = test.ddata(aa)
aa = test.train_data(index[4])
X_train4, Y_train4, X_Test4, Y_Test4 = test.ddata(aa)
aa = test.train_data(index[5])
X_train5, Y_train5, X_Test5, Y_Test5 = test.ddata(aa)
aa = test.train_data(index[6])
X_train6, Y_train6, X_Test6,Y_Test6 = test.ddata(aa)
aa = test.train_data(index[7])
X_train7, Y_train7, X_Test7, Y_Test7 = test.ddata(aa)
aa = test.train_data(index[8])
X_train8, Y_train8, X_Test8, Y_Test8 = test.ddata(aa)
aa = test.train_data(index[9])
X_train9, Y_train9, X_Test9, Y_Test9 = test.ddata(aa)

m=test.get_model()
inp0=Input((5,10,10,1))
inp1=Input((5,10,10,1))
inp2=Input((5,10,10,1))
inp3=Input((5,10,10,1))
inp4=Input((5,10,10,1))
inp5=Input((5,10,10,1))
inp6=Input((5,10,10,1))
inp7=Input((5,10,10,1))
inp8=Input((5,10,10,1))
inp9=Input((5,10,10,1))
out0=m(inp0)
out1=m(inp1)
out2=m(inp2)
out3=m(inp3)
out4=m(inp4)
out5=m(inp5)
out6=m(inp6)
out7=m(inp7)
out8=m(inp8)
out9=m(inp9)

model = Model([inp0,inp1,inp2,inp3,inp4,inp5,inp6,inp7,inp8,inp9],[out0,out1,out2,out3,out4,out5,out6,out7,out8,out9])
model.compile(optimizer='adam', loss='mse')
model.fit([X_train0,X_train1,X_train2,X_train3,X_train4,X_train5,X_train6,X_train7,X_train8,X_train9],[Y_train0,Y_train1,Y_train2,Y_train3,Y_train4,Y_train5,Y_train6,Y_train7,Y_train8,Y_train9], epochs = 50)
ypred0,ypred1,ypred2,ypred3,ypred4,ypred5,ypred6,ypred7,ypred8,ypred9 = model.predict([X_Test0,X_Test1,X_Test2,X_Test3,X_Test4,X_Test5,X_Test6,X_Test7,X_Test8,X_Test9])
print(ypred0.shape)

FYI-test is another where I get my data from.

A: It's best to train in parallel or all at once than sequentially.
If you train it sequentially you might end up by overfitting on the last dataset on which you train the model.


text:
Q: How to make Eslint/Prettier fail on errors and warnings inside ci environment? I have a Vue app using Eslint with Prettier. A Github action should check the code style, but npm run lint -- --no-fix only logs the warnings, the workflow doesn't fail.
My test PR:

The workflow passes although I would expect it to fail. Is there a flag for this? E.g.
npm run lint -- --no-fix --fail-on-errors-and-warnings

A: --max-warnings=0 this should do the trick.


text:
Q: Unable to read Shapes from DOCX file using OpenxmlSDK I have a requirement where in I have to parse a DOCX file and extract all the text and images. I am using OpenxmlSDK 2.5 to achieve this. I am able to parse the images and text but the DOCX also have a group of Shapes which I trying to parse and convert them to Drawing images, which is giving me wrong results.
Here is the Sample docx file which I am trying to parse.
I referred the this Stack overflow discussion and tried the same way but no luck.
The resulting DOCX which I am creating with following code is not having any parsed images.
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Drawing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Vml;
using DocumentFormat.OpenXml;

namespace ReadGroupShape
{

    class Program
    {
        static List<Bitmap> images = new List<Bitmap>();

        static void Main(string[] args)
        {
            MainDocumentPart mainPart = null;
            Body content = null;

            WordprocessingDocument newDoc = WordprocessingDocument.Create("NewDocx.docx", WordprocessingDocumentType.Document);
            MainDocumentPart newMainPart = newDoc.AddMainDocumentPart();
            newMainPart.Document = new Document();
            Body newbody = newMainPart.Document.AppendChild(new Body());

            byte[] docBytes = File.ReadAllBytes("SampleDoc.docx");
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(docBytes, 0, docBytes.Length);

                using (WordprocessingDocument wpDoc = WordprocessingDocument.Open(ms, true))
                {
                    mainPart = wpDoc.MainDocumentPart;
                    content = mainPart.Document.Body;

                    foreach (Paragraph par in content.Descendants<Paragraph>())
                    {
                        Paragraph npar = newbody.AppendChild(new Paragraph());

                        foreach (Run run in par.Descendants<Run>())
                        {
                            Run nrun = npar.AppendChild(new Run());
                            DocumentFormat.OpenXml.Drawing.Blip pic = run.Descendants<DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();

                            ImageData imageData = run.Descendants<ImageData>().FirstOrDefault();

                            if (pic == null && imageData == null)
                            {
                                nrun.InsertAfterSelf(run.CloneNode(true));

                            }
                            else
                            {
                                if (pic != null)
                                {

                                    nrun.InsertAfterSelf(CreateImageFromBlip(wpDoc, run, newMainPart, pic));
                                }
                                else if (imageData != null)
                                {
                                    nrun.InsertAfterSelf(CreateImageFromShape(wpDoc, run, newMainPart, imageData));
                                }
                            }

                        }
                    }

                    mainPart.Document.Save();
                }

            }

            newMainPart.Document.Save();
            newDoc.Close();
        }

        private static Run CreateImageFromShape(WordprocessingDocument sourceDoc, Run sourceRun, MainDocumentPart mainpart, ImageData imageData)
        {
            ImagePart p = sourceDoc.MainDocumentPart.GetPartById(imageData.RelationshipId) as ImagePart;
            return CreateImageRun(sourceDoc, sourceRun, mainpart, p);
        }

        private static Run CreateImageFromBlip(WordprocessingDocument sourceDoc, Run sourceRun, MainDocumentPart mainpart, DocumentFormat.OpenXml.Drawing.Blip blip)
        {
            ImagePart newPart = mainpart.AddImagePart(ImagePartType.Png);

            ImagePart p = sourceDoc.MainDocumentPart.GetPartById(blip.Embed.Value) as ImagePart;

            Bitmap image = new Bitmap(p.GetStream());

            using (Stream s = p.GetStream())
            {
                s.Position = 0;
                newPart.FeedData(s);
            }

            string partId = mainpart.GetIdOfPart(newPart);

            Drawing newImage = CreateImage(partId);

            return new Run(newImage);
        }

        private static Run CreateImageRun(WordprocessingDocument sourceDoc, Run sourceRun, MainDocumentPart mainpart, ImagePart p)
        {
            ImagePart newPart = mainpart.AddImagePart(ImagePartType.Png);

            using (Stream s = p.GetStream())
            {
                s.Position = 0;
                newPart.FeedData(s);
            }

            string partId = mainpart.GetIdOfPart(newPart);

            Drawing newImage = CreateImage(partId);

            return new Run(newImage);
        }

        private static Drawing CreateImage(string relationshipId)
        {
            // Define the reference of the image.
            return new Drawing(
                               new DocumentFormat.OpenXml.Drawing.Wordprocessing.Inline(
                                   new DocumentFormat.OpenXml.Drawing.Wordprocessing.Extent() { Cx = 990000L, Cy = 792000L },
                                   new DocumentFormat.OpenXml.Drawing.Wordprocessing.EffectExtent()
                                   {
                                       LeftEdge = 0L,
                                       TopEdge = 0L,
                                       RightEdge = 0L,
                                       BottomEdge = 0L
                                   },
                                   new DocumentFormat.OpenXml.Drawing.Wordprocessing.DocProperties()
                                   {
                                       Id = (UInt32Value)1U,
                                       Name = "Picture 1"
                                   },
                                   new DocumentFormat.OpenXml.Drawing.Wordprocessing.NonVisualGraphicFrameDrawingProperties(
                                       new DocumentFormat.OpenXml.Drawing.GraphicFrameLocks() { NoChangeAspect = true }),
                                   new DocumentFormat.OpenXml.Drawing.Graphic(
                                       new DocumentFormat.OpenXml.Drawing.GraphicData(
                                           new DocumentFormat.OpenXml.Drawing.Picture(
                                               new DocumentFormat.OpenXml.Drawing.NonVisualPictureProperties(
                                                   new DocumentFormat.OpenXml.Drawing.NonVisualDrawingProperties()
                                                   {
                                                       Id = (UInt32Value)0U,
                                                       Name = "New Bitmap Image.jpg"
                                                   },
                                                   new DocumentFormat.OpenXml.Drawing.NonVisualPictureDrawingProperties()),
                                               new DocumentFormat.OpenXml.Drawing.BlipFill(
                                                   new DocumentFormat.OpenXml.Drawing.Blip(
                                                       new DocumentFormat.OpenXml.Drawing.BlipExtensionList(
                                                           new DocumentFormat.OpenXml.Drawing.BlipExtension()
                                                           {
                                                               Uri =
                                                                 "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                                           })
                                                   )
                                                   {
                                                       Embed = relationshipId,
                                                       CompressionState =
                                                       DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print
                                                   },
                                                   new DocumentFormat.OpenXml.Drawing.Stretch(
                                                       new DocumentFormat.OpenXml.Drawing.FillRectangle())),
                                               new DocumentFormat.OpenXml.Drawing.ShapeProperties(
                                                   new DocumentFormat.OpenXml.Drawing.Transform2D(
                                                       new DocumentFormat.OpenXml.Drawing.Offset() { X = 0L, Y = 0L },
                                                       new DocumentFormat.OpenXml.Drawing.Extents() { Cx = 990000L, Cy = 792000L }),
                                                   new DocumentFormat.OpenXml.Drawing.PresetGeometry(
                                                       new DocumentFormat.OpenXml.Drawing.AdjustValueList()
                                                   )
                                                   { Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle }))
                                       )
                                       { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                               )
                               {
                                   DistanceFromTop = (UInt32Value)0U,
                                   DistanceFromBottom = (UInt32Value)0U,
                                   DistanceFromLeft = (UInt32Value)0U,
                                   DistanceFromRight = (UInt32Value)0U,
                                   EditId = "50D07946"
                               });
        }

    }
}

What is that I am missing? Could anyone please help me to parse the shapes and images?
Thanks.


text:
Q: How can dbt build with a json var through the command console I would like to define a json var for a run of dbt through the command console.
This json is generated in python with a database schema, something like [{'name': 'Name', 'type': 'STRING', 'mode': 'NULLABLE'}...]
I tried in different ways but I couldn't get it:
 $ dbt build --vars 'json: [{'name': 'Name', 'type': 'STRING', 'mode': 'NULLABLE'}...]'

In this case I got the error "while parsing a block mapping" probably because of the single quotes from JSON.
I tried to convert the single quotes to double quotes in python with json.dumps() function and execute again something like this:
$ dbt build --vars 'json: [{"name": "Name", "type": "STRING", "mode": "NULLABLE"}...]'

In this case I'm getting an error like:
The --vars argument must be a YAML dictionary, but was of type 'str'
I tried some more ways but with similar results.
I have to do this because I have an Airflow operator that generates this json in python with the database schema to validate and sends it via xcom to a Kubernetes Pod Operator that is in charge of launching the dbt build command with this var.
https://docs.getdbt.com/docs/building-a-dbt-project/building-models/using-variables

A: You're missing a set of curlies. You want to pass in a dictionary literal that has a single set of quotes around it (so it gets read as a single string by your shell).
You have:
--vars 'json: ...'

You need:
--vars '{json: ...}'

With all the args:
$ dbt build --vars '{json: [{"name": "Name", "type": "STRING", "mode": "NULLABLE"}...]}'

Note that YAML is flexible about quoting, so this is the same as either of these:
$ dbt build --vars '{json: [{name: Name, type: STRING, mode: NULLABLE}...]}'
$ dbt build --vars '{"json": [{"name": "Name", "type": "STRING", "mode": "NULLABLE"}...]}'


text:
Q: Как называется этот трюк с динамическим созданием имени переменной ${'foo' . $x}? $x = 'bar';
${'foo' . $x} = 'abc';
echo $foobar; // abc

Как и почему это работает?

A: КАК ЭТО РАБОТАЕТ:
Переменная переменной, или Динамическая переменная использует строку, выражение или значение другой переменой как собственное имя:
$x = 'bar';
$$x = 'baz'; // $$x -> $ + bar -> $bar
// теперь в куче имён появилось новое - bar со значением baz

То, что новая переменная теперь доступна легко проверить:
$x = 'bar';
$$x = 'baz';
echo $bar; // baz
echo $$x;  // baz

Возможно присвоение по цепочке, с использованием нескольких переменных:
$x = 'bar';
$$x = 'foo';
$$$x = 'baz'; // $ + foo как ( $ + bar как значение $x )
echo $foo; // baz
echo $$$x; // baz

Если необходимо создать переменную с использованием строковых выражений или нескольких переменных (и с и без строк), их заключают в фигурные скобки {'string'}
$x = 'bar';
${$x.'bar'} = 'baz'; // $ + {bar как значение $x + bar как строка}
echo $barbar;        // baz
echo ${$x.'bar'};    // baz

Можно подставлять пользовательские функции:
function bar() {
    return 'bar';
}

$x = 'bar';
${$x.'bar'} = 'baz'; // $ + {bar как значение $x + bar как строка}
echo $barbar;        // baz
echo ${$x . bar()};  // baz

и конструкции языка:
$bar = 'BAR';
$x = 'bar';
${$x.'bar'} = 'baz'; // $ + {bar как значение $x + bar как строка}
echo $barbar;                // baz
echo ${$x.strtolower($bar)}; // baz

Стоит упомянуть переменные переменных при работе с массивами. Для тех, кто мануал читать не будет:
$bar = array('bar');
$x = 'bar';
${$x.$bar[0]} = 'baz';
echo $barbar; // baz

Последний нюанс, на который хотелось бы обратить внимание - т.к. переменные в php это ссылки на значения в куче, удаление переменной донора после создания переменной переменной не влияет на её состояние.
$x = 'bar';
$$x = 'baz';
unset($x);
echo $bar; // baz
echo $$x;  // Undefined variable

ПОЧЕМУ ЭТО РАБОТАЕТ:
потому, что гладиолус ;)


text:
Q: Remove navigation divider at the end of nav bar - HTML/CSS I am having trouble removing the last border divider after 'PART C'. I would like to keep the border on the right of each element in the navigation list apart from the last one.

a {
  text-decoration: none;
  color: #000000;
  display: block;
  width: 150px;
}
li {
  list-style: none;
  float: left;
  padding-left: 10px;
  width: 150px;
}
ul {
  width: 900px;
  margin: 0px auto;
}
.nav {
  padding: 25px 50px 10px 0px;
  z-index: 1;
  font-family: "Avenir";
}
.nav a:hover {
  color: #cccccc;
}
.nav a {
  color: #000;
  display: block;
  line-height: 14px;
  padding-left: 10px;
  padding-right: 30px;
  text-decoration: none;
  border-right: 1px solid #000;
  text-align: center;
  width: 100px;
}

HOME

ABOUT ME

PART A

PART B

PART C

A: You could use :last-child css selector.

a {
  text-decoration: none;
  color: #000000;
  display: block;
  width: 150px;
}
li {
  list-style: none;
  float: left;
  padding-left: 10px;
  width: 150px;
}
ul {
  width: 900px;
  margin: 0px auto;
}
.nav {
  padding: 25px 50px 10px 0px;
  z-index: 1;
  font-family: "Avenir";
}
.nav a:hover {
  color: #cccccc;
}
.nav a {
  color: #000;
  display: block;
  line-height: 14px;
  padding-left: 10px;
  padding-right: 30px;
  text-decoration: none;
  border-right: 1px solid #000;
  text-align: center;
  width: 100px;
}
.nav li:last-child a {
  border-right: none;
}

HOME

ABOUT ME

PART A

PART B

PART C

Reference: MDN

A: Add this rule:
.nav li:last-child a{border-right:none}

Demo :http://jsfiddle.net/lotusgodkk/Lewza63r/

A: Another solution is add class to last li a{ which li doesn't need border} and write style to class.
'a.no_border { border-right: 0; }'

Demo link

A: :last-child do not work below IE9
Use this it will work on all browser
a#button2 {border-right: none;}


text:
Q: Deriving the equation of motion of an harmonic oscillator from the equation of motion of a mass-spring system During my physics 1 course I stumbled upon this problem (our professor left it as an exercise). Basically I have to prove that $$A\cos(\omega t) + B\sin(\omega t) = C\cos(\omega t + \varphi )$$ and find $C$,$\varphi$ in function of $A$,$B$. He told us as a hint that we can use the trigonometric identity $$\cos(\alpha + \beta) = \cos\alpha \cos\beta - \sin\alpha \sin\beta$$
I really don't understand how to approach this problem. The most promising way I found is to apply the identity to the r.h.s., that is to say:
$$C\cos(\omega t + \varphi ) = C(cos\omega t cos\varphi - sin\omega t sin\varphi)$$
Expliciting $C$:
$$C = \frac{Asin\omega t + Bcos\omega t}{cos\omega t cos\varphi - sin\omega t sin\varphi}$$
But now I'm stuck: how can I express $C$ in terms of only $A$ and $B$?

A: Hint.
We have
$$
\cos(\omega t)\frac AC + \sin(\omega t)\frac BC = \cos(\omega t)\cos\varphi-\sin(\omega t)\sin\varphi
$$

A: It is true that you need to apply the trigonometric identity to expand the r.h.s. of the given equation. But the way you tried to make $C$ the subject is wrong. You should have proceeded as shown below.
$$A\cos\left(\omega t\right) + B\sin\left(\omega t\right) = C\cos\left(\omega t + \varphi \right) = C\left(\cos\left(\omega t\right) \cos\left(\varphi\right) \right)- C\left(\sin\left(\omega t\right) \sin\left(\varphi\right) \right).$$
Now compare the coefficients of $\cos(\omega t)$ and $\sin(\omega t)$ terms on l.h.s. with those on the r.h.s. respectively to obtain the following pair of relations.
$$C\cos(\varphi ) = A $$
$$C\sin(\varphi ) = -B $$
When you solve this system of equations simultaneously, we get,
$$C=\sqrt{A^2+B^2} \qquad\text{and}$$
$$\tan\left(\varphi\right)=-\dfrac{B}{A}\quad\rightarrow\quad \tan\left(180^o-\varphi\right) =\dfrac{B}{A} \quad\rightarrow\quad \varphi = 180^o - \tan^{-1}\left(\dfrac{B}{A}\right)$$


text:
Q: If $x$ is a real and $0 < x < 4$, then $\frac{4}{x(4-x)} \geq 1$ I got this exercise from the textbook Book of Proof, CH4 E12. I've tackle this problem in the following manner:
Suppose x is a real and $0 < x < 4$, it follows that,
\begin{align*}
&\Rightarrow 0 - 2 < x - 2 < 4 - 2 \\
&\Rightarrow     4 < (x - 2)^2 < 4\\
&\Rightarrow     0 \leq (x - 2)^2 < 4
\end{align*}
Since, $x(4 - x) = 4x - x^2 = 4 - (x - 2)^2$, then
$$\dfrac{4}{x(4 - x)} = \dfrac{4}{4 - (x - 2)^2}.$$
This expression is greater or equal to $1$ for
$0 \leq (x - 2)^2 < 4$. Thus,
$$\dfrac{4}{x(4 - x)} \geq 1.$$
I'm quite new to proof technique and I'm using this book to self-learn logic and proofing writing. My question is: is the solution stated above logically sound? Would my arguments be considered sufficient to prove that $P \Rightarrow Q$?

A: Your approach is actually quite nice, but there is one error:  It is incorrect to say that $0-2\lt x-2 \lt 4-2$ implies $4\lt(x-2)^2\lt4$.  What you want to say instead is something like
$$0-2\lt x-2\lt4-2\implies|x-2|\lt2\implies0\le(x-2)^2\lt4$$

A: Hint See that: $0\le x\le 4 $ implies $0\le 4-x\le 4$ and then,
$$0\le x(4-x) =-(x-2)^2+4\le4$$
Thus directly implies your inequality.$$\dfrac{4}{x(4 - x)} \geq 1.$$

A: To get from $0−2<x−2<4−2$ to $4<(x−2)^2<4$ you have simply squared the entire inequality. This is invalid since you have not only led to a contradiction ($4 < k < 4$ implies no such $k$ exists), you have also mistakenly thought that if $a$ and $b$ are reals and $a < b$, then $a^2 < b^2$. This is clearly not true if $a$ and $b$ are not restricted in any other way. Since this step leads to a contradiction, the rest is invalid.
To create a logical and sound solution, the solution must not lead to any contradiction and cover all possible cases. One method to write a logical proof is to include as much (as necessary) details as possible. Try not to skip steps as it might lead to one missing some cases or using a "fact" that hasn't been shown to be true yet. When the details are there, make them clear and concise.
One possible method I propose for this problem is using the AM-GM inequality. Since $0 < x < 4$, both $x$ and $(4-x)$ are positive. Use it on $x(4-x)$ to derive $\sqrt{x(4-x)} \le \frac{x+(4-x)}{2}$. You may continue from here on.

A: We can do this proof by contradiction: We want to prove $P\rightarrow Q$ and we prove it by assuming $P$ and $\neg Q$, and getting a contradiction.
Suppose $0<x<4$ with $x\in\mathbb{R}$, and the inequality $\dfrac{4}{x(x-4)}\geq 1$ does not hold.
Then we have $0<x,0<4-x$ (both follow from $0<x<4$) and $\dfrac{4}{x(x-4)}<1$, and we have:
\begin{align*}
\dfrac{4}{x(4-x)}&<1 & &\\
4&<x(4-x) & &\text{[multiplying both sides by $x(x-4)>0$]}\\
0&<x(4-x)-4\\
0&<-x^2+4x-4\\
x^2-4x+4&<0\\
(x-2)^2&<0
\end{align*}
which is absurd because every squared real number is positive.
This contradiction allows us to conclude that $\dfrac{4}{(x-4)}\geq 1$.


text:
Q: How to avoid unwanted imports on IntelliJ IDEA 2016.3.2? Frequently, when writing variables with type String, after I write the type declaration, IJ adds automatically the following import:
import com.sun.org.apache.xpath.internal.operations.String;

Afterward, when I assign a string value to the variable, I get the following error popup:

Incompatible types:
Required: com.sun.org.apache.xpath.internal.operations.String
Found: java.lang.String

After I remove the unwanted import, the problem is solved.  But this import keeps reappearing, not on every String I declare, but frequently enough to be a nuisance.
How to prevent IJ from inserting this import?


text:
Q: "Your npm version is outdated." but it's not. While install yo On Windows 7 64 bit. Installed Node.js via wizard which gave me npm.
I run npm install -g yo and get the following
Your npm version is outdated.
Complete output:
C:\Users\dlite922>npm install -g yo
|

> spawn-sync@1.0.11 postinstall C:\Users\dlite922\AppData\Roaming\npm\node_modules\yo\node_modules\cross-spawn\node_modules\spaw
> node postinstall

C:\Users\dlite922\AppData\Roaming\npm\yo -> C:\Users\dlite922\AppData\Roaming\npm\node_modules\yo\lib\cli.js

> yo@1.4.7 postinstall C:\Users\dlite922\AppData\Roaming\npm\node_modules\yo
> yodoctor

Yeoman Doctor
Running sanity checks on your system

√ Global configuration file is valid
√ NODE_PATH matches the npm root
√ Node.js version
× npm version

Your npm version is outdated.

Upgrade to the latest version by running:
npm install -g npm

See this guide if you're having trouble upgrading:
https://github.com/npm/npm/wiki/Troubleshooting#upgrading-on-windows

√ No .bowerrc file in home directory
√ No .yo-rc.json file in home directory

Found potential issues on your machine :(
yo@1.4.7 C:\Users\dlite922\AppData\Roaming\npm\node_modules\yo
├── titleize@1.0.0
├── array-uniq@1.0.2
├── figures@1.3.5
├── user-home@1.1.1
├── opn@1.0.2
├── async@1.2.1
├── humanize-string@1.0.1 (decamelize@1.0.0)
├── sort-on@1.2.0 (dot-prop@2.1.0)
├── string-length@1.0.0 (strip-ansi@2.0.1)
├── yeoman-character@1.0.1 (supports-color@1.3.1)
├── findup@0.1.5 (commander@2.1.0, colors@0.6.2)
├── meow@3.1.0 (object-assign@2.1.1, minimist@1.1.1, camelcase-keys@1.0.0, indent-string@1.2.1)
├── yosay@1.0.4 (ansi-regex@1.1.1, pad-component@0.0.1, ansi-styles@2.0.1, word-wrap@1.0.3, strip-ansi@2.0.1, minimist@1.1.1, take
├── chalk@1.0.0 (escape-string-regexp@1.0.3, ansi-styles@2.0.1, supports-color@1.3.1, strip-ansi@2.0.1, has-ansi@1.0.3)
├── root-check@1.0.0 (sudo-block@1.2.0, downgrade-root@1.1.0)
├── repeating@1.1.3 (is-finite@1.0.1)
├── configstore@1.0.0 (object-assign@2.1.1, xdg-basedir@1.0.1, osenv@0.1.1, graceful-fs@3.0.8, uuid@2.0.1, mkdirp@0.5.1)
├── update-notifier@0.5.0 (is-npm@1.0.0, latest-version@1.0.0, semver-diff@2.0.0)
├── package-json@1.2.0 (registry-url@3.0.3)
├── got@3.2.0 (lowercase-keys@1.0.0, timed-out@2.0.0, is-stream@1.0.1, prepend-http@1.0.1, object-assign@2.1.1, nested-error-stack
fy@3.4.1)
├── npm-keyword@1.1.1 (registry-url@3.0.3, got@2.9.2)
├── fullname@1.1.0 (npmconf@2.1.2)
├── cross-spawn@0.4.0 (lru-cache@2.6.4, spawn-sync@1.0.11)
├── yeoman-environment@1.2.5 (untildify@2.0.0, escape-string-regexp@1.0.3, log-symbols@1.0.2, diff@1.4.0, text-table@0.2.0, debug@
├── lodash@3.9.3
├── yeoman-doctor@1.4.0 (object-values@1.0.0, log-symbols@1.0.2, each-async@1.1.1, semver@4.3.6, bin-version-check@2.1.0, twig@0.8
├── inquirer@0.8.5 (ansi-regex@1.1.1, cli-width@1.0.1, through@2.3.7, readline2@0.1.1, rx@2.5.3)
└── insight@0.6.0 (object-assign@2.1.1, async@0.9.2, lodash.debounce@3.1.0, os-name@1.0.3, tough-cookie@1.2.0, request@2.57.0)

Yet I have a pretty recent npm version:
C:\Users\dlite922>npm -v
2.10.1

I followed the troubelshooting and put my %appdata% npm BEFORE nodejs in my %PATH% list, but still get the response above.
Any luck?
PS: By the way this mean stack is so disorganized. There's 50 million ways of installing and all advertise a quick two step installation on their frontpage like it's the easiest thing in the world. Then everybody feels stupid when the 20 pre-requisites they assumed was installed does not work. Web App Development future is in shambles if javascript is leading the way these days. I thought PHP days were bad. lol
/endRant

A: The yo package isn't detecting your npm version properly. The output of the installation indicates that it installed correctly.


text:
Q: What are ways to detect running under windows 10 emulation? Since a binary built for Ubuntu may now run under the Win10 "Ubuntu subsystem" -  how can it detect this? (besides of poking in obscure corners of sysfs, /dev and so on)

A: The WSL faq does not show anything about identifying bash on windows.
Notable though:  Bash for Windows will have a mount point for the Windows devices. So when a ...
/mnt/c:

exists you are using bash on Windows (remark: that FAQ from Microsoft is probably wrong and it is /mnt/c and not /mnt/c:. Same applies for D: and other drive letters (that are disks).

A: This looks like one of possibilities:
cat /proc/sys/kernel/osrelease

Under WSL it contains "Microsoft".