Q: Angularjs ui sortable - Replace content of dropped item

{{ input.text }}

 place your elements here

var mainInputs = function(){
    return [
    {
        type: 'radio',
        text: 'Radio group',
        "content_to_drop": {
            type: 'radio',
            contents: [{
                text: 'radio 1',
                value: '1'
            },{
                text: 'radio 2',
                value: '2'
            },{
                text: 'radio 3',
                value: '3'
            }]
        }
    },
    {
        type: 'checkbox',
        text: 'Checkbox Input',
        "content_to_drop": {
            type: 'checkbox',
            contents: [{
                text: 'checkbox 1',
                value: '1'
            },{
                text: 'checkbox 2',
                value: '2'
            },{
                text: 'checkbox 3',
                value: '3'
            }]
        }
    }
    ];
};

This is a Drag and drop example.
One of the elements being dragged will be inserted inside column array.
My problem:
Instead of adding the whole object, I just only want the "content_to_drop" object to be added inside the column array. Is there any possibility of doing this?
For a better look:
https://jsfiddle.net/ssftkp96/

A: You can do the following:
var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop); // clone
$scope.column.push(newObj);

Or if you want the drop target to only have a single object you must provide it in the form of an array:
var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop);
$scope.column = [newObj];

var myApp = angular.module('myApp', ['ui.sortable']);

myApp.controller('MainCtrl', function($scope) {

  $scope.mainInputs = [];
  $scope.column = [];

  var mainInputs = function() {
    return [{
      type: 'radio',
      text: 'Radio group',
      content_to_drop: {
        type: 'radio',
        contents: [{
          text: 'radio 1',
          value: '1'
        }, {
          text: 'radio 2',
          value: '2'
        }, {
          text: 'radio 3',
          value: '3'
        }]
      }
    }, {
      type: 'checkbox',
      text: 'Checkbox Input',
      content_to_drop: {
        type: 'checkbox',
        contents: [{
          text: 'checkbox 1',
          value: '1'
        }, {
          text: 'checkbox 2',
          value: '2'
        }, {
          text: 'checkbox 3',
          value: '3'
        }]
      }
    }];
  };

  $scope.mainInputs = mainInputs();

  $scope.sortableSection = {
    connectWith: ".connected-apps-container",
    update: function(event, ui) {
      if ( // ensure we are in the first update() callback
        !ui.item.sortable.received &&
        // check that it's an actual moving between the two lists
        ui.item.sortable.source[0] !== ui.item.sortable.droptarget[0]) {
        ui.item.sortable.cancel(); // cancel drag and drop

        var newObj = jQuery.extend({}, ui.item.sortable.model.content_to_drop);
        $scope.column.push(newObj);
        // Or for a single object in the drop target, it must be provided as an Array:
        //$scope.column = [newObj];
      }
    }
  };
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

{{ input.text }}

        place your elements here

{{ column | json }}


Q: Why am I getting "no such file or directory" for an opencv file that exists when compiling in Ubuntu? I'm trying to use the OpenCV library in C++ (VSCode), so I have the statement #include <opencv4/opencv2/imgproc/imgproc.hpp>. When I try to compile using gcc in Ubuntu, however, I get the following error message:
/usr/local/include/opencv4/opencv2/imgproc/imgproc.hpp:48:10: fatal error: opencv2/imgproc.hpp: No such file or directory
 #include "opencv2/imgproc.hpp"

I'm fairly new to C++ and Ubuntu in general so I have no idea why this is happening, as I double checked and the file absolutely exists. In fact, even though it's apparently skipped the imgproc folder in finding the file, imgproc.hpp exists both in opencv2 and in the folder imgproc inside opencv2 anyway. How do I get this to work?

A: Did you try using #include "opencv4/opencv2/imgproc/imgproc.hpp" instead?


Q: Importing an old project in updated Android version While Running or importing a project in newer version of Android Studio got the following error even after successfully built
 - Could not find com.android.tools.build:aapt2:3.3.0-5013011.
Searched in the following locations:
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom
  - file:/C:/Users/dimi1/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar
  - https://jcenter.bintray.com/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011.pom
  - https://jcenter.bintray.com/com/android/tools/build/aapt2/3.3.0-5013011/aapt2-3.3.0-5013011-windows.jar
Required by:
    project :app

This is the error message I receive. I downloaded an older project and found solutions to the other error messages. Yet, how can I fix this problem/error message?

A: According to the directories, I believe it is a problem with the Android SDK. Try reinstalling Android Studio (but keep the project files), which will also reinstall the Android SDK with it. If that doesn't work, go to https://developer.android.com/studio/#downloads, scroll down to command-line tools only, and download the right version of the Android SDK based on your OS. Go through the install process and hopefully that should fix your issue.


Q: modifying styles in child component modifies stack order? I'm trying to use @use-gesture/react's useDrag to ... drag things around. Specifically, some MUI components whose styling gets dynamically updated.
I have a component wrapped in a div tied to the bind hook from useDrag:
return (

  <MyComponent isDraggable={logic} isShadow={logic} /> // <- Instance 1

)

When you click on the div, I shadow out the original element, and create a new copy of the component in a createPortal portal tied to the document body, such that you can drag it around:
const dragObjectPortal = dragState && dragState.pointerStartInfo
    ? createPortal(

            <MyComponent isDragged />                 // <- Instance 2

,
        document.body
      )
    : null;

Instance 1 renders fine. When I click on it, the state updates, it gets greyed out, the portal is created attached to the body, and Instance 2 renders fine. However, when I drag Instance 2 around, the movement is constrained by the borders of Instance 1.
The return from MyComponent is something like:
return (
  <Card
    sx={{
      position: 'relative',
      zIndex: 0,
      py: 2,
      px: 3,
      cursor: 'default',
      touchAction: 'none',
      ...(!!isDraggable) ? cardSxDraggable : {},
      ...(!!isShadow) ? cardSxShadow : {}
    }}
  >
    <Box
      sx={{
        width: 300,
        height: 300,
        ...(!!isShadow) ? {bgcolor: 'text.disabled'} : {bgcolor: 'primary.main'}
      }}
    >
    </Box>
  </Card>
)

It took ~ forever for me to figure this out, but if I remove the call to Instance 1, and replace it with inline MUI components from the above return (still dynamically styled), it works fine. So, something about the dynamic styling happening in a component, rather than in the main app's return itself, is ... I don't know ... causing some resetting of the stacking order or something.
Inline demo (works as expected)
Component demo (motion constrained)
But in the actual app I'm writing, I need an arbitrary number of these components. What do I have to do to fix it so that it doesn't ... do whatever it's doing to mess with useDrag?


Q: What is the relation between water damage and a cracked iPhone screen? This morning I took my iphone 5c to the genius bar and they refused to repair my cracked screen of the iphone initially agreeing to repair and then backing off citing water damage.
My iPhone is in standard 1-year warranty yet, so I don't understand what the connection between water damage and a cracked screen is.
Can someone explain Apple's reasoning or decision?

A: Just like an automotive repair service, some damage costs more to repair than it would cost to make a new vehicle. In car terms, your phone is "totaled" and the physical damage to the screen alone lies outside the warranty.

*

*You could buy a new phone from the vendor and then submit that cost to your insurance company if it covers the accidental (or not) damage to your property for reimbursement.

*You could ask Apple why they aren't offering you a "partial repair" - where you acknowledge that some damage is present and want a limited repair and then forgo the warranty on the repaired phone. My guess is they decided that all Apple repaired phones need to pass all tests and they literally can't even know how much liquid damage has spread without entirely reworking the phone.

*You could seek repair from a company or person other than Apple.

Liquid damage is expensive to even diagnose since the small cracks in an iPhone ensure that water can and will go everywhere. If corrosive salts are coating the electronics you now have a safety and reliability concern. The cost to inspect and test every single part is akin to painstakingly refurbishing a 1971 Hemi 'Cuda convertible that you found rusting in a field. In that case, there were external factors that made the cost to refurbish the product economically or socially pleasing.

A: There might be corrosion inside the device making it a pain or very expensive to replace parts which can potentially start to rot.
Once the water indicator in your device (sim card slot) has been colored ree, it will void all warranty.
You can still try to call Apple and explain the problem and try for the best

A: bmike pretty much approached the reason. Here's the actual reason in simple terms:
When Apple does a repair, they give you back a product that they guarantee is working. They stand behind it. Even if it's out of warranty, they give you a 90 day warranty. With liquid damage, for the reasons bmike stated in his answer, they CANNOT guarantee that you have a fully working to factory standards and longevity phone.  For this reason they decline to do the repair.

A: This is illegal, if they refused to repair it because of ‘water damage’. Apple lost a huge lawsuit in Australia wherein they had to admit that their moisture sensors can turn red/pink just from humidity and not necessarily because a device has actually been in water. Because of this admission they are required by law to repair or replace any device which is malfunctioning under warranty regardless of the color of the sensor. If you do some google-fu, you can find documentation of water damage not voiding warranty on Apple’s own site.


Q: Changed codomain of inverse trigonometric functions If codomain of  $\arcsin(x)$ is $(\pi/2 , 3\pi/2)$  and codomain of $\arccos(x)$ is $(\pi , 2\pi)$ then what should be $\arcsin + \arccos$ equal to ?
I thought of putting $x = \sin \theta$
But then stuck , what to do next ?

A: Let $\theta=\sin^{-1}x$. Then,
$$x=\sin\theta$$
$$x=\cos\left(\frac{\pi}2-\theta\right)$$
$$\cos^{-1}x=\cos^{-1}\left(\cos\left(\frac{\pi}2-\theta\right)\right)$$
Since $\theta=\sin^{-1}x$, we have $\theta\in\left(\frac{\pi}2,\frac{3\pi}2\right)$.
$$\frac{\pi}2-\theta\in(-\pi,0)$$
$$\cos\left(\frac{\pi}2-\theta\right)=\cos\left(\frac{\pi}2-\theta+2\pi\right)$$
where $\frac{\pi}2-\theta+2\pi\in(\pi,2\pi)$.
Thus,
$$\cos^{-1}x=\cos^{-1}\left(\cos\left(\frac{\pi}2-\theta+2\pi\right)\right)=\frac{5\pi}2-\theta=\frac{5\pi}2-\sin^{-1}x$$
$$\sin^{-1}x+\cos^{-1}x=\frac{5\pi}2$$

A: I'll denote by $\arcsin_s$ and $\arccos_s$ these two “shifted” functions.
Since $\arcsin_s x+\arccos_s x$ is easily seen to be constant, just compute it for $x=0$.
Why is it constant? Because the derivative of $\arcsin_s x$ is $1/\sqrt{1-x^2}$ and the derivative of $\arccos_s x$ is $-1/\sqrt{1-x^2}$ (for $x\in(-1,1)$).


Q: Why does (1 >> 0x80000000) == 1? The number 1, right shifted by anything greater than 0, should be 0, correct?  Yet I can type in this very simple program which prints 1.
#include <stdio.h>

int main()
{
        int b = 0x80000000;
        int a = 1 >> b;
        printf("%d\n", a);
}

Tested with gcc on linux.

A: 6.5.7 Bitwise shift operators:

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

The compiler is at license to do anything, obviously, but the most common behaviors are to optimize the expression (and anything that depends on it) away entirely, or simply let the underlying hardware do whatever it does for out-of-range shifts.  Many hardware platforms (including x86 and ARM) mask some number of low-order bits to use as a shift-amount.  The actual hardware instruction will give the result you are observing on either of those platforms, because the shift amount is masked to zero.  So in your case the compiler might have optimized away the shift, or it might be simply letting the hardware do whatever it does.  Inspect the assembly if you want to know which.

A: according to the standard, shifting for more than the bits actually existing can result in undefined behavior. So we cannot blame the compiler for that.
The motivation probably resides in the "border meaning" of 0x80000000 that sits on the boundary of the maximum positive and negative together (and that is "negative" having the highmost bit set) and on certain check that should be done and that the compiled program doesn't to to avoid to waste time verifying "impossible" things (do you really want the processor to shift bits 3 billion times?).

A: It's very probably not attempting to shift by some large number of bits.
INT_MAX on your system is probably 2**31-1, or 0x7fffffff (I'm using ** to denote exponentiation).  If that's the case, then In the declaration:
int b = 0x80000000;

(which was missing a semicolon in the question; please copy-and-paste your exact code) the constant 0x80000000 is of type unsigned int, not int.  The value is implicitly converted to int.  Since the result is outside the bounds of int, the result is implementation-defined (or, in C99, may raise an implementation-defined signal, but I don't know of any implementation that does that).
The most common way this is done is to reinterpret the bits of the unsigned value as a 2's-complement signed value.  The result in this case is -2**31, or -2147483648.
So the behavior isn't undefined because you're shifting by value that equals or exceeds the width of type int, it's undefined because you're shifting by a (very large) negative value.
Not that it matters, of course; undefined is undefined.
NOTE: The above assumes that int is 32 bits on your system.  If int is wider than 32 bits, then most of it doesn't apply (but the behavior is still undefined).
If you really wanted to attempt to shift by 0x80000000 bits, you could do it like this:
unsigned long b = 0x80000000;
unsigned long a = 1 >> b;    // *still* undefined

unsigned long is guaranteed to be big enough to hold the value 0x80000000, so you avoid part of the problem.
Of course, the behavior of the shift is just as undefined as it was in your original code, since 0x80000000 is greater than or equal to the width of unsigned long.  (Unless your compiler has a really big unsigned long type, but no real-world compiler does that.)
The only way to avoid undefined behavior is not to do what you're trying to do.
It's possible, but vanishingly unlikely, that your original code's behavior is not undefined.  That can only happen if the implementation-defined conversion of 0x80000000 from unsigned int to int yields a value in the range 0 .. 31.  IF int is smaller than 32 bits, the conversion is likely to yield 0.

A: well read that maybe can help you
expression1 >> expression2
The >> operator masks expression2 to avoid shifting expression1 by too much.
That because if the shift amount exceeded the number of bits in the data type of expression1, all the original bits would be shifted away to give a trivial result.
Now for ensure that each shift leaves at least one of the original bits,
the shift operators use the following formula to calculate the actual shift amount:
mask expression2 (using the bitwise AND operator) with one less than the number of bits in expression1.
Example
var x : byte = 15;
// A byte stores 8 bits.
// The bits stored in x are 00001111
var y : byte = x >> 10;
// Actual shift is 10 & (8-1) = 2
// The bits stored in y are 00000011
// The value of y is 3
print(y); // Prints 3

That "8-1" is because x is 8 bytes so the operacion will be with 7 bits. that void remove last bit of original chain bits


Q: Check for specific naming convention I have a directory where users are saving their excel files that should adhere to a specific naming convention:
XX-TestFile.xlsx

where XX is a variable digit and -TestFile.xlsx should always be the same and not change. I'd like to be able to check through a batch job if files in the directory adhere to a specific naming convention.
If filename is misspelled, i.e. XX-TetsFiel.xlsx, XX is not a digit like 02 or even XX-testfile.xlsx (all lowercase), then files should move to an Error directory.
I am using below to move the files to achieve this. I am testing with 11-testFiel.xlsx and it works just fine.
@echo off

for /f "delims=" %%a in ('dir /b *.xlsx ^| findstr /v "[0-9][0-9]-TestFile.xlsx"') do move "%%a" "C:\Temp\Archive\Error"

However, dir /b *.xlsx | findstr /v "[0-9][0-9]-TestFile.xlsx" allows for 109 possible combinations since XX is a variable with two digits like 02. However, I would now only like to check for specific file names of 20 possible digits like 02-TestFile.xlsx, 05-TestFile.xlsx, 10-TestFile.xlsx, etc. This list is fixed... So for example, if file is named 99-TestFile.xlsx I would still like to move it to an Error archive as it is an undesired file name. Can you suggest a solution for this?

A: Put the valid names into a text file (i.e. "ValidNames.txt") and use findstr with the /G option.
02-TestFile.xlsx
05-TestFile.xlsx
10-TestFile.xlsx
...

@echo off

for /f "delims=" %%a in ('
    dir /b *.xlsx ^| findstr /vxlg:"ValidNames.txt"
') do move "%%a" "C:\Temp\Archive\Error"


Q: groupby not behaving as expected The below code is suppose to sum the values of a list of tuples but when two or more tuples contain the same value , the tuple is just outputted once :
var data = List((1, "1") , (1, "one"))            //> data  : List[(Int, java.lang.String)] = List((1,1), (1,one))

        data = data.groupBy(_._2).map {
            case (label, vals) => (vals.map(_._1).sum, label)
        }.toList.sortBy(_._1).reverse

println(data)                                     //> List((1,1))

The output of above is List((1,1)) when I'm expecting List((1,1) , (1,"one"))
Does the groupBy function paramaters need to be tweaked to fix this ?

A: Actually, it does behave as expected. groupBy returns a map. When you map over a map, you construct a new map, where, of course, each key is unique. Here, you'd have the key 1 twice…
You should then call toList before calling map, not after.


Q: Javascript select specificed data from html tag Is is possible for javascript to work like PHP to find specificed data with keyword ? for example
other html from html page
<video> <source type="application/x-mpegurl" src="https://xxxx.xxxx/xxx.mp4"></video>
other html from html page

How can javascript work 2 steps 1st get html page (like php CURL) 2nd find specificed data (in my case is all in src="xx") ("source type="application/x-mpegurl" is keywork for finding) ?
Sorry but I'm very bad in javascript.

A: You can do this with javascript:
document.querySelector('source[type="application/x-mpegurl"]').src


Q: Fundamental group of family of rational varieties Let $X$ be a smooth, projective, simply connected variety over a field $k$ (i.e. $\pi_1^{\text{et}} = 1$). Let $f: Y \to X$ be a family of rational varieties parametrized by $X$, such that $Y$ is smooth and projective. Then $Y$ should be simply connected.
Is this right, and if so, how do I prove this?


Q: How to find the correct surface area of rotation Hi I am trying to find the surface area that is traced when the curve $8y^2=x^2-x^4$ is revolved about the $x$-axis. But I am having some trouble with it.
I know that for this in general I will want to use that about the x axis,
$$S= 2\pi \int_{C} y dS $$
I graphed the curve so I see what it looks like; a figure eight type shape with $x$ going from $-1$ to $1$.
But my issue is how I should find $y(t)$.
 I think I could probably use symmetry to simplify as well. Can anyone help with this please?
It seems that there are some discrepancies with different answers from different users, leaving me feeling quite confused. I am still wondering, can no one answer this??

A: Using symmetry as you suggest, and using $y=\frac{1}{\sqrt{8}}x\sqrt{1-x^2}$ in the first quadrant,
$\displaystyle S=2\int_0^12\pi r(x)\sqrt{1+\left(\frac{dy}{dx}\right)^2}dx=2\int_0^1 2\pi\cdot\frac{1}{\sqrt{8}}x\sqrt{1-x^2}\cdot\sqrt{1+\frac{1}{8}\frac{(1-2x^2)^2}{1-x^2}}dx$
$\hspace{.2 in}\displaystyle=\frac{4\pi}{\sqrt{8}}\int_0^1 x\sqrt{1-x^2+\frac{1}{8}(1-2x^2)^2}dx$
$\hspace{.2 in}\displaystyle=\frac{4\pi}{8}\int_0^1 x\sqrt{8-8x^2+1-4x^2+4x^4}\;dx=\frac{\pi}{2}\int_0^1x\sqrt{4x^4-12x^2+9}\;dx$
$\hspace{.2 in}\displaystyle=\frac{\pi}{2}\int_0^1x\big|2x^2-3\big|dx$.  $\;\;\;$(Now simplify and integrate.)

Alternate solution:  $\;\;$Using symmetry, and the parametrization
$x=\cos t, \;y=\frac{1}{\sqrt{8}}\sin t\cos t,\; 0\le t\le\frac{\pi}{2},$ for the part of the curve in Quadrant I gives
$\displaystyle S=2\int_0^\frac{\pi}{2}2\pi r(t)\sqrt{\left(\frac{dx}{dt}\right)^2+\left(\frac{dy}{dt}\right)^2}dt=2\int_0^\frac{\pi}{2} 2\pi\left(\frac{1}{\sqrt{8}}\sin t\cos t\right)\sqrt{\sin^2 t+\frac{1}{8}(\cos^2 t-\sin^2 t)^2} dt$
$\hspace{.2 in}\displaystyle=\frac{4\pi}{8}\int_0^\frac{\pi}{2}(\sin t\cos t)\sqrt{8\sin^2t+(1-2\sin^2 t)^2}dt=\frac{\pi}{2}\int_0^\frac{\pi}{2}(\sin t\cos t)\sqrt{(1+2\sin^2 t)^2}dt$
$\hspace{.2 in}\displaystyle=\frac{\pi}{2}\int_0^\frac{\pi}{2}(\sin t\cos t)(1+2\sin^2 t)dt$.  $\hspace{.2 in}$ (Now use $u=1+2\sin^2t, du=4\sin t\cos t dt$.)

A: Notice, consider an elementary right triangle with hypotenuse $dS$ & legs $dx$ & $dy$ then one should have,
$$dS=\sqrt{1+\left(\frac{dy}{dx}\right)^2}\ dx=\sqrt{1+\left(\frac{x-2x^3}{8y}\right)^2}\ dx$$
$$=\frac{x\sqrt{7-4x^2-4x^4}}{8y}\ dx$$
hence, the surface area of the solid $$2\pi\int_Cy\ dS=2\pi\int y\cdot \frac{x\sqrt{7-4x^2-4x^4}}{8y}\ dx$$
$$=\frac\pi4\int x\sqrt{7-4x^2-4x^4}\ dx$$
$$=\frac\pi4\int 2 x\sqrt{2-\left(x^2-\frac 12\right)^2}\ dx$$
let, $x^2-\frac 12=t\implies 2x\ dx=dt$,
$$=\frac\pi4\int\sqrt{2-t^2}\ dt$$


Q: How do I add hint text in otp text field and remain nodes focused when code entered in them? I am using the OtpTextField package and trying to add dashes (-) in text field as a hint text but unable to do so. There is a property in decoration which requires hasInputDecoration set to true, by doing so all the other decorations donot apply e.g showFieldAsBox sets to false. How can I achieve dashes in the otp text field. In addition I also want the box's border to be blue as text gets entered into the field and remain blue when all six fields are filled. Kindly help me out in this.
 OtpTextField(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                numberOfFields: 6,
                borderColor: color.primaryLight,
                filled: true,
                fillColor: color.primaryLight,
                borderRadius: BorderRadius.circular(8),
                showCursor: false,
                fieldWidth: 40,
                showFieldAsBox: true,
                disabledBorderColor: color.accentPrimary,
                decoration: InputDecoration(
                  hintText: "dfgdfgdf",
                  counterText: '',
                  hintStyle: TextStyle(
                    color: Colors.black,
                    fontSize: sizes!.fontRatio!*17,
                    fontWeight: FontWeight.bold,
                  )
                  ),
                //runs when a code is typed in
                onCodeChanged: (String code) {
                  viewModel().otpTextfield(code);
                },
                //runs when every textfield is filled
                onSubmit: (String verificationCode){
                  viewModel().otpTextfield(verificationCode);
                },
              // end onSubmit
              ),


Q: Attaching database to SQL Server 2016 using Management Studio 13 When using the right-click option on 'databases' the 'Attach' option is not listed.
CODE EXAMPLE WITH ERROR
I'm wondering if someone else has seen this before.
I also get an error when I run this code instead:
CREATE DATABASE testdb
ON (FILENAME = 'C:\databasefile.mdf')
FOR ATTACH_REBUILD_LOG
GO

My SQL Server version is
select @@version

Microsoft SQL Azure (RTM) - 12.0.2000.8   Jul 10 2018 21:38:33
Attach option is missing


Q: Is there anyway to set a binding on ALL scroll bars? I need to bind on scroll. Normally I would do this:
$(window).bind('scroll', someFunction);

The issue is that I have a scroll bar on a specific div, so this doesn't work. I need to do this:
$('.divClass').bind('scroll', someFunction);

This works fine. I want to do this for ALL my scroll bars though. Is there any good way to do this?

A: Use on to bing all your div scrollbar, including the dynamically created div.
$(document).on('scroll','.divClass', someFunction);

The .divClass must be present on all your container where you want to execute the someFunction function.


Q: Beds Online API - How to set the destination of the hotel and currency of the results Beds was provided the request example, but i cant set the destination of the hotel in here..
I just want to set manually the destination and set the currency using this request body given by the beds online.
$bedsonline_data = '{
    "stay": {
        "checkIn": "2019-01-01",
        "checkOut": "2019-01-05",
        "shiftDays": "2"
    },
    "occupancies": [
        {
            "rooms": "1",
            "adults": "1",
            "children": "1",
            "paxes": [
                {
                    "type": "AD",
                    "age": 30
                },
                {
                    "type": "AD",
                    "age": 30
                },
                {
                    "type": "CH",
                    "age": 8
                }
            ]
        }
    ],
    "hotels": {
        "hotel": [
            1067,1070,1075,135813,145214,1506,1508,1526,1533,1539,1550,161032,170542,182125,187939,212167,215417,228671,229318,23476
            ]
    }
}';

Where do i need to set that here in request body?

A: see the API docs ...the response will deliver a currency symbol.
and the example on Github explains how to set the destination:
$rqData = new \hotelbeds\hotel_api_sdk\helpers\Availability();
$rqData->destination = new Destination("PMI");


Q: Two way communication between one master and multiple nodes I have an architecture like this:

Master - It contains an RF communication chip. All nodes rely on Master to receive and send data to a central unit.
Node - It has some basic GPIO functionality. There can be 4-5 different types of nodes, each requiring a different GPIO count. For the sake of design simplicity, I am planning to throw a cheap microcontroller on each node and handle all GPIO locally. That way I just need a pre-defined control data packet from the master to do any task. Similarly, the node will send a pre-defined packet which the master will understand. The packet definition will contain the node type.
Nodes can change in number and preferably should be hot-swappable. Communication works like this:
Two nodes do not communicate directly.
Master can have a data packet which it wants to send to any particular node.
Any node can have a data packet which it wants to send to the master.
Max distance between a node and master will be less than 50 cm.
After some thought, this is the plan I came up with:
Make all nodes communicate over i2c. 16 nodes per master seems to be a good number so I can put a 4 bit DIP switch to set the i2c address of each node. Basically I will be doing a digital read on 4 gpio and setting the address accordingly.
This will be perfect when master wants to read or write data to the nodes.
For the time when node wants to send data, I need to have an additional GPIO per node which alerts the master that some data is present. Alternatively, I can keep reading all nodes in the loop and keep checking if some data is available.
Is there a better solution to this problem?

A: An alternative to I2C, you could consider CANbus for this solution.  It is arguably more complex, but slaves would be able to communicate back to the master on the same bus without needing a GPIO to indicate they have data available.  Also, collision detection is built into the design of the physical layer and protocol.
CAN controllers are available relatively cheap, although you need a transceiver for each node.
Other common multidrop buses you could consider:
RS-485: Simple to use, but you would be responsible for all the addressing.  I2C at least builds that in.
SPI: Useful if you have the I/O to spare for a slave select line for each node.  Based on your description above, this would probably not be the best route.

A: Your polling solution is probably the most classic.
One other solution is to do a broadcast poll.
Basically send a message that everyone hears which causes them to send a pulse a set delay after receiving the poll if they have data. The delay length being set by the devices address.
The master can then monitor the return signal and decode who has data to send and ask it directly.
Another technique is to build in a short delay between master transmission and slave acknowledge. Then use that window to allow slaves to squawk a single pulse that acts like an interrupt to the master. You would then need to poll them.


Q: Why is there a 'dangling else' scenario here? Do you think that this is a case of dangling else?
According to compiler and IIT professor it is. But I have doubt! According to theory, after condition of if is met, it will always process further only ONE statement (or one compound statement i.e. multiple statements enclosed within bracket). Here, after first if is processed and met, the compiler should consider immediate statement that is another if and check for the condition. If condition is not met, then compiler will not display any result as we don't have any associated else with printf function saying condition is not met (i.e. n is not zero).
Here, compiler should always associated given else in program with first if clause because all the statement given after first if is not enclosed in brackets. So, why there is a scenario of dangling else here?
#include <stdio.h>

void main(void)
{
  int n = 0;
  printf("Enter value of N: ");
  scanf("%d",&n);
  if (n > 0)
  if (n == 0)
    printf("n is zero\n");
  else
    printf("n is negative\n");
  getch();
}

A: Per Wikipedia's definition of dangling else, you do have a dangling else statement.
C makes your code unambiguous. Your code is interpreted as:
if (n > 0)
{
   if (n == 0)
   {
      printf("n is zero\n");
   }
   else
   {
      printf("n is negative\n");
   }
}

Had you meant the code to be interpreted as:
if (n > 0)
{
   if (n == 0)
   {
      printf("n is zero\n");
   }
}
else
{
   printf("n is negative\n");
}

you would be surprised.
FWIW, no matter which interpretation is used, your code is wrong.
What you need to have is:
if (n > 0)
{
   printf("n is positive\n");
}
else
{
   if (n == 0)
   {
      printf("n is zero\n");
   }
   else
   {
      printf("n is negative\n");
   }
}

or
if (n > 0)
{
   printf("n is positive\n");
}
else if (n == 0)
{
   printf("n is zero\n");
}
else
{
   printf("n is negative\n");
}

A: *

*if (n == 0) printf("n is zero\n"); else printf("n is negative\n"); is ONE statement and

*I strongly recommend not even paying any attention into learning the concept of danglings elses (unless it will show up in tests) but instead learning the concept of ALWAYS using curly brackets, because it helps reading the code and it helps preventing bugs especially when inserting debugging statements.

So write:
if (n > 0) {
    if (n == 0) {
        printf("n is zero\n");
    } else {
        printf("n is negative\n");
    }
}

or
if (n > 0) {
    if (n == 0) {
        printf("n is zero\n");
    }
} else {
    printf("n is negative\n");
}

and everything is clear to everyone.
BTW: Proper indentation - that might be broken due to copy&paste I admit - will help in reading code and preventing bugs, too.

A: +1 to @Bodo Thiesen's suggestion to always use curly braces. I suggest you also use clang-format to automatically format your code. It will it will ident everything correctly and generally make coding wonderful.
You can configure clang-format extensively to match your preferred style - this is your code clang-format'd in LLVM's house style.
#include <stdio.h>

void main(void) {
  int n = 0;
  printf("Enter value of N: ");
  scanf("%d", &n);
  if (n > 0)
    if (n == 0)
      printf("n is zero\n");
    else
      printf("n is negative\n");
  getch();
}


Q: PHP - PayPal Integration, failed running my custom transaction function after payment accepted I have tried using a tutorial script for PayPal payment in the past and it worked. Now it doesn't. The script is simple, all I need is this one page for processing payment:
<?php
  session_start();
  include ('mydbconfig.php');

  // payPal settings
  $paypal_email = 'seller@yahoo.com';
  $return_url = 'https://www.mytestsite.com/paypal-thanks.php';
  $cancel_url = 'https://www.mytestsite.com/paypal-cancel.php';
  $notify_url = 'https://www.mytestsite.com/paypal-notify.php';

  $item_name = $_POST['item_name'];
  $item_amount = $_POST['item_amount']; //price

  // check if paypal request or response
  if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
    // firstly append paypal account to querystring
    $querystring .= "?business=".urlencode($paypal_email)."&";

    // append amount& currency (£) to quersytring so it cannot be edited in html

    //the item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
    $querystring .= "item_name=".urlencode($item_name)."&";
    $querystring .= "amount=".urlencode($item_amount)."&";

    //loop for posted values and append to querystring
    foreach($_POST as $key => $value) {
      $value = urlencode(stripslashes($value));
      $querystring .= "$key=$value&";
    }

    // Append paypal return addresses
    $querystring .= "return=".urlencode(stripslashes($return_url))."&";
    $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
    $querystring .= "notify_url=".urlencode($notify_url);

    // Append querystring with custom field
    //$querystring .= "&custom=".USERID;

    // Redirect to paypal IPN
    header('location:https://www.paypal.com/cgi-bin/webscr'.$querystring);
    exit();

  } else { // response from Paypal

    // read the post from PayPal system and add 'cmd'
    $req = 'cmd=_notify-validate';
    foreach ($_POST as $key => $value) {
      $value = urlencode(stripslashes($value));
      $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
      $req .= "&$key=$value";
    }

    // assign posted variables to local variables
    $data['item_name'] = $_POST['item_name'];
    $data['item_number'] = $_POST['item_number'];
    $data['payment_status'] = $_POST['payment_status'];
    $data['payment_amount'] = $_POST['mc_gross'];
    $data['payment_currency'] = $_POST['mc_currency'];
    $data['txn_id'] = $_POST['txn_id'];
    $data['receiver_email'] = $_POST['receiver_email'];
    $data['payer_email'] = $_POST['payer_email'];
    $data['custom'] = $_POST['custom'];

    // post back to PayPal system to validate
    $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

    $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

    if (!$fp) {
      // HTTP ERROR
      header('location: https://www.mytestsite.com/paypal-error.php?tr='.$data['txn_id'].'&in='.$data['item_name'].'&pe='.$data['payer_email'].'&pa='.$data['payment_amount'].'&ps='.$data['payment_status']);

    } else {
      fputs ($fp, $header . $req);
      while (!feof($fp)) {
        $res = fgets ($fp, 1024);
        if (strcmp ($res, "VERIFIED") == 0) {
          //payment accepted, insert transaction to my database
          //function to insert transaction here

        } else if (strcmp ($res, "INVALID") == 0) {
          //something to do if failed

        }
      }
      fclose ($fp);
    }
  }
?>

After the process is completed, I checked and the payment is paid successfully, but my function or anything I wrote in //function to insert transaction here won't be executed. In the end I'm forced to do the function on paypal-thanks.php page. Is there something's wrong in the script?
Is this script can be used to send more than one item purchasing? My cart is my own custom made and I only want to send Item name, number, and price detail, and total price to PayPal order summary.
I checked the other PayPal integration questions here, and most of them direct me to PayPal tutorial, documentation, or integration wizard which're confusing. I use this simple script before because I can't understand PayPal documentation (and the sample code, it didn't even let me know where to start) :(
And lastly my ultimate question, is this script is the correct and secure way to do a payment transaction?

A: use this
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

instead of
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

i think it is better to use CURL instead of socket


Q: Erlang C-Node erl_errno symbol not found error I tried to use erl_errno as described in the erlang document: http://erlang.org/doc/man/erl_error.html#.
However, I'm getting a symbol not found problem during linking. I'm running on Mac and here's the how the program is linked:
g++ -L/usr/local/lib/erlang/lib/erl_interface-3.9.3/lib -o "roserl"  ./src/driver.o ./src/erl_bridge.o  -lei -lm -lerl_interface
I have already linked with libei and liberl_interface. What else is needed?

A: It is weird but you will have to do this in your header:
#ifndef _REENTRANT
#define _REENTRANT /* For some reason __erl_errno is undefined unless _REENTRANT is defined */
#endif

#include "erl_interface.h"
#include "ei.h"

This fixed the problem for me. Now I can use erl_errno.


Q: ActionScript: How to listen for an event from a different XML I have a popup screen in which the player enters their name and clicks OK. When OK is clicked I want the player's name to be passed to the main XML. How can I do this?
Here is the function in the main XML that handles the popup:
    private function NewHighScore():void{
        highScorePopup = PopUpManager.createPopUp(this, Popup, true) as Popup;
        highScorePopup.SetScore(playerscore);
        PopUpManager.centerPopUp(highScorePopup);
        playerName = highScorePopup.getName();
        trace(playerName);
    }

And here is the popup XML script:
        import mx.events.CloseEvent;
    import mx.managers.PopUpManager;

    import spark.events.TextOperationEvent;
    public var playerName:String;

    public function SetScore (playerScore:int):void{
        scoreDisplay.text = "You achieved a new high score of " + playerScore.toString();
    }

    protected function button1_clickHandler(event:MouseEvent):void{ remove(); }

    private function remove():void{ PopUpManager.removePopUp(this);}

    protected function titlewindow1_closeHandler(event:CloseEvent):void
    { remove();}

    protected function nameBox_changeHandler(event:TextOperationEvent):void
    {playerName = nameBox.text;}

    public function getName():String{
    return playerName;
    }

A: Waiting for player to enter their name is an asynchronous process, therefore you have to wait for an event dispatched by the popup. Since the popup closes itself (gets removed from stage) once OK button is clicked, you can listen on that popup for Event.REMOVED_FROM_STAGE event, and only then gather the data from the popup. Don't for get to remove the event listener from the popup so that you'll not leak the instance.
private function NewHighScore():void{
    highScorePopup = PopUpManager.createPopUp(this, Popup, true) as Popup;
    highScorePopup.SetScore(playerscore);
    PopUpManager.centerPopUp(highScorePopup);
    highScorePopup.addEventListener(Event.REMOVED_FROM_STAGE,getPlayerName);
}
function getPlayerName(event:Event):void {
    event.target.removeEventListener(Event.REMOVED_FROM_STAGE,getPlayerName);
    var popup:Popup=event.target as Popup;
    if (!popup) return;
    var playerName:String=popup.getName(); // now the name will be populated
    // do stuff with the name
}


Q: Record video using screenrecord error I am trying to use the adb shell screenrecord functionality on my S4 which is running 4.4. I keep getting this error
ERROR: unable to configure codec (err=-2147483648)
WARNING: failed at 1080x1920, retrying at 720x1280
Yes the video eventually gets recorded in the lower resolution. How can I record it in the highest resolution possible (even if you can suggest another method)?
Thank you


Q: Where to store value for duration of request Preamble
I'm developing a card game server in Rails. The application records what a player is expected to do via a tree of instances of the PendingAction model.
class Player < ActiveRecord::Base
  has_many :cards
  has_many :pending_actions
end

At any time, the player needs to act on any leaf PendingActions - there may be more than one, for instance:
1. End turn
|
+- 2. Do thing A
|  |
|  + 3. Do thing pre-A
|
+- 4. Do thing B
   |
   + 5. Do thing pre-B

The view code presents the player with one or more forms, requesting their choice for each leaf action. For instance, in the above case, forms would be presented to solicit input for actions 3 and 5.
When the player makes a choice for, say, action 5, that action is destroyed. However, processing their choice may cause them to need to make another choice before the parent (action 4) can happen. Like so:
1. End turn
|
+- 2. Do thing A
|  |
|  + 3. Do thing pre-A
|
+- 4. Do thing B
   |
   + 6. Do other thing pre-B

Action 4 therefore needs to be on-hand, so action 6 can be created as its child. At present, I am simply passing action 4 around as a function argument. However, I've just come across a situation where it would really help to be able to have access to it in a before_save hook on a Card object.
Question
Where is the best place to store an object, associated with a Player, that I can access from all models related to that Player, which is valid throughout - but not beyond - a single HTTP request?
I am running under Heroku, with 1 dyno - so I believe I'm single-threaded.

A: It depends on which environment you work, but lets assume that this is single-threaded environment. Next, first thought was to create instance attribute to manually assign and retrieve anything. It is will work fine when Player instance is the same for all places.
If not, I suggest to introduce class variable, some sort of cache, that will hold Player#id => <some_obj> reference, and with helper accessors, like Player#some_obj which will query Player for object by self.id.
That way you will be ensured that for all Player with the same Id, some_obj will be the same. Also, you will need to deside, when to empty that class-cache. For Rails, i suppose after_filter is good enough.


Q: The portals keep teleporting me back and forth I have a simple c# script to teleport me between two portals. The problem is that when I place the portals facing down, it keeps teleporting me between them. the script works fine when it is upright. I tried to make a cooldown so that it can't teleport me over and over. I also tried to place the destination above the portal.
Here is my code:
using UnityEngine;

public class portal : MonoBehaviour
{
    public GameObject portal2;
    public GameObject player;

    void OnTriggerEnter(Collider other)
    {
        if (player.transform.position != portal2.transform.position)
        {
            if(other.CompareTag("Player"))
            {
                player.transform.position = portal2.transform.position;
            }
        }
    }
}

A: Comparing the transform positions is not likely to be useful as even a tiny amount of offset in the float (think something as small as 0.0000001 will cause the condition to fail. I would suggest that when a player portals through to another portal, that you place them slightly in front of the portal, in addition to a small cooldown that prevents portal travel. You'll need to translate the players speed (not velocity, speed) to the direction (transform.forward) of the portal they exited as well to keep them moving in the right direction.


Q: How to hold the dynamic text box and its values after form submission fails I am using three dynamic textboxes in a form ,my problem is that when the form validation fails then i have to keep the user in that form ,Now my problem is that i  have to hold the values and those textbox also in the form ,how this is possible ?? i am giving a fiddle please suggest what can be done,
DEMO FIDDLE
Here is the fiddle
function GetDynamicTextBox(value) {
   return '<input class="txt1" name="DynamicTextBox" type="text" value="' + value + '" /> <input class="txt2 time" id="myPicker" class="time" type="text" /> <input name="phoneNum1" id="phoneNum1" class="time txt3"  type="text" /><input type="button" value="Remove" class="remove" />';
}

This is the code which is responsible for the creating dynamic textboxes


Q: How to abbreviate "deLuze"
Possible Duplicate:
How would you abbreviate surnames starting with Mc/O/D?

How would I abbreviate Jane deLuze?
If I were listing a numbe of people by initials, like John Doe or John Smith, I could use JD, JS etc.... but how would I do deLuze?

A: If possible, I would use JdL.  If absolutely constrained to two letters, then JL.

A: The MLA guideline for Spanish names says:

The Spanish de is not used before the last name when it stands
  alone.
example: Zayas, Maria de (María de Zayas)

The Chicago Manual of Style has an elaboration on this advice:

When the particle de appears in a Spanish name, the family name,
  under which the person is indexed, may be either the preceding or the
  following name (depending in part on how a person is known).

In the common spelling of my middle name (dePano), the de does not stand alone, and I've observed these variations:

*

*In the USA, my middle initial is considered to be D; on my driver's license, it's printed in all caps as DEPANO. My family has always spelled it DePano.

*My relatives in my native country consider the initial to be P, and continue to spell it dePano. It's filed under P.

Here, the "how a person is known" clause of the CMoS guideline comes into play, as well as the locale.

*

*In the USA, abbreviating Jane deLuze as J. D. likely would not cause any
confusion. Americans would tend to hear the name as starting with D.

*A Spanish-speaking locale might require J. L., or even J.D.L., to
follow convention. (For example, I've seen Pedro de la Rosa
abbreviated as Pedro D.L.R.)


Q: capistrano symlink permission denied I am using cap deploy to deploy to staging. cap deploy:setup created the releases and shared folder.
This is the deploy.rb code.
set :stages, %w(staging production)
set :default_stage, "staging"
set :stage_dir, "capistrano"
require 'capistrano/ext/multistage'

set :application, "application"
set :repository,  "git@github.com:owner/#{application}.git"
set :scm, :git

set :local_user, ENV['USER'] || ENV['USERNAME'] || "unknown"
set :user, "server_owner"

set :deploy_via, :copy

set :use_sudo, false
set :copy_remote_dir, "/home/#{user}/tmp/capistrano"

namespace :deploy do
  desc "Change Permissions"
  task :change_permissions, :except => { :no_release => true } do
    run "find #{current_path}/ -type d -exec chmod 755 {} \\;"
    run "find #{current_path}/ -type f -exec chmod 644 {} \\;"
  end

  desc "Create symlinks for shared items"
  task :update_shared_symlinks, :except => { :no_release => true} do
     < ln -s command to create the links>
  end
end

before "deploy:finalize_update", "deploy:update_shared_symlinks"

And this is the staging code
role :app, "ipaddress"

set :branch, "staging"

set :deploy_to, "/home/#{user}/_#{application}_beta/"

When deploying with cap deploy i get the following error
ln: creating symbolic link `/home/narayan/_instaprint_beta/releases/20130130102815/': Permission denied
Can anyone tell me why this is happening?

A: Two things:

*

*Use chmod straight away instead of a find and exec, like so: chmod 755 #{current_path}

*Check if the server_owner user has permission to current_path. If not, then use sudo like so: sudo "chmod 755 #{current_path}"


Q: Firefox driver for selenium where to download the firefox driver for selenium?
I only find this, and herer is not the driver file for download
https://code.google.com/p/selenium/wiki/FirefoxDriver
NOTE: I already have Selenium Webdriver IDE for Firefox but the script aks me to find firefox driver
Can I use firefox in for webdriver in C# or its only capable for java?

A: The best approach for C# projects is to install the WebDriver NuGet, because if there are any updates it will be notified. Just install NuGet Manager and search for WebDriver.
After that just use the following code:
IWebDriver driverOne = new FirefoxDriver();
IWebDriver driverTwo = new InternetExlorerDriver("C:\\PathToMyIeDriverBinaries\");

The FirefoxDriver is included in the NuGet. However, you need to download manually the ChromeDriver from here: https://code.google.com/p/selenium/wiki/ChromeDriver
You can find ten mins tutorial with images here:
http://automatetheplanet.com/getting-started-webdriver-c-10-minutes/

A: You just need to include/import driver to your project if you want to use firefox unlike for CHROME you need to store the jar file or Exe to a particular location and then then you just need to call it in your project
demo program
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;

    public class Firefox {

         public void returnFirefoxBrowser(){
             WebDriver driver = new FirefoxDriver();
        }
    }

chrome
         File file = new File(
              "//Users//Documents//workspace//SELENIUM//chromedriver");
         System.setProperty("webdriver.chrome.driver",file.getAbsolutePath());
         WebDriver driver_chrome;
         driver_chrome = new ChromeDriver();


Q: Problems with updating Xamarin.Android.Support.Annotations 28.0.0 After New Years are over I'm at the office again and started to update the packages of my Xamarin project, that I wrote over the last two months.
I got the error:
Could not install package 'Xamarin.Android.Support.Annotations 28.0.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.6.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

What do I have to do, to handle the error?


Q: proving strong induction in coq from scratch I am in the middle of proving the equivalence of weak and strong induction.
I have a definition like:
Definition strong_induct (nP : nat->Prop) : Prop :=
  nP 0 /\
  (forall n : nat,
    (forall k : nat, k <= n -> nP k) ->
    nP (S n))
.

And I would like to prove the following, and wrote:
Lemma n_le_m__Sn_le_Sm : forall n m,
  n <= m -> S n <= S m
.

Lemma strong_induct_nP__nP_n__nP_k : forall (nP : nat->Prop)(n : nat),
  strong_induct nP -> nP n ->
  (forall k, k < n -> nP k)
.
Proof.
  intros nP n [Hl Hr].
  induction n as [|n' IHn].
  - intros H k H'. inversion H'.
  - intros H k H'.
    inversion H'.
    + destruct n' as [|n''] eqn : En'.
      * apply Hl.
      * apply Hr.
        unfold lt in IHn.
        assert(H'' : nP (S n'') -> forall k : nat, k <= n'' -> nP k). {
          intros Hx kx Hxx.
          apply n_le_m__Sn_le_Sm in Hxx.
          apply IHn.
          - apply Hx.
          - apply Hxx.
        }

However I cannot continue the proof any further.
How can I prove the lemma in this situation?

A: Changing the place of forall in the main lemma makes it much easier to prove. I wrote it as follow:
Lemma strong_induct_is_correct : forall (nP : nat->Prop),
  strong_induct nP -> (forall n k, k <= n -> nP k).

(Also note that in the definition of strong_induct you used <= so it's better to use the same relation in the lemma as I did.)
So I could use the following lemma:
Lemma leq_implies_le_or_eq: forall m n : nat,
  m <= S n -> m <= n \/ m = S n.

to prove the main lemma like this:
Proof.
  intros nP [Hl Hr] n.
  induction n as [|n' IHn].
  - intros k Hk. inversion Hk. apply Hl.
  - intros k Hk. apply leq_implies_le_or_eq in Hk.
    destruct Hk as [Hkle | Hkeq].
    + apply IHn. apply Hkle.
    + rewrite Hkeq. apply Hr in IHn. apply IHn.
Qed.

This is much a simpler proof and also you can prove a prettier lemma using the lemma above.
Lemma strong_induct_is_correct_prettier : forall (nP : nat->Prop),
  strong_induct nP -> (forall n, nP n).
Proof.
  intros nP H n.
  apply (strong_induct_is_correct nP H n n).
  auto.
Qed.

Note: Usually after using a destruct or induction tactic once, it is not very helpful to use one of them again. So I think using destruct n' after induction n would not bring you any further.


Q: iOS Example (GLSprite) doesnt show anything i implemented the iOS example (GLSprite) for drawing images
but it doesnt show anything. the NSLogs say me, that everything
is initialized, so i dont know, why nothing is shown.
i want to load a png file and to rotate it.

*

*context loads

*framebuffer creates

*setupView finishes

*drawView finishes

No Errors. Everything seem to work fine except this black screen :)
Does anybody knows why?
h-file
#import <Foundation/Foundation.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>

@interface CJTEAGLView : UIView
{
GLint backingWidth;
GLint backingHeight;

EAGLContext *context;

GLuint viewRenderbuffer;
GLuint viewFramebuffer;
GLuint viewDepthRenderbuffer;

GLuint playerTexture;

BOOL animating;
BOOL displayLinkSupported;

NSInteger animationFrameInterval;

id displayLink;
}

@property (nonatomic) BOOL animating;
@property (nonatomic) NSInteger animationFrameInterval;

- (void)startAnimation;
- (void)stopAnimation;
- (void)drawView;

@end

m-file
@interface CJTEAGLView()
- (void)createFramebuffer;
 - (void)destroyFramebuffer;
- (void)setupView;

@end

const GLfloat spriteVertices[] =
{
-0.5f, -0.5f,
0.5f, -0.5f,
-0.5f,  0.5f,
0.5f,  0.5f,
};

const GLshort spriteTexcoords[] =
{
0, 0,
1, 0,
0, 1,
1, 1,
};

@implementation CJTEAGLView

@synthesize animating;
@synthesize animationFrameInterval;

+ (Class) layerClass
{
return [CAEAGLLayer class];
}

- (id)initWithCoder:(NSCoder*)coder
{
if(self = [super initWithCoder:coder])
{
    CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;

    eaglLayer.opaque = YES;
    eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];

    context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];

    if(!context || ![EAGLContext setCurrentContext:context])
    {
        NSLog(@"Context failed");

        [self release];

        return nil;
    }

    animating = FALSE;
    displayLinkSupported = TRUE;
    animationFrameInterval = 1;
    displayLink = nil;

    [self createFramebuffer];
    [self setupView];
    [self drawView];
}

return self;
}

- (void)layoutSubviews
{
[EAGLContext setCurrentContext:context];

[self destroyFramebuffer];
[self createFramebuffer];
[self drawView];
}

- (void)createFramebuffer
{
glGenFramebuffersOES(1, &viewFramebuffer);
glGenRenderbuffersOES(1, &viewRenderbuffer);

glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDrawable>)self.layer];
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);

glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
}

- (void)destroyFramebuffer
{
glDeleteFramebuffers(1, &viewFramebuffer);
glDeleteRenderbuffers(1, &viewRenderbuffer);
glDeleteRenderbuffers(1, &viewDepthRenderbuffer);
}

- (NSInteger) animationFrameInterval
{
return animationFrameInterval;
}

- (void) setAnimationFrameInterval:(NSInteger)frameInterval
{
if (frameInterval >= 1)
{
    animationFrameInterval = frameInterval;

    if (animating)
    {
        [self stopAnimation];
        [self startAnimation];
    }
}
}

- (void) startAnimation
{
if (!animating)
{
    if (displayLinkSupported)
    {
        displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(drawView)];
        [displayLink setFrameInterval:animationFrameInterval];
        [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    }

    animating = TRUE;
}
}

- (void)stopAnimation
{
if (animating)
{
    if (displayLinkSupported)
    {
        [displayLink invalidate];
        displayLink = nil;
    }

    animating = FALSE;
}
}

- (void)setupView
{
CGImageRef playerImage;
CGContextRef playerContext;
GLubyte *playerData;
size_t playerWidth;
size_t playerHeight;

glViewport(0, 0, backingWidth, backingHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(-1.0f, 1.0f, -1.5f, 1.5f, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glClearColor(0, 0, 0, 1);

playerImage = [UIImage imageNamed:@"Cruiser.png"].CGImage;
playerWidth = CGImageGetWidth(playerImage);
playerHeight = CGImageGetHeight(playerImage);

if(playerImage)
{
    playerData = (GLubyte *) calloc(playerWidth * playerHeight * 4, sizeof(GLubyte));
    playerContext = CGBitmapContextCreate(playerData, playerWidth, playerHeight, 8, playerWidth * 4, CGImageGetColorSpace(playerImage), kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(playerContext, CGRectMake(0, 0, (CGFloat)playerWidth, (CGFloat)playerHeight), playerImage);
    CGContextRelease(playerContext);

    glGenTextures(1, &playerTexture);
    glBindTexture(GL_TEXTURE_2D, playerTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, playerWidth, playerHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, playerData);

    free(playerData);

    glEnable(GL_TEXTURE_2D);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);
}
}

- (void)drawView
{
[EAGLContext setCurrentContext:context];

glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
glRotatef(3.0f, 0.0f, 0.0f, 1.0f);

glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER_OES];
}

@end


Q: How do I read time in min/hr in a dataframe get sales rate? I have a data frame which has hours in min for example 14:59 where 60:00 (max) is 1 (hr).
I tried reading this dataframe using the code below I got an error "Can only use .dt accessor with datetimelike values"
df['time sold'].dt.minute

My hope was after reading the date below to get the sale rate per min.
my data is
Name Sales Time
Jame 603   14:59
Sam  903   34:00
Lee  756   34:55

Is there a way to get how much each sold be the minute?
Name Sales Time    Sale Rate
Jame 603   14:59   xxxx
Sam  903   34:00   yyyy
Lee  756   34:55   zzzz

Please excuse the xyz just used them as place holders.

A: first add the HH to be able to convert it to a pandas timedelta:
df['Time'] = '00:'+df['Time'].astype(str)

then convert to timedelta
df['Time'] = pd.to_timedelta(df['Time'])

then make a new column equal to sales per minute
df['Sales Rate'] = df['Sales'] / (df['Time'].dt.total_seconds()/60)

output:
     Sales     Time Sales Rate
Jame   603 00:14:59    40.2447
Sam    903 00:34:00    26.5588
Lee    756 00:34:55    21.6516

A: You could do the following if you have datetime dtype in time column:
s = '''Name Sales Time
       Jame 603   14:59
       Sam  903   34:00
       Lee  756   34:55'''

df = (pd.read_csv(io.StringIO(s),
                  sep='\s+',
                  converters={'Time':lambda x: pd.to_datetime(x, format='%M:%S')})
      )

df['rate'] = df['Sales'] / (df['Time'].dt.minute + df['Time'].dt.second.div(60))


Q: JQuery UI add to accordion Here is the demo for the JQuery UI's accordion widget. I have one on my page, and the way to put items in it (as shown on the demo page) is like so:

Section 1

    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

Section 2

    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
    suscipit faucibus urna.

Section 3

    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.

List item one

List item two

List item three

Section 4

    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.

    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.

Notice how for every item, there is the following structure:
Title

Text

. I would like to be able to dynamically add to this accordion; however, when I tried to simply add that structure to the accordion it didn't work. I looked into my chrome console, and saw that JQuery adds all sorts of classes and properties to the bare-looking elements of the item. Now, of course the obvious way to solve this is instead of adding
Title
 to add

Title

And likewise for every other element. I know that this should work fine, but it looks ugly and I was wondering if JQuery has provided us with some nice function to do all this stuff for us. If it hasn't, can anyone suggest a less annoying way to do this?
EDIT: in response to all the answers suggesting to recreate the accordion: I know that that is probably a better idea than the method shown above, but is it possible to "accordion" only the block of HTML that I need as opposed to the whole accordion, which can get quite big?

A: Just recreate the accordion when you add new data to it:
$("#accordion").append(html).accordion('destroy').accordion();

A: The only critical HTML is the main structure:

Section 1

Section 2

You can put anything you want inside the DIV content panels.
WHen you add a a new set of h3 and div, destroy and recreate the accordion:
var newPanel='
New section

New content
';
$('#accordion').append(newPanel).accordion('destroy').accordion( /* options */ );


Q: Many to many hibernate mapping and intermediate table object How can I define  a many to many relationship in hibernate where the intermediate table maps to a object? I.e.
Build can have another build as dependency and this dependency can be selected in other builds too. The 'build dependency' object should look something like:
BuildDep{
   int id;
   Build parent;
   Build child;
   ....
}

mapping to the intermediate table having columns:
id, child_build_id, parent_build_id

Thank you

A: By definition, many-to-many associations can only be used when the association table does not have any other columns besides the foreign keys to the parent tables.
Instead, you should use two ManyToOne/OneToMany associations.
Here's a forum topic on this subject (with an example):
http://www.coderanch.com/t/218431/ORM/databases/Hibernate-Annotations-many-many-association


Q: Get text of a clicked button? Hi I am very new to java and android studio. I made a set of buttons in a fragment and used a for loop to set the text of each button....
For example:
for (int i = 0; i < letterBttns.length; i++) {
    letterBttns[i].setText(ethereal[i]);
}

What is the best way to get the text of a clicked button? Is there a short way to do it or the only way to do it is calling an onClick method for each button?
Because that seems like the long and easy way.

A: public class TestActivity extends AppCompatActivity implements View.OnClickListener {
    .....
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ....
        for (int i = 0; i < letterBttns.length; i++) {
            letterBttns[i].setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        String text = ((Button) v).getText().toString();
    }
}


Q: How to write a spirial function in python? I'm trying to write a function in python that takes two arguments (x,y), and returns an angle in degrees in a spiraling direction.
Suppose the center of the spiral is at location (x0,y0). Then given (0,0), it returns 45. Given some other point say (0,90) which is the second intersection from the top on the y axis, the angle is around 170. For any point not touching the red line, it should return an angle of what you would expect the direction to be. The spiral is just a general thing to show the direction of the angles.
Does anyone know how to write such a function?
Thanks

A: That's an Archimedean spiral curve. As the page says in polar coordinates the formula of the curve is r = aθ, usually the scalar a is 1 i.e. r = θ. Polar to cartesian conversion is
x = r cos θ, y = r sin θ

Hence
x = θ cos θ, y = θ sin θ

Varying θ from 0 to 6π would give the curve you've. When you vary the parameter θ and get x and y values what you get would be relative to the origin (0, 0). For your case, you've to translate i.e. move the points by the x and y offset to position it accordingly. If you want a bigger version of the same curve you've to scale (before translation) i.e. multiply both x and y values by a constant scalar.

A: (I think the spiral image is more confusing than helpful...)
for a point (x, y), you want to get back the angle theta in degrees, where (1,0) is at 0 degrees and (0, 1) is at 90 degrees.
So we want to find theta. Using trigonometry, we know that x is the adjacent side and y is the opposite side, and tan(theta) == y/x.
This is slightly confused by the fact that tan() repeats every 180 degrees - tan(y/x) == tan(-y/-x). Luckily, Python has a built-in function, atan2, that compensates for that. It returns theta in radians, and we convert that to degrees, like so:
from math import atan2, degrees

x, y = (2, 2)
theta = degrees(atan2(y, x))   # => theta == 45.0

however atan2 returns values in -2*pi < theta <= 2*pi (-179.9... to +180 degrees); you want it in (0.. 359.9...) degrees:
theta = (degrees(atan2(y, x)) + 360.0) % 360.0

A: You want a vector field where one of the trajectories is the Archimedean spiral.
If you take the spiral formula

x = θ cos θ, y = θ sin θ

from the answer of legends2k and compute its tangent, you get

vx = cos θ - θ sin θ, vy = sin θ + θ cos θ

Elimination of θ for x and y in the most straightforward way gives the general vector field

vx = x/r-y, vy = y/r + x, where r=sqrt(x^2+y^2).

The angle of the vector field is then obtained as atan2(vy,vx).

A: If someone could verify this I'd appreciate it.
This solution allows you to have a radius which grows at a different rate then the angle
radius:
r(t) = r_scalar * t
d(r(t))/dt = r_scaler

degrees:
a(t) = a0 + a_scalar * t
d(a(t))/dt = a_scaler

location:
x(t),y(t) = x0 + r(t)*cos(a(t)), y0 + r(t)*sin(a(t))

Now we can compute the direction of any t as:
d(x(t))/dt = r(t)*(-sin(a(t))*d(a(t))/dt) + d(r(t))/dt*cos(a(t))
d(y(t))/dt = r(t)*(cos(a(t))*d(a(t))/dt) + d(r(t))/dt*cos(a(t))

which simplifies:
d(x(t))/dt = r(t)*(-sin(a(t))*a_scaler) + r_scaler*cos(a(t))
d(y(t))/dt = r(t)*(cos(a(t))*a_scaler) + r_scaler*sin(a(t))

to get the a value of t for a,b such that it is closest to x(t),y(t). you can first approximate saying the distance x0,y0 to x1,y1 will satisfy r(t).
t0 = sqrt((x0 - x2)^2 + (y0 - y1)^2)/r_scalar

seeing that the closest point in the spiral will be at the same degree, adjust t minimally such that the angle is satisfied.. ie
t1 = t0-t2 where atan((y0 - y1)/(x0 - x2)) = (a0 + a_scalar * t0) % 2*pi - (a0 + a_scalar * t2)

thus
t2 = (((a0 + a_scalar * t0) % 2*pi) - atan((y0 - y1)/(x0 - x2)) + a0)/a_scalar

then the closest direction angle is atan((d(x(t0-t2))/dt / d(y(t0-t2))/dt))

A: import numpy as np
import matplotlib.pyplot as plt
import math

def fermat_spiral(dot):
    data=[]
    d=dot*0.1
    for i in range(dot):
        t = i / d * np.pi
        x = (1 +  t) * math.cos(t)
        y = (1 +  t) * math.sin(t)
        data.append([x,y])
    narr = np.array(data)
    f_s = np.concatenate((narr,-narr))
    return f_s

f_spiral = fermat_spiral(20000)
plt.scatter(f_spiral[len(f_spiral)//2:,0],f_spiral[len(f_spiral)//2:,1])
plt.scatter(f_spiral[:len(f_spiral)//2,0],f_spiral[:len(f_spiral)//2,1])
plt.show()


Q: How to tell when AxWindowsMediaPlayer is downloading? I am using AxWindowsMediaPlayer on VB.NET to preview MP3 files from the web so that the user can choose to download it if he likes it. It works. I just put a link in the URL property and after a while it begins playing.
... after a while, of course. Because it has to download the file first. Perhaps I realized that because of my slow connection XD.
But that made me think: how can I tell if the player is currently downloading a file? So that I can put a label saying "Please wait, preparing file..." or something.

A: Look at using the Buffering Event and the BufferingProgress Property. According to the MSDN Link:

Use this event to determine when buffering or downloading starts or stops. You can use the same event block for both cases and test IWMPNetwork.bufferingProgress and IWMPNetwork.downloadProgress to determine whether Windows Media Player is currently buffering or downloading content.


Q: Android: Issue creating Custom 3 state toggle button I'm trying to create a 3 state toggle button by overriding the Button class.
Although, there is no error in the code, but Eclipse is showing following issue in layout xml.
The following classes could not be instantiated:
- com.example.threewaytoggle.TriToggleButton (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.
Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse

And in the error log, this is coming:
com.example.threewaytoggle.TriToggleButton failed to instantiate.

java.lang.NullPointerException
at android.view.View.mergeDrawableStates(View.java:7506)
at com.example.threewaytoggle.TriToggleButton.onCreateDrawableState(TriToggleButton.java:42)
at android.view.View.getDrawableState(View.java:7410)
at android.view.View.setBackgroundDrawable(View.java:7583)....

Following is the code:
Layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.example.threewaytoggle.TriToggleButton
        android:id="@+id/triToggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TriToggleButton" />
</LinearLayout>

Custom Button Class:
package com.example.threewaytoggle;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

public class TriToggleButton extends Button {

    int _state = 0;
    public TriToggleButton(Context context) {
        super(context);
        _state = 0;
        this.setText("1");
    }

    public TriToggleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        _state = 0;
        this.setText("1");
    }

    public TriToggleButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        _state = 0;
        this.setText("1");
    }

    private final int[] STATE_ONE_SET = { R.attr.state_one };
    private final int[] STATE_TWO_SET = { R.attr.state_two };
    private final int[] STATE_THREE_SET = { R.attr.state_three };

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 3);

        if (_state == 0) {
            mergeDrawableStates(drawableState, STATE_ONE_SET);
        } else if (_state == 1) {
            mergeDrawableStates(drawableState, STATE_TWO_SET);
        } else if (_state == 2) {
            mergeDrawableStates(drawableState, STATE_THREE_SET);
        }

        return drawableState;
    }

    @Override
    public boolean performClick() {
        nextState();
        return super.performClick();
    }

    private void nextState() {
        _state++;
        if (_state > 2) {
            _state = 0;
        }
        setButtonText();
    }

    private void setButtonText() {
        //TODO
    }

    public int getState() {
        return _state;
    }
}

A: Found it....Only static was missing in:
private static final int[] STATE_ONE_SET = { R.attr.state_one };
private static final int[] STATE_TWO_SET = { R.attr.state_two };
private static final int[] STATE_THREE_SET = { R.attr.state_three };

But how come this creates a problem...?


Q: Strange (browser) caching issue in cart We had a third party build our initial website and I am in the process of 'fixing' things that were not done as well as we might have liked. One such issue was the manner they used to handle pages that required a user account.
The third party had just added a sign-in page as an intercessionary step before loading the product form. (there were problems with this approach in that a user could technically bookmark the form and anything after it and return to it in a non-signed in state that would cause errors)
The new method is using an open source 'blacklist' style extension where you can list specific pages that require the user to log in. This particular extension did not re-direct to the desired page so I added code to do that (using the built in setBeforeAuthUrl() and setAfterAuthUrl() session variables).
The problem we have gotten in a few, isolated tests is that some browsers appear to have some kind of cached information on the /checkout/cart/ page that again pops up the login screen when you click 'go to checkout' which will then bring you back to the user dashboard. The process will rinse-wash-repeat until you clear the browser cache or otherwise hard-reload (Ctrl-F5) the /checkout/cart/ page.
What I want to know is if there is anyway to force the user's browser to not cache anything on the /checkout/cart/ page and/or any other way to avoid whatever may be the cause of this particular page causing a login prompt to be displayed when a user is already logged in.
SW


Q: What does it precisely mean for the limit to not exist? I know a question With the exact same title has an answer but it hasn’t areally answered mine so please hear me out.
I know what it means for the limit At a point to “ not exist”; the function doesn’t approach a certain value as x approaches some value. But i have seen this phrase used in 2 different contexts. One where the one-sided limits are different and
the second where function approaches infinity or negative infinity from both sides.
The notation for the second, “infinite limit, is always written out in the regular limit notation by the author, who says that it is “describing the way in which limit does not exist”. What are the differences in these 2 types of non-existences in context of the precise definition of a limit not existing?
Secondly, the author explains how The limit of a quotient cannot be computed by the quotient of the limits when the limit of the denominator is equal to zero and that of the numerator is Positive  and proceeds to say that the “limit does not exist” without mentioning the limit notation used for the “infinite limits”, so I assume that he’s implying that this is the first kind of non existence. Shoudn’t this be the second type, since this is no longer an intermediate form and should clearly approach a very large positive number?
Sorry for not formatting, I post on a tablet and dont know how to format.

A: We say the the limit $\lim_{x\to a}f(x)$ is a real number $l$ when$$(\forall\varepsilon>0)(\exists\delta>0)(\forall x\in D_f):|x-a|<\delta\implies|f(x)-l|<\varepsilon,$$we say that $\lim_{x\to a}f(x)=\infty$ when$$(\forall M\in\Bbb R)(\exists\delta>0)(\forall x\in D_f):|x-a|<\delta\implies f(x)>M,$$and we say that $\lim_{x\to a}f(x)=-\infty$ when$$(\forall M\in\Bbb R)(\exists\delta>0)(\forall x\in D_f):|x-a|<\delta\implies f(x)<M.$$The limits $\lim_{x\to a^+}f(x)$ and $\lim_{x\to a^-}f(x)$ are similar, but then $|x-a|<\delta$ becomes $0<x-a<\delta$ and $-\delta<x-a<0$ respectively. In any case, $\lim_{x\to a}f(x)$ exists if and only if both limits $\lim_{x\to a^+}f(x)$ and $\lim_{x\to a^-}f(x)$ exist.
When someone says that the limit $\lim_{x\to a}f(x)$ exists, that person should let it clear whether he or she is talking about existence in $\Bbb R$ or about existence in $\Bbb R\cup\{\pm\infty\}$. Assuming that the context here is just the existence in $\Bbb R$, how can a limit fail to exist? These are the possibilities:

*

*One of the limits $\lim_{x\to a^\pm}f(x)$ does not exist in $\Bbb R$.

*Both of them exist, but they are distinct.

A: We might summarize by saying that

*

*the limit is said to not exist when there is no real number which is the limit (either because the function does not converge to a single real, or because it is unbounded); e.g. $\sin\frac1x$ or $\frac1x$ or $\frac1{x^2}$ at $0$.

*the infinite limit is said to not exist if the function does not converge to infinity nor minus infinity; e.g. $\frac1x\sin\frac1x$ or $\frac1x$ at $0$.


Q: Cron run my Python script but nothing is happening I want to run a Python script every night at 12:00 am to clean up a csv file which is automatically filled in during the day by another script.
My csv file code_list.csv content looks like this at the end of the day:
87698
63753
19742
89876
62765
79832
# etc.

I use the truncate method to clean the csv file with this script csvclean.py :
import csv

filename = "/root/folder/code_list.csv"
f = open(filename, "w")
f.truncate()
f.close()

and here is my crontab:
SHELL=/bin/bash
0 0 * * * cd /root/folder && /usr/bin/python3 ./csvclean.py

Both files are located in the same folder /root/folder.
I can see in /var/log/syslog that the cron is running at the scheduled time but nothing is happening inside my code_list.csv file. While if I run the script directly using python3 csvclean.py it cleans up the csv file perfectly.
What have I forgotten?
- EDIT -
I used a method found here to retrieve logs.
I edited my crontab like this:
*/1 * * * * cd /root/folder && /usr/bin/python3 ./csvclean.py > /root/folder/csvclean.log 2>&1

and I added this line at the beginning of the csvclean.py script:
print 'starting'

I opened the csvclean.log file after the cron and I saw:
/usr/bin/python3: can't open file './csvclean.py': [Errno 2] No such file or directory

Which made me realize that my Python script file name is cleancsv.py and not csvclean.py.
It was under my eyes...

A: Run this command: sudo /etc/init.d/cron restart
after setting crontab demon has to restart.
Also check sys/log for tracing what is issue while running script.


Q: google maps resize event The problem is start the map hidden, if the toggle buttom start showing the map there isn't any ploblem.
I'm seeing a lot of question with this problem but I can't fix it. This is my code. I call the resize event after toogle the map and doen't work.
$('.map-btn').click(function(){
    $(this).next().toggle(500, function(){
        var gMap = document.getElementById("acf-map");
        google.maps.event.trigger(gMap, 'resize');
    });
})

Related question here Google Maps v3 load partially on top left corner, resize event does not work

A: Form my experience is better recall a (re)initilizeMap() function when you click the tab for show the map.
Due the problem/difficulties related to the correct congfiguration of the map in this case if you, wher click the tab for show the map call the initializzazion of the map. the problem is structurally solved.


Q: Getting a GIT change summary like GitHub I've got a group of developers which make GIT commit and merge mistakes (once in a while).
I would like to monitor for 'large changes' somehow.  I see in GitHub that they have the following line when looking at the details of a specific commit:

Showing 759 changed files with 21,736 additions and 3,237 deletions.

That is an example of a real merge that should have only had 1 file changed and several additions/deletions.
Is there some way or some tool that exists that would send out an alert via email or SMS when a commit breaches a configured threshold?
If not, I was wondering if it was possible to generate that same type of output using the GIT command line.  That way, if no tool exists, I can easily script it and send out an email with my own tools.

Update: 2014-03-20 18:52
Based on nulltoken's suggestion, I've tried the following command:

git diff --shortstat $(git rev-parse HEAD HEAD^)

And got exactly what I needed (for the very last commit anyway).  Oddly enough though, what I just observed is that GitHub (1) provides the following numbers, compared to what my GIT  provides (2):

1 :  759 changed files with 21,736 additions and 3,237 deletions.
2 :  759 files changed, 3237 insertions(+), 21736 deletions(-)

So somebody clearly has a bug!  Either GitHub or my GIT (version 1.7.10.4)... funny!

Update: 2014-03-20 19:05
Correction, I simply inverted my hashes and it fixed it... my mistake!  No bug to report.

A:
if it was possible to generate that same type of output using the GIT command line. That way, if no tool exists, I can easily script it and send out an email with my own tools.

You may be after one of the following options of git diff

*

*git diff --stat <from_commit> <until_commit>

*git diff --shortstat <from_commit> <until_commit>

Those commands, when ran against the LibGit2Sharp project, output the following
$ git diff --stat a4c6c45 14ab41c
 LibGit2Sharp.Tests/StashFixture.cs  |  3 ++-
 LibGit2Sharp/Core/NativeMethods.cs  |  8 +++-----
 LibGit2Sharp/Core/Proxy.cs          | 18 +++++++++---
 LibGit2Sharp/ReferenceCollection.cs |  5 ++++-
 4 files changed, 18 insertions(+), 16 deletions(-)

$ git diff --shortstat a4c6c45 14ab41c
 4 files changed, 18 insertions(+), 16 deletions(-)

You'll note that this is pretty much the same content than from the GitHub page showcasing those changes (Note: Clicking on the "Show Diff Stats" will show the per file counts).


Q: JPQL NEW operator with native query ? Can I use the NEW JPQL operator to map result of query inside DTO ?
I tested this code :
Query query = em.createNativeQuery("SELECT NEW com.sim.dtos.entities.FreeLocation(t1.galaxie, t1.ss, t1.position) FROM ...");

List<FreeLocation> l = query.getResultList();

But I have exception :

[#|2012-12-20T12:9:21.203+0100|WARNING|glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=79;_ThreadName=Thread-2;|StandardWrapperValve[Faces Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw exception
  org.postgresql.util.PSQLException: ERREUR: erreur de syntaxe sur ou près de « . »
    Position : 15

So can I use NEW operator with native query please ?

A: A native query, by definition, is a SQL query. It must contain valid SQL for your specific database.
The query will return a List<Object[]>, and it should be trivial to iterate through the list and create a new instance of FreeLocation for each Object[] array.


Q: R_Extracting data for a particular date form a zoo object Hi I have a zoo time series (interval-1 min) contains rainfall data from multiple rain gauges for a month which looks like
head(precApr)
                    RG.1 RG.2 RG..4 RG.5 RG.6 RG.7 RG.8 RG.9 RG.10 RG.12 RG.13
2008-04-06 00:00:00    0    0     0    0    0    0    0    0     0     0     0
2008-04-06 00:01:00    0    0     0    0    0    0    0    0     0     0     0
2008-04-06 00:02:00    0    0     0    0    0    0    0    0     0     0     0
2008-04-06 00:03:00    0    0     0    0    0    0    0    0     0     0     0
2008-04-06 00:04:00    0    0     0    0    0    0    0    0     0     0     0
2008-04-06 00:05:00    0    0     0    0    0    0    0    0     0     0     0
                    RG.14 RG.15 RG.16 RG.17 RG.18
2008-04-06 00:00:00     0     0     0     0     0
2008-04-06 00:01:00     0     0     0     0     0
2008-04-06 00:02:00     0     0     0     0     0
2008-04-06 00:03:00     0     0     0     0     0
2008-04-06 00:04:00     0     0     0     0     0
2008-04-06 00:05:00     0     0     0     0     0

Now I want to extract the data for a particular date, say 25. I used the following code using xts::.indexDate
precAprxts=as.xts(precApr)
precApr25=precAprxts[.indexDate(25)]

But this just gives the following answer whereas I would expect a time series of that day
  precApr25
  ## RG.1 RG.2 RG..4 RG.5 RG.6 RG.7 RG.8 RG.9 RG.10 RG.12 RG.13 RG.14 RG.15
  ## RG.16 RG.17 RG.18

Does anybody know what's the problem with my code or Is there are any other method to do it? Thanks in advance.

A: If z is a zoo series (as stated in the question) then subscripting and window should both work.  In the second and third examples we have assumed that the index is of POSIXct class:
 z[4, ] # fourth row

 window(z, as.POSIXct("2008-04-06 00:03:00"))

 window(z, as.POSIXct("2008-04-06")) # assumes time is 00:00:00

Added One can also subscript with a time:
 z[as.POSIXct("2008-04-06 00:00:00"), ]

 z[as.POSIXct("2008-04-06 00:00:00")] # same

See ?window.zoo for more info.


Q: Why does decreasing the CMOS supply voltage also decrease the maximum circuit frequency? In CMOS circuit design, we know dynamic power is proportional to \$V_{dd}^2Cf\$, so the best way to reduce dynamic power is to reduce \$V_{dd}\$.
However, according to the textbook,

Keeping the same clock frequency becomes unsustainable as \$V_{dd}\$ is continuously reduced, because the rise and fall times of signals stop meeting the noise margin of the gate.

Source: Page 47, Chapter 2, Section 2.5, Parallel Computer Organization and Design
By Michel Dubois, Murali Annavaram, Per Stenström.
Google books link
I don't understand why rise time and fall time increases as voltage decreases.

A: You can consider the fact that the speed of a CMOS circuit is based on the charging and discharging of capacitive loads (since the gate of of downstream transistors is highly capacitive).
Since \$V_{DD}\$ sets the logic values (HIGH = \$V_{DD}\$, LOW = GND), lowering \$V_{DD}\$ decreases a transistor's ability to sink or source current (consider square law:
\$(V_{GS}-V_t)^2\$ directly affected by \$V_{DD}\$).
With less current being sourced/sunk the capacitive nodes will charge and discharge at a slower rate, overall decreasing circuit speed and rise and fall times.
Further, consider rise and fall times are related to di/dt. Rise and fall time are by definition dv/dt. This, however is a result of the charging and discharging capacitances.
Two standard equations:
\$V = Q/C\$
\$I = dQ/dt\$
yield that
\$dV/dt = I/C\$.
So with less current sinking/sourcing the rate of change of current will also be lower.

A: Decreasing the voltage decreases the maximum frequency that can be used such that the operation of the digital system is as desired.
This is because the equivalent resistance, \$R_{eq}\$, of the CMOS transistor increases as \$V_{dd}\$ decreases. As the equivalent resistance increases the propagation delay of the inverter increases, since the propagation delay is proportional to the equivalent resistance.
The average propagation delay is the average of the high to low propagation time and low to high propagation time. The output rise time and fall time depends on the propagation delay of the transistor.
The equation of propagation delay of the inverter is approximately given by
\$t_p = 0.69*R_{eq}*(C_{in} + C_{ext})\$.
\$C_{in}\$ and \$C_{ext}\$ are the effective internal and effective external capacitances of the gate.
As the propagation delay increases the maximum frequency the circuit can use has to decrease, else it would violate the dynamic discipline of digital circuits. Further reading on dynamic discipline: https://computationstructures.org/notes/sequential_logic/notes.html
Modern computers use Dynamic Voltage and frequency scaling, i.e. the frequency is reduced if the supply voltage is reduced.

I also found additional explanation online:

Fig 5.12 b is the voltage transfer characteristic of a CMOS inverter for the supply voltages of 200 mV, 100 mV, and 50 mV (while keeping the transistor thresholds at the same level). Amazingly enough, we still obtain an inverter characteristic, this while the supply voltage is not even large enough to turn the transistors on! The explanation can be found in the sub-threshold operation of the transistors. The sub-threshold currents are sufficient to switch the gate between low and high levels, and provide enough gain to produce acceptable Voltage Transfer Characteristics.
The very low value of the switching currents ensures a very slow operation but this might be acceptable for some applications (such as watches, for example).
At around 100 mV, we start observing a major deterioration of the gate characteristic. \$V_{OL}\$ and \$V_{OH}\$ are no longer at the supply rails and the transition-region gain approaches 1. The latter turns out to be a fundamental show-stopper. To achieving sufficient gain for use in a digital circuit, it is necessary that the supply must be at least a couple times \$ \psi_{T} =
k.T/q \$ (=25 mV at room temperature), the thermal voltage introduced . It turns out that below this same voltage, thermal noise becomes an issue as well, potentially resulting in unreliable operation.
\$V_{DD_{min}} > 2…4k.T/q\$
The above equation presents a true lower bound on supply scaling. It suggests that the only way to get CMOS inverters to operate below 100 mV is to reduce the ambient temperature, or in other words to cool the circuit.
Source for the above figures and explanation: http://bwrcs.eecs.berkeley.edu/Classes/icdesign/ee141_f01/Notes/chapter5.pdf

A: I am not in chip design, but in electronics and software area, and "the rise and fall times of signals stop meeting the noise margin of the gate.", makes sense to me. See if this is right:

*

*"Noise margin" is the key word there. Noise margin is fixed (almost) amount. At least, it does not narrow as much as supply voltage reduces.

*Input capacitance of the circuit, 'Cin', does not decrease as much as supply voltage reduces.

*The voltage at input node is Vin = Vout x (1 - e^(-t/tow)), tow = Rin x Cin, which is an inverse exponential curve.
Thus, when Vdd (Vout) is near noise-margin, Vin takes time (rise, fall) to reach the threshold of the noise-margin.


Q: Get more than one string as a variable into input separated by space I'm using Python 3.
I need to get three values from a input (separated by a space). The values are a integer, a string and a integer again.
Consider that the string can have more than one word.
If I set two words it does not work, because each word is like a value.
My code into the momment is:
list_a = {}
list_b = []
for i in range(4):
    input_values = input("Press {}, {} and {}".format("id1", "name", "id2"))
    id1, name, id2 = input_values.split()

    list_a["id1"] = id1
    list_a["name"] = name
    list_a["id2"] = id2

    list_b.append(dict(list_a))

print(list_b)

If my input is something like 1 name_ok 0, it works. But if my input is something like 1 pasta ok 0, doesn't works because 3 values are expected, not 4.
How could I do to consider that any character between the two integer values was the variable name?
Sorry about the english xD

A: You don't necessarily know that id2 is the third argument; it's the last argument. You can gather all the intervening arguments into a single tuple using extended iterable unpacking. Once you have the tuple of middle arguments, you can join them back together.
id1, *names, id2 = input_valores.split()

list_a["id1"] = int(id1)
list_a["name"] = " ".join(names)
list_a["id2"] = int(id2)

This is somewhat lossy, as it contracts arbitrary whitespace in the name down to a single space; you get the same result of 1, "foo bar", and 2 from "1 foo bar 2" and "1 foo     bar 2", for instance. If that matters, you can use split twice:
# This is the technique alluded to in  Ignacio Vazquez-Abrams' comment.
id1, rest = input_valores.split(None, 1)
name, id2 = rest.rsplit(None, 1)

rsplit is like split, but starts at the other end. In both cases, the None argument specifies the default splitting behavior (arbitrary whitespace), and the argument 1 limits the result to a single split. As a result, on the first and last space is used for splitting; the intermediate spaces are preserved.

A: You can use slicing.
args = input('Enter ID, name, and second ID').split()
id1 = int(args[0])
id2 = int(args[-1])
name = " ".join(args[1:-1])

A: you could use python's slicing notation for this
input_values = input("Press {}, o {} e o {}".format("id1", "name", "id2"))
listSplit = input_values.split()

id1 = listSplit[0]
name = join(listSplit[1:-1])
id2 = listSplit[-1]

def join(arr):
newStr = ""
for i in arr:
    newStr += i + " "
return newStr[:-1]

where id1 is the first word, name is everything between the first index and the last which has been joined into one string and the third argument which is actually the last word.
Hope that helps.

A: this will work:
split = input_values.split()
id1 = int(split[0])
id2 = int(split[-1])
name = " ".join(split[1:-1])


Q: Xwiki Access Rights (AppWithinMinutes) I apologize if the question has already been asked. I made an application with “AppWithinMinutes” in Xwiki. In this application I get user information (eg name, age, etc.)
My application will be 100-150 users.
Each user will enter information.
I have studied these connections:
https://www.xwiki.org/xwiki/bin/view/Documentation/AdminGuide/Access%20Rights/
https://www.xwiki.org/xwiki/bin/view/Documentation/AdminGuide/Access%20Rights/Permission%20types/
My English is a little bad. :slight_smile:
In my application every user just want to see their own information
For example, the AA user only sees the information he enters.
I don’t want you to see the information that other users have entered.(for example, CC,DD,EE users…etc)
How do I do this?
Thanks for your help.


Q: How can I tell if CLLocationManager is actively scanning for a beacon? When you set up an iOS device as a beacon (peripheral role), you can query its state by calling CBPeripheralManager.isAdvertising. I can't find the equivalent to query whether a device is scanning for a beacon (central role) on CLLocationManager. Any ideas?
Update:
Given David's answer, I encapsulated the code setting up the CLBeaconRegion with the specific UUID and added a boolean variable which is changed when calling startMonitoringRegion and stopMonitoringRegion on CLLocationManager.

A: I do not believe there is any way this is possible.  Even though CoreLocation's iBeacon APIs use Bluetooth LE and CoreBluetooth under the hood, Apple appears to have gone to some lengths to hide this implementation.  There is no obvious way to see whether a Bluetooth LE scan is going on at a specific point in time.
Generally speaking, a Bluetooth LE scan is always going on when an app is ranging for iBeacons in the foreground.  When an app is monitoring for iBeacons (either in the foreground or background) or ranging in the background, indirect evidence suggests that scans for beacons take place every few minutes, with the exact number ranging from 1-15 depending on phone model and state.  I know of no way to programmatically detect the exact times when this starts and stops, although it can be inferred by iBeacon monitoring entry/exit times.  If you look at the graph below, the blue dots show the inferred scan times for one particular test case.  Details of how I inferred this are described in this blog post.


Q: R - Mediated moderation in lavaan I'm trying to set up a mediated moderation model using lavaan but am unsure how to code it. I want to replicate Hayes process model number 7, but with two independent variables and an interaction between them. The independent variables are dummy coded, so I don't think I can just multiply them together to get the interaction term. But the moderator, mediator, and outcome variables are continuous.
Here's what my data looks like:
df <- data.frame( iv1 = c(rep(0, 50), rep(1, 50)),
                  iv2 = c(rep(c(0,1), 50)),
                  moderator = rnorm(mean = 5.19, n = 100, sd = 1.22),
                  mediator = rnorm(mean = 4.02, n = 100, sd = 1.90)
                  dv = rnorm(mean = 3.27, n = 100, sd = 1.35))

Thanks!

A: Actually, yes, you can just multiply the binary predictors together. The 0 and 1 are logical parameters, and multiplying in this case preserves the logical relation. You will create a new 0-1 variable which will correctly represent the interaction. Sometimes it really is that easy.