text:
Q: How does PHPMailer use oauth? When sending mail in smtp format, it is known that the header and body suitable for smtp are made and sent to the smtp server.
However, there is a source that is sent using oauth, so I checked it.
PHPmailer's gmail_xoauth.php file does that.
What is the difference between using oauth here and using general smtp?
It seems to be a different method than sending using the API provided by Gmail.
Is it possible to send mail with oauth authentication using mail, the default built-in function in php? If this is possible, I would also like to check out the sources that can be referenced.

A: Yes, you can use OAuth with SMTP via an extension to SMTP's AUTH command called XOAUTH2. A server that supports it will list it amongst its capabilities in response to an EHLO command:
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2

You can see Google's docs on this subject (it can also be used with POP3 and IMAP). Similarly for Microsoft services.
Actually sending the AUTH command is very easy. There is a preset structure to the auth token:
base64("user=" {User} "^Aauth=Bearer " {Access Token} "^A^A")

that results in SMTP output like this:
AUTH XOAUTH2 dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB5YTI5LnZGOWRmdDRxbVRjMk52YjNSbGNrQmhkSFJoZG1semRHRXVZMjl0Q2cBAQ==

What's difficult about XOAUTH2 is obtaining that access token. To get hold of it requires that you run an HTTP service (on top of whatever other services you are running) and provide it with the correct ID and secret, which you submit and receive an access token in response, which you then use in your XOAUTH2 request. PHPMailer provides a script that helps you to do this for Google, Microsoft and Yahoo services, and others via the numerous adapters that are available for the PHPLeague's OAuth2 client package.
IMHO, OAuth2's monumentally confusing structure, ambiguity, and complexity creates excessive overhead and many opportunities for error, and it's all ultimately secured by a username and password, all of which undermines the security of the whole exercise. What doesn't help is that there is no standardisation, and the procedures you must follow to obtain tokens can be completely different across providers (hence the need for different adapters), and is subject to frequent change, making it hard to document. However, since Google imposes it on everyone, you have no choice but to go along with it.


text:
Q: How to adjust the QFileDialog's size in pyQt? Here is part of my code about show the QFileDialog.
expand='Image Files(*.mp3 *.wav)'
tips=u'choose the music file'
path = QtGui.QFileDialog.getOpenFileName(self, tips, QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MusicLocation), expand)

Then it can show the window to choose file.
But its size is too big for me.
I want to set up the size is 320*240.
However I don't know how to do.
Hope there is anyone can solve this problem.

A: I think the only option is not to use the convenience function getOpenFileName.
You will need to create the Dialog by yourself and connect its signal.
Something like this:
def fileSelected(self, filename):
    print(filename)

def showDialog(self):
    filedialog = QtGui.QFileDialog()
    filedialog.fileSelected.connect(self.fileSelected)
    filedialog.setFixedSize(320,240)
    filedialog.show()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot Add WSDL Web Reference to .NET Project in Visual Studio 2012 I'm working on trying to update a couple old integration tools I developed to interface with NetSuite to the latest web services endpoint, which is at the following URL:

https://webservices.netsuite.com/wsdl/v2018_1_0/netsuite.wsdl

I do the usual traveling to add the WSDL:

*

*Project

*Add Service Reference

*Advanced

*Add Web Reference

*Enter WSDL URL into "Address"

However, I consistently get the following message:

There was an error downloading 'https://webservices.netsuite.com/wsdl/v2018_1_0/netsuite.wsdl/_vti_bin/ListData.svc/$metadata'.
  The request was aborted: Could not create SSL/TLS secure channel.

I've downloaded the WSDL file from a browser without issue and tried to use wsdl.exe, both with the file and the URL. With the URL I get the same message as above. With the file I get the following:

Error: Unable to import binding 'NetSuiteBinding' from namespace 'urn:platform_2018_1.webservices.netsuite.com'.

*

*Unable to import operation 'login'.

*The element 'urn:messages_2018_1.platform.webservices.netsuite.com:applicationInfo'
  is missing.

Some suggestions I've found included downloading all of the XSD files listed in the WSDL as imports and list them when running wsdl.exe. That leads to a different error:

Error: Unable to import binding 'NetSuiteBinding' from namespace
  'urn:platform_2018_1.webservices.netsuite.com'.

*

*Unable to import operation 'login'.

*The datatype 'urn:types.core_2018_1.platform.webservices.netsuite.com:RecordType'
  is missing.

I thought maybe it was a TLS issue, and that maybe my machine wasn't using the right version, but I've gone through and updated IE and registry settings to force use of TLS 1.2 without positive results. I also thought maybe there was an issue with my machine, so I sent the files and wsdl.exe from my Win 7 Pro machine to a Win 10 Pro machine. Same results there.
I'm pretty much at a loss here because I did not run into these issues the last time I pulled down a NetSuite wsdl, and I've even tried older WSDLs to the same result. I'm pretty lost as to what to do now.

A: What version of .net is your project using?  Tls 1.2 wasn't avalable by default until .net 4.6.1 I believe.

A: Ok, I think I have it figured out. I believe that since NetSuite did a push to enforce use of TLS 1.2, that ended up being the cause. I installed Visual Studio 2017 and made a test console application, and from there tried to pull down the web services. It succeeded. So, I'm left to assume that VS 2012 cannot communicate using TLS 1.2, therefor causing attempts to generate NetSuite web services to fail, while VS 2017 CAN use TLS 1.2, which is why it succeeded. Guess I'm going to need to port all my projects over into VS 2017 and work with that from now on.


text:
Q: Error reprojecting point cloud with liblas 1.8: "latitude or longitude exceeded limits"? I was previously reprojecting a point cloud in .las format using liblas 1.7.0 (with GeoTIFF 1.4.0 GDAL 1.10.1) as follows:
las2las /tmp/input.las --a_srs EPSG:4326 --t_srs EPSG:3857 --scale 0.001 0.001 0.001 --offset -13704940,4639778,0 --output /tmp/new.las

However, after upgrading to liblas 1.8.0 (with GeoTIFF 1.4.1 GDAL 1.11.3) I now get the following error which I believe indicates the scale factor and offset combination are not enough to cover the data range:

ERROR 1: latitude or longitude exceeded limits
  error: Could not project point for ReprojectionTransform::latitude or longitude exceeded limits

I have played about with the offset and scale factor and can get it to work only if I set the scale factors to 0.01 and remove the offset, e.g.:
las2las /tmp/input.las --a_srs EPSG:4326 --t_srs EPSG:3857 --scale 0.01 0.01 0.01 --output /tmp/next.las

Why am I getting this error with the newer version of liblas, and what should my reprojection command be?
For your information, here is the lasinfo for the input point cloud:
  Version:                     1.2
  Source ID:                   0
  Reserved:                    0
  Project ID/GUID:             '00000000-0000-0000-0000-000000000000'
  System ID:                   'libLAS Python API'
  Generating Software:         'libLAS 1.8.0'
  File Creation Day/Year:      149/2018
  Header Byte Size             227
  Data Offset:                 738
  Header Padding:              0
  Number Var. Length Records:  4
  Point Data Format:           2
  Number of Point Records:     20
  Compressed:                  False
  Number of Points by Return:  20 0 0 0 0
  Scale Factor X Y Z:          0.00000010000000 0.00000010000000 0.01000000000000
  Offset X Y Z:                -123.1140000 38.4250000 -100.00
  Min X Y Z:                   -123.1139429 38.4257008 -2.43
  Max X Y Z:                   -123.1130518 38.4263682 18.19
  Spatial Reference:
GEOGCS["WGS 84",
    DATUM["WGS_1984",
        SPHEROID["WGS 84",6378137,298.257223563,
            AUTHORITY["EPSG","7030"]],
        AUTHORITY["EPSG","6326"]],
    PRIMEM["Greenwich",0],
    UNIT["degree",0.0174532925199433],
    AUTHORITY["EPSG","4326"]]


text:
Q: serialize form data and add them to jquery $.post $('#btnsave').click(function() {
    var id = $('.nameact').attr('data-id');
    var img = $('#imguser').attr('src');
    var uname = $('#inpuname').val();
    var pass = $('#inpass').val();
    var canpublic = $('#selcanpublic').val();
    var about = $('#txtabout').val();
    $.post('btn-save.php', {id, img, uname, pass, canpublic, about}, function(data) {
        console.log(data);
    });
});

It works fine but because inpuname, inpass, selcanpublic, txtabout are all elements of a form (forma) I wonder is it possible to serialize that data and add them to $.post data?
Something like this:
$('#btnsave').click(function() {
    var id = $('.nameact').attr('data-id');
    var img = $('#imguser').attr('src');
    $.post('btn-save.php', {id, img, $('#forma').serialize()}, function(data) {
        console.log(data);
    });
});

A: $('form').serialize() generates a querystring with values. So when you serialize your form it will send the values as url parameters.
It would generate as
http://example.com?id=value&img=value&uname=value&pass=value&canpublic=value&about=value

So there is one way you can send
var formData = $('#forma').serialize()+'&id='+idvalue +'&img='+imgValue;

 $.post('btn-save.php', formData, function(data) {
        console.log(data);
    });

or you can serializeArray() to form. It will create key-value pair of form elements.
var formData = $('#myForm').serializeArray();
formData.push({name: 'id', value: idValue});
formData.push({name: 'img', value: imgValue});

A: You can use FormData() object. It stores form values.
EDIT you can use FormData() only with option processData: false,
$('#btnsave').click(function () {
    var formData = new FormData($('#forma'));
    $.ajax({
        url: 'btn-save.php',
        data: formData,
        type: "POST",
        processData: false,
        success: function(data) {
            console.log(data);
        }
    });
});


text:
Q: If i select one radiobutton and select path from dropdown it should show alert that particular path is not allowed I have 3 radio buttons. If I select one radio button and select particular path from drop down which contains x string , it should show alert that please select other path. How can I do this using JavaScript or jQuery?
I have tried index Of function but it is showing alert for whatever drop down I am selecting. It should show alert when I select one radio button and select path which contains raw.

var path = "/c/devops/java/raw";
if (document.getElementById('transaction3').checked) {
  var indexOfFirst = (path.indexOf('/raw') !== -1);
  alert("Renaming of files under Raw folder is not allowed!!!");
}


text:
Q: Bit twiddling: interleave bytes in word with zero bytes using bitwise operators (<<, |, &, etc) Given a long with bytes WXYZ (where each letter is a byte), I would like some fast bit twiddling code that will create two longs with the same bytes as the original, but interleaved with the 0 byte.
For example, given the long with value ABCDEFGH (each letter being one byte), produce the two longs:
0A0B0C0D
0E0F0G0H

Something equivalent to, but faster than:
long result1 = expand((int)(input >>> 32));
long result2 = expand((int)input);

long expand(int inputInt) {
  long input = intputInt;
  return
    (input & 0x000000FF)       |
    (input & 0x0000FF00) <<  8 |
    (input & 0x00FF0000) << 16 |
    (input & 0xFF000000) << 24;
}

A: The following is about 25% faster for me (Java 7, benchmarked using Google Caliper), YMMV may vary according to your compiler of course:
long a = (input | (input << 16));
long result = (a & 0xFF000000FFL) + ((a & 0xFF000000FF00L) <<8);

The idea is to use a bit of extra parallelism vs. the original approach.
The first line is a neat trick that produces garbage in bits 17-32, but you don't care as you are going to mask it out anyway. :-)

A: long expand(int inputInt) {
  long input = intputInt;
  return
    (input & 0x000000FF) <<  8 |
    (input & 0x0000FF00) << 16 |
    (input & 0x00FF0000) << 24 |
    (input & 0xFF000000) << 32;
}

A: In C++ you could try to use a union:
typedef union
{
    char bytes[8];
    long value;
} PlatformSpecificSolution;

long expand(int valueInt)
{
    PlatformSpecificSolution pss;
    pss.value = valueInt;
    pss.bytes[6] = pss.bytes[3]; pss.bytes[3] = 0;
    pss.bytes[4] = pss.bytes[2]; pss.bytes[2] = 0;
    pss.bytes[2] = pss.bytes[1]; pss.bytes[1] = 0;
    // pss.bytes[0] = pss.bytes[0];
    return pss.value;
 }

I have no idea if this is faster (you will have to run benchmarks on the platforms that you want to support). This solution is definitely more error prone. You should always ask yourself, if the performance benefit outways the disadvantage of less maintainable code.


text:
Q: How do I test a Node.JS Script that is not a module and runs as soon as it's called? I like to use Javascript as a replacement for bash scripts.
Assuming a contrived script called start.js that is run using node start.js:
const shelljs = require("shelljs")

if (!shelljs.which("serve")) {
  shelljs.echo("'serve' is missing, please run 'npm ci'")
  process.exit(1)
}

shelljs.exec("serve -s build -l 3000")

How do I test that:

*

*If serve isn't available then serve -s build -l 3000 is never called and program exits with code 1.

*If serve is available then serve -s build -l 3000 is called.

I don't mind mocking "shelljs", process.exit or anything else.
My main issue is figuring out how to require or import such a functionless and moduleless file in a test suite and get it to run once on each separate test with the mocks present without actually turning this into a CommonJS/ES6 module.

A: Just mock shelljs module, and spy process.exit function.
describe("start.js", () => {
  let shelljs
  let exitSpy

  beforeEach(() => {
    jest.mock("shelljs", () => {
      return {
        exec: jest.fn(),
        which: jest.fn(),
        echo: jest.fn(),
      }
    })
    shelljs = require("shelljs")
    exitSpy = jest.spyOn(process, "exit").mockImplementation(() => {})
  });

  afterEach(() => {
    jest.resetModules()
    jest.resetAllMocks()
  })

  it("should execute process.exit with code is 1 when 'serve' is not existed", () => {
    shelljs.which.mockReturnValue(false)

    require("./start")

    expect(shelljs.which).toHaveBeenCalledWith("serve");
    expect(shelljs.echo).toHaveBeenCalledWith("'serve' is missing, please run 'npm ci'")
    expect(exitSpy).toHaveBeenCalledWith(1)
    // expect(shelljs.exec).toHaveBeenCalled() // can not check like that, exitSpy will not "break" your code, it will be work well if you use if/else syntax
  });

  it("should execute serve when 'serve' is existed", () => {
    shelljs.which.mockReturnValue(true)

    require("./start")

    expect(shelljs.which).toHaveBeenCalledWith("serve");
    expect(shelljs.echo).not.toHaveBeenCalled()
    expect(exitSpy).not.toHaveBeenCalled()
    expect(shelljs.exec).toHaveBeenCalledWith("serve -s build -l 3000")
  });
})

Another way to make sure the production code with be break when process.exit is called. Mock exit function throw an Error, then expect shelljs.exec will not be called
describe("start.js", () => {
  let shelljs
  let exitSpy

  beforeEach(() => {
    jest.mock("shelljs", () => {
      return {
        exec: jest.fn(),
        which: jest.fn(),
        echo: jest.fn(),
      }
    })
    shelljs = require("shelljs")

    exitSpy = jest.spyOn(process, "exit").mockImplementation(() => {
      throw new Error("Mock");
    })
  });

  afterEach(() => {
    jest.resetModules()
    jest.resetAllMocks()
  })

  it("should execute process.exit with code is 1 when 'serve' is not existed", () => {
    shelljs.which.mockReturnValue(false)

    expect.assertions(5)
    try {
      require("./start")
    } catch (error) {
      expect(error.message).toEqual("Mock")
    }

    expect(shelljs.which).toHaveBeenCalledWith("serve");
    expect(shelljs.echo).toHaveBeenCalledWith("'serve' is missing, please run 'npm ci'")
    expect(exitSpy).toHaveBeenCalledWith(1)
    expect(shelljs.exec).not.toHaveBeenCalled()
  });

  it("should execute serve when 'serve' is existed", () => {
    shelljs.which.mockReturnValue(true)

    require("./start")

    expect(shelljs.which).toHaveBeenCalledWith("serve");
    expect(shelljs.echo).not.toHaveBeenCalled()
    expect(exitSpy).not.toHaveBeenCalled()
    expect(shelljs.exec).toHaveBeenCalledWith("serve -s build -l 3000")
  });
})


text:
Q: prolog how to remove an element from a list? I know of the subtract predicate which removes which removes a list of items from a list
subtract([a,b,c,a,b], [a,c], X).

but is there anything like
remove([a,b,c,a,b], a, X).

I know I can modify the above in
subtract([a,b,c,a,b], [a], X).

To achieve the desired result.
But I want to know if there is another way?
EDIT:
@user27815
you did provide a very detailed answer but i'm still very much new to prolog.
And perhaps I didn't ask the question correctly(My bad).
If there is another way to achieve this.Is it Pre-defined or do I have to define it myself.
And can I have an example?

A: Of course, there are many ways.
A good way to do this is to use library reif.
See the answer to this question by repeat:
Delete vowels in a list
There are some general use predicates which are defined that you can adapt to your program.
remove(List,Element,NewList):-
     tinclude(not(list_memberd_truth([Element])),List,NewList).


text:
Q: Backbone change trigger is never called I'm trying some backbone.js examples and can't get change triggers to work. The "Welcome to this world" alert shows up as expected, but "Changed my name to" is never shown. Debugging the code with firefox reveils the same result, a breakpoint on the second alert is never hit.
Any ideas what's wrong?
This is my code:
main.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>hello-backbonejs</title>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

    <script src="model.js" type="text/javascript"></script>

</body>
</html>

model.js
Person = Backbone.Model.extend({
    defaults: {
        name: 'Fetus',
        age: 0
    },
    initialize: function(){
        alert("Welcome to this world");
        this.on("change:name", function(model){
            var name = model.get("name"); // 'Stewie Griffin'
            alert("Changed my name to " + name );
        });
    }
});

var person = new Person({ name: "Thomas", age: 67});
person.set({name: 'Stewie Griffin'}); // This triggers a change and will alert()

A: To get the correct version of the js libraries I had to change main.html into this
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>hello-backbonejs</title>
</head>
<body>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>

    <script src="model.js" type="text/javascript"></script>

</body>
</html>


text:
Q: Cauchy theorem in a general domain Let $f$ be an analytic function in $D$ and continuous on $\partial D$, where $D\subseteq\mathbb{C}$ is an open set, bounded by a Jordan curve.
Is it true that $f\left(z\right)=\frac{1}{2\pi i}\int\limits _{\partial D}\frac{f\left(\xi\right)}{\xi-z}d\xi$?
I know how to prove it for a disk D, using uniform continuity of $\frac{f\left(\xi\right)\cdot\xi}{\xi-z}$, and perhaps if it is half a circle with a straight line connecting the edges, but it seems to fail when $D$ is any open set.
[EDIT 1: Refined the boundary to be bounded by a Jordan curve]
[EDIT 2: Refined terms]

A: An outline of the above comment explicited:
Let $U$ a domain bounded by a rectifiable Jordan curve $J$; then $U$ is simply connected so we can pick $\phi$ a Riemann map from the unit disc $\mathbb D$ to $U$; then Caratheodory theorem says that $\phi$ extends to a continuous (bijective) map from the unit circle $C$ to $J$, call it still $\phi$, and a corollary of the Riesz brothers theorem on analytic measures says that $J$ is rectifiable if and only if $\phi$ is absolutely continuous on $C$ (or equivalently $\phi' \in H^1$) and then $\phi$ gives a change of variables on the boundary hence $$\int_J \frac {f(\zeta)d\zeta}{z-\zeta}=\int_C  \frac {f(\phi(\eta))\phi'(\eta)d\eta}{\phi (w)-\phi(\eta)}, z=\phi(w)$$ and by the usual Cauchy (or residue theorem if you prefer as the integrand has a pole at $w$ with residue $f(\phi(w))$) $$\int_C  \frac {f(\phi(\eta))\phi'(\eta)d\eta}{\phi (w)-\phi(\eta)}=2\pi i f(\phi(w))=2\pi if(z)$$


text:
Q: Haskell rare pattern matching In haskell, I can do:
s@"Hello" = s

The result is:
>s
>"

It begins to print the String but never ends, what is goin on?

A: In lets and top level expressions everything on the left-hand side of the = is in scope on the right-hand side. So you've created a looping "bottom" value.
Notice this behaves the same way:
Prelude> let s = (s::String)
Prelude> s
"

That's because (simplifying) print on String is defined something equivalent to:
printString chars = putChar '"' >> mapM_ putChar chars

Because chars is a loop the mapM_ putChar chars appears to hang.

A: The @"Hello" is irrelevant here, all it does is fix the type to String. You get the same behaviour with
s :: String
s = s

Which is semantically equivalent to
s' :: String
s' = undefined

which gives the result
Prelude> s'
"*** Exception: Prelude.undefined

What I mean by "semantically equivalent" is, both s and s' are examples of bottom values, i.e. values from that "sin bin of error values any type contains, thanks to non-strictness". As soon as you hit a bottom value, the pure Haskell language is basically powerless and has give in to, well, undefined, "impure behaviour", like letting you wait forever or throwing an exception.
However, again thanks to non-strictness, this needs not necessarily happen. When printing a value, the first thing that happens is, the Show instance is invoked and asked to produce a string. A Haskell string is a lazy list. And the show of any string begins with ", therefore even if the string itself is utterly undefined, show will manage to produce that one character.
We can observe this more sheltered with
Prelude> head $ show s
'"'


text:
Q: Qt + XCompositeRender problem I want to render the contents of the window in to QWidget ( or QPixmap ) using XComposite and XRender.
The Issue I'm facing is that I can't get the picture be rendered in the QWidget. The code below has been written using the following tutorial: http://ktown.kde.org/~fredrik/composite_howto.html
The window ID is hardcoded, so there can be any other window ID used. QWidget window which opens does not display the contents of the original window, but just shows the blank gray rectangle. The same thing is if I use the QPixmap, it contains just black rectangle and nothing else.
XRender support is enabled.
What I'm missing here ?
int main( int argc, char *argv[] )
{

    QApplication app( argc, argv );

    Display *dpy = XOpenDisplay( getenv("DISPLAY") );

    Window window = 2097154;

    XCompositeRedirectWindow( dpy, window, CompositeRedirectManual );

    XWindowAttributes attr;

    XGetWindowAttributes( dpy, window, &attr );

    XRenderPictFormat *format = XRenderFindVisualFormat( dpy, attr.visual );
    bool hasAlpha             = ( format->type == PictTypeDirect && format->direct.alphaMask );
    int x                     = attr.x;
    int y                     = attr.y;
    int width                 = attr.width;
    int height                = attr.height;

    qDebug() << hasAlpha << x << y << width << height;

    XRenderPictureAttributes pa;
    pa.subwindow_mode = IncludeInferiors; // Don't clip child widgets

    QWidget widget;
    widget.setGeometry( 100, 100, 500, 500 );
    widget.show();
    Picture picture = XRenderCreatePicture( dpy, window, format, CPSubwindowMode, &pa );

    XRenderComposite( dpy, PictOpSrc, picture, None,
                      widget.x11PictureHandle(), 0, 0, 0, 0, 0, 0, 500, 500 );

    XRenderFreePicture( dpy, picture );

    return app.exec();
}

A: Looks like you need to use
app.setGraphicsSystem("native");

instead of default raster graphic system to have QPixmap buffer be stored.


text:
Q: How to get the TestCategory name from TestContext in vb.net I have a test method with TestCategory attribute as shown below.
<TestMethod()> <TestCategory("myCategory")>
Public Sub TestString()
   Dim a as String="a"
   Dim b as String="b"
   Assert.AreEqual(a,b)
End Sub

can we get the test category name (myCategory) using TestContext in AssemblyInitialize method?
Thanks in advance..


text:
Q: Remove dupe rows from DataTable _CheckPayees = ds.Tables("Payees")

_CheckPayees is a DataTable variable. After it is set with the code above, I would like to go through it and remove duplicate rows from it. These rows have to be exactly dupes though, say two columns have matching values however another one doesn't, that's not considered a dupe.
Is there an easy way to do this?

A: Nevermind....this works.
I hate to answer my own questions but...I figure it I'm stuck on something for a while, and then find it out, and this has no answers yet, I'll post mine because other people may need it to.
Private Function EliminateDuplicates(ByVal dt As DataTable) As DataTable
            Dim ssort As String = ""
            Dim col As DataColumn
            Dim scol As DataColumn
            For Each scol In dt.Columns
                If ssort <> "" Then ssort &= ","
                ssort &= scol.ColumnName
            Next

            dt.DefaultView.Sort = ssort
            Dim i As Integer, bEquals As Boolean, c As Integer, ccount As Integer
            ccount = dt.Columns.Count
            For i = dt.Rows.Count - 1 To 1 Step -1
                bEquals = True
                For c = 0 To ccount - 1
                    If dt.DefaultView(i)(c).ToString() <> dt.DefaultView(i - 1)(c).ToString() Then
                        bEquals = False
                        Exit For
                    End If
                Next c

                If bEquals Then
                    dt.DefaultView(i).Delete()
                End If
            Next

            Return dt

        End Function


text:
Q: How to get the updated contents in a YUI simple editor from your view model I am using ASP.NET MVC3 with the razor view engine.  I am also using a the Yahoo User Interface 2 (YUI2) simple editor.
My view has a view model called ProductEditViewModel.  In this view model I have a property defined as:
public string LongDescription { get; set; }

In my view I would create the YUI2 simple editor from this input field.  The field is defined in the view like:
<td>@Html.TextAreaFor(x => x.LongDescription, new { cols = "75", rows = "10" })<br>
     @Html.ValidationMessageFor(x => x.LongDescription)
</td>

Here is a partial view of my Edit action method:
[Authorize]
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(ProductEditViewModel viewModel)
{
     if (!ModelState.IsValid)
     {
          // Check if valid
     }

     // I added this as a test to see what is returned
     string longDescription = viewModel.LongDescription;

     // Mapping
     Product product = new Product();
     product.InjectFrom(viewModel);

     // Update product in database
     productService.Update(product);

     return RedirectToRoute(Url.AdministrationProductIndex());
}

When I view the contents of the longDescription variable then it should contain the values from the editor.  If I edit the contents in the editor then longDescription still only contains the original contents, not the updated contents.  Why is this?

A: I suspect that somewhere in your POST action you have written something like this:
[Authorize]
[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(ProductEditViewModel viewModel)
{
     ...
     viewModel.LongDescription = "some new contents";
     return View(viewModel);
}

If this is the case then you should make sure that you have cleared the value from the ModelState before modifying it because HTML helpers will always first use the value from model state and then from the model.
So everytime you intend to manually modify some property of your view model inside a POST action make sure you remove it from modelstate:
ModelState.Remove("LongDescription");
viewModel.LongDescription = "some new contents";
return View(viewModel);

Now when the view is displayed, HTML helpers that depend on the LongDescription property will pick the new value instead of using the one that was initially submitted by the user.


text:
Q: Comparing files using timestamp in Python I'm trying to compare my files with the timestamp. For example, there is a directory with files, like
a.xls, a.log, a.txtb.xls, b.log, b.txtc.xls, c.log, c.txt
here i have to find whether the timestamp(datetime) of a.log and a.txt is greater than timestamp of a.xls
I did research about how to get a timestamp of a file, comparing timestamp of two files.
I don't know whether I'm going in a correct direction.Please direct me how to look into this problem and give some logical guidance.

A: I have managed to write a code for the above question.
import os
path = 'D:/Newfolder/A'
xls_file = []
for i in os.listdir(path):
    if i.endswith('xls'):
        file_name = (i.split('.')[0])
        ext_name = (i.split('.')[1])
        xls_file.append(file_name)
for fname in os.listdir(path):
    for i in xls_file:
        if fname.__contains__(i) and not fname.endswith('xls'):
            log_txt = os.path.getmtime(path+'/'+fname)
            xls_tym = os.path.getmtime(path+'/'+i+'.xls')
            if xls_tym < log_txt:
                pass
            else:
                print(i+'.xls')

It may not be the clean code,but i think the code works finePlease suggest if any changes had to be made

A: In Python if you are able to create a datetime object then you can compare them using comparison operators.
So to get a datetime object of your file you can do this:
modTimesinceEpoc = os.path.getmtime(filePath)
 # Convert seconds since epoch to readable timestamp
modificationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modTimesinceEpoc))

Then you can directly use the timestamp and compare them and get your desired output.
Hope this helps.


text:
Q: Sonarqube webhook not valid with Jenkins Localhost Im testing using a Sonarqube Server Community EditionVersion 8.4.1 (build 35646) and Jenkins Server 2.235.5. Both are in the same machine.
Im trying to implement Sonarqube functionalities in my Jenkins Pipeline following some tutorials.
This is the Pipeline Stage/Step where I have defined the Sonarqube implementation:

When I want to define a webhook in Sonarqube, appears me this message:

I already try to update windows host file with another name, but no working :(

A: You can change this behavior in the global configuration: Administration › General Settings > Security, setting "Enable local webhooks validation" to false.


text:
Q: Run another sql query inside foreach loop I have a foreach loop from the first sql query, then inside that foreach loop, i would like to run another sqli query, but i got this error: Call to a member function prepare() on a non-object
Here is my query:
$sqli = "SELECT DISTINCT approveby FROM ads LIMIT 0,20";
$resulti = $conn->prepare($sqli);
$resulti->execute();
foreach ($resulti as $rowi){
$sqlii = "SELECT * FROM ads WHERE approveby=:approveby ORDER BY approvedate ASC";
    $resultii = $conn->prepare($sqlii);
    $resultii->bindParam(':approveby', $rowi['approveby']);
    $resultii->execute();
    $num_rowsii=$resultii->rowCount();
    echo "This person: ". $rowi['approveby']."has approved $num_rowsii advertisements";
}

The reason for above code is:
There are different people who can approve advertisement from table ads. There will be one person who approve many advertisements. So the first query, i would like to list the people who have just approved advertisement.
And the second query, I would like to calculate total number of approvement for each person.
SO please tell me how to fix the error above? And also is there anyway to do this more effectively?
Many thanks

A: You can achieve result in single query, user GROUP BY instead of DISTINCT result and then count result will show total advertisements of each group set, try this query
$sqli = "SELECT *, count(*) AS `total_advertisements` FROM ads
    GROUP BY approveby
    ORDER BY approvedate ASC
    LIMIT 0,20";
$resulti = $conn->prepare($sqli);
$resulti->execute();
foreach ($resulti as $rowi){
  echo "This person: ". $rowi['approveby']."has approved {$rowi['total_advertisements']} advertisements";
}

A: That code is not going to perform well at all.  Instead, combine the two queries like this:
$sql = "SELECT approveby, count(*) FROM ads GROUP BY approveby"
$result = $conn->prepare($sql);
$result->execute();


text:
Q: Creating levels for age in survival analysis I'm running survival analysis in R and would want to predict the survival times for age groups e.g. 20-29; 30-39; 40-49 etc. and BMI 15-18.5; 19-24.9; 25-29.9 etc. I need help on putting age and BMI in group to do the analysis.
Event  Time  Age  Bmi   Gender  Smoke  Stroke
0      80    16   16.5  2       0      2
1      79    19   18.5  1       1      2
0      80    21   20    2       0      2
1      79    23   23    1       1      1
0      80    34   34    2       0      1
1      79    37   35    1       1      1
0      80    43   22    2       0      1
1      79    48   24    1       1      2
0      80    52   41    2       0      2
1      79    54   45    1       1      2

A: I cannot test without the data but that should be the idea:
breaks_age <- seq(from = 0, to = 100, by = 10)
breaks_bmi <- seq(from = 0, to = 100, by = 5)
df$cutpoint_age <- cut(df$age,breaks=breaks_age , right=FALSE)
df$cutpoint_BMI <- cut(df$BMI,breaks=breaks_bmi , right=FALSE)


text:
Q: Django pass selected object from form to another form I got 2 pages. Step 2 and Step 3. What I'm trying to do is pass the selected object from the step 2 form, to the step 3 form so I can filter the objects of the Step 3 forms. You can see the 2 pages/forms in the images below. So when a user selects a university in step 2, then the step 3 must show only the courses of the selected university.
My current code is really simple since I'm deleting and re-writing the code for the past days without results.
views.py
def step2(request):
    universities = University.objects.order_by('name').distinct()
    return render_to_response("registration/step2.html", {'universities': universities},  RequestContext(request))

def step3(request):
    courses = Course.objects.order_by('name')
    return render_to_response("registration/step3.html", {'courses': courses},  RequestContext(request))

A: In your view, you have to retrieve the selection that the user made and use it to filter the choices for the next form. Something like:
form = FirstForm(request.POST)
if form.is_valid():
    uni = form.cleaned_data['uni']
    courses = Course.objects.filter(university__name=uni).order_by('name')
    return render_to_response("registration/step3.html", {'courses': courses},  RequestContext(request))


text:
Q: Activating Form By Title Throws System.NullReferenceException so I have a form with a ComboBox that I populate with a list of open processes (In this case, I limit it to processes with titles that have 13 characters.) When I select an Item in the ComboBox I want to find that Form by Title and BringToFront However when I do so, it throws a System.NullReferenceException.
Here's the code I use to populate the box.
using HWND = IntPtr;
public static class OpenWindowGetter
{
    /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
    /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
    public static IDictionary<HWND, string> GetOpenWindows()
    {
        HWND shellWindow = GetShellWindow();
        Dictionary<HWND, string> windows = new Dictionary<HWND, string>();

        EnumWindows(delegate (HWND hWnd, int lParam)
        {
            if (hWnd == shellWindow) return true;
            if (!IsWindowVisible(hWnd)) return true;

            int length = GetWindowTextLength(hWnd);
            if (length == 0) return true;

            StringBuilder builder = new StringBuilder(length);
            GetWindowText(hWnd, builder, length + 1);

            windows[hWnd] = builder.ToString();
            return true;

        }, 0);

        return windows;
    }

    private delegate bool EnumWindowsProc(HWND hWnd, int lParam);

    [DllImport("USER32.DLL")]
    private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("USER32.DLL")]
    private static extern int GetWindowTextLength(HWND hWnd);

    [DllImport("USER32.DLL")]
    private static extern bool IsWindowVisible(HWND hWnd);

    [DllImport("USER32.DLL")]
    private static extern IntPtr GetShellWindow();
}

public void populateIncidents()
    {
        foreach (KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
        {
            IntPtr handle = window.Key;
            string title = window.Value;
            if (title.Length == 13)
            {
                chooseIncidentBox.Items.Add(title);
            }
        }
    }

And here's the code I'm using to try to show the Form.
private void chooseIncidentBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        sSelectedIncident = chooseIncidentBox.Text;
        Application.OpenForms[sSelectedIncident].BringToFront(); //Exception thrown here.
    }

I'm not quite sure why it's throwing the exception, I know the Form exists as it wouldn't populate the ComboBox otherwise. Any help would be greatly appreciated.

A: The code you have gives all the active windows. Now, Application.OpenForms works only on the forms which are opened in your application. For example, if you have ParentForm and ChildFormin your application and both are open, OpenForms collection will contain these two.
What you are looking for is to bring any process window in front. You can make use of SetForegroundWindow in User32.dll to do so. This SO question looks fairly similar to what you need. Take a look at the accepted solution.


text:
Q: Get user's IP address in TypeScript How do I get the IP address of user's computer in TypeScript?

A: Assuming this JavaScript/TypeScript runs inside the browser:
Neither JavaScript nor TypeScript will allow this directly: for all you know, the user might have gone offline, he's behind a NAT, etc.
Make an AJAX request to your server and have the backend determine the IP.


text:
Q: 555 timer bistable circuit problem: default flip-flop state is 'ON' on power reset The following circuit is a controller for a water pump. It turns the pump on when the reservoir water level drops below the 'L' probe and turns it off when the level reaches the 'H' probe. This circuit works well except a small problem. We have frequent power outages in my area. Every time the power is restored, the water pump starts. Most of the times water level is between the 'L' and the 'H' probes. Theoretically the pump should remain off if the power is restored during the middle levels. Any thoughts what is causing this behavior? How can it be corrected?

Edit:
I simulated this circuit in multisim using the following schematic.

The left two switches simulate the test probes. Down positions of S1 and S2 simulate the lower and upper probe immersed in water, respectively. The oscilloscope output is obtained by switching on-off the power using X-switch. The 555 gets ON after each power restoration. Have implemented the time delay circuit for reset pin IC1-4 as advised by @EM Fields.

A: *

*Disconnect IC1-4 from +12V

*connect one end of a 100k ohm resistor to +12V and the other end to a
100nF capacitor.

*Connect the free end of the 100nF cap to GND.

*Connect IC1-4 to the junction of the resistor and the capacitor.

Like this:

A: Instead of being used as a timer, in this application the 555 (IC1) is being used as a  window comparator, of sorts, and when the voltage on pin 2 falls to less than Vcc/3, IC1-3 will go high and stay high until the voltage on IC1-2 rises above 4 volts and the voltage detected by IC1-6 rises above 2Vcc/3.
In your application, the input required to cause IC1-3 to go high comes from the voltage divider comprising your R2, R4, and the resistance exhibited by the water in the tank.
If we call the water resistance Rw, then the voltage divider will look like this:

and the voltage at E2 will be:
$$ E2 = \frac{E1R2}{Rw+R1+R2}$$
If we wish to rearrange in order to solve for Rw, we can write:
$$Rw =\frac {R2(E1-E2)}{E2}-R1$$
$$ =  \frac{1M\Omega \times 8V}{4V}-10k\Omega$$
$$ = 1.99M\Omega $$
Now, since IC1-2 is connected to ground through 1 megohm, when the water level in the tank falls to the point where contact between the low probe and the water is broken, IC1-2 will be pulled to zero volts through 1 megohm, IC1-3 will go high, and the pump will start.
When the water level then rises to the point where contact is made with the low probe, your voltage divider Rw, R2, R4 will be connected to Vcc and, if the water resistance is less than 1.99 megohms, the voltage on IC1-2 will rise to greater than 4 volts. IC1-3 will remain high, however, and the pump will keep working until the tank fills and the water contacts the high probe.
When that happens, the output of your voltage divider Rw, R1, R3 will cause the voltage on IC1-6 to rise to greater than 8 volts and, since the voltage on IC1-2 is greater than 4 volts, IC1-3 will go low, the pump will stop, and once the tank's water level drops to the point where contact with the low probe is broken, the fill cycle will begin anew. Note that Rw will not be the same for both the low and high probes
As far as your pump problem is concerned, if it's not the lack of a hard reset on power-up after power fail, the only other thing I can think of is that it may be something (some unaccounted-for capacitance, perhaps) in the tank-probe configuration or connection which is causing IC1-2 to stay low during power-up after power fail when the water level is between probes.
In any case, as long as the pump doesn't start up when the tank is full and cause an overflow, it seems like a convenience instead of a problem. :)


text:
Q: Reverse chain rule vs Sum & Difference rules for integrating $\int(x - 1) dx$ I've been studying the basic rules of integration and learnt about the reverse chain rule quite recently. I was doing some practice exercises and there's this concept that I don't get. $\int (x - 1) dx$, using the sum and difference rule would give $\frac {x^2}{2} - x$ however applying the reverse chain to the same example gives $\frac{(x-1)^2}{2}$. Shouldn't the two expressions be equivalent? What am I missing?

A: Since there is only a difference by the integral constant, those two are the same as the result of indefinite integration.

A: You forgot that you get the integral constant.
$\frac{x^2}{2}-x+C=\frac{(x-1)^2}{2} +C$
Where C = -1

A: There are cases where different methods of integration seem to give different answers, but they all differ by a constant. For general antiderivatives, the value of the constant doesn't matter, but for particular antiderivatives, the value of the constant matters.
In your case, it seems as if you are finding the general antiderivative of $(x - 1)$. For this, the value of the constant of integration doesn't matter. One should not say that the first answer is the correct answer, or the second answer is the better answer. Both are valid.


text:
Q: Okta Javascript Auth API fails on Android I'm implementing SSO for my product using Okta Authentication Javascript API. The code is something like this (I use Aurelia as front-end framework):
  login() {
    var OktaAuth = require('@okta/okta-auth-js');
    this.authClient = new OktaAuth({url: 'https://myurl.okta.com'});
    var $this = this;
    $this.authClient.signIn({
        username: this.username,
        password: this.password
      })
      .then(function(transaction) {
        if (transaction.status === 'SUCCESS') {
          $this.authClient.session.setCookieAndRedirect(transaction.sessionToken, 'https://myredirecturl.com');
        } else {
          alert(transaction.status);
          console.error('Error status: ' + transaction.status);
        }
      })
      .fail(function(err) {
        alert(err + ' ' + err.errorSummary + ' ' + err.errorCode);
        console.error(err);
      });
  }

It works perfectly on my desktop with Windows 7, but when I test the same application on my Android mobile device I get AuthApiError with errorSummary and errorCode undefined. Do you know if there are any issues with Okta Auth working on Android (other mobile devices) and what can be done here?

A: That was an issue with CORS. I used a special url to connect to my app via mobile - when I added it to trusted domains in Okta admin dashboard the isseu was resolved.


text:
Q: Mathematical derivation of $N(\lambda)d\lambda$ We all know that in Rayleigh-Jeans law,
$$N(f)df ~=~ 8\pi f^2 df/c^3.$$
How do you derive $N(\lambda)d\lambda$?
I am sort of confused...

A: by wave theory $ \lambda =vT $ and $ f=1/T $ the waves move to the speed of light so
$ f= \frac{c}{\lambda} $ then  $ d\lambda = -\frac{cdf}{f^{2}} $ simply replace in your equation.
i believe he is referring to $ f= \nu = 2\pi \omega $


text:
Q: Using UML to describe voting and commenting process What is the best way to describe a commenting and voting process as we have it here on SO in UML? I need a clear way to describe that one user asks a question, multiple users submit answers and each user can upvote / downvote answers and the question as he likes.
I tried to model that using an activity diagram that starts on top, has to branches, one branch that goes to a node that says "comment", the other one goes in a "voting" action. Each action then has a flow to itself (representing that the user can upvote / downvote and comment as often as he wants) and then both join in a final node.
I do not think that this is in any way comprehensible so I want to ask: what is the correct way to describe this using UML?

A: If you want to describe the rules (i.e. relationships) then a class diagram is probably more appropriate than an activity diagram.  Here's a pretty crude but nevertheless representative example:

Activity diagrams are appropriate for describing chained activities (processes).  In this case however, the behaviour is pretty simple; a User can submit Posts (Question or Answer) and also vote on Posts.
The diagram captures the following rules (reading directly from the relationships):
Each User may submit many Posts
A User need not submit any Posts
Each Post must be submitted by exactly one User
Each User may vote on many Posts
A User need not vote on any Posts
Each Post may be voted on by many Users
A Post need not be voted on by any Users
Each Vote has a type which is either up or down
A Post is either a Question or an Answer
A Question may have many Answers
A Question need not have any Answers
Each Answer must be a response to exactly one Question

Note the model is missing some important rules (e.g. can't up/down vote your own posts).  Also missing Comments (another subtype of Post) and other salient attributes (e.g. User name, Post text, etc.).  Hopefully representative enough for purpose though.
hth.
PS: I took liberties with syntax for Vote.type.  It should really be defined as an enumeration, but for these purposes the way it's shown is sufficient.  Apologies to any lurking UML police :-)


text:
Q: How come whenever I connect a monitor via the mini display port, the WiFi signal drops to below 1Mbps? I have a client machine (System 76 Gazelle) that is running Pop_Os 19.10 with one monitor connected via HDMI. Every time I connect another monitor via mini displayport, the WiFi speed drops from ~150Mbps to under 1Mbps. Why on earth is this happening?
Edit: Some screenshots of pinging google before and after plugging in the third monitor
Before
After


text:
Q: Optimizing Jetpack for Wordpress Yslow reports following issues with Jetpack:
1) Compress http://stats.wordpress.com/e-201219.js using gzip
2) Configure etags for http://stats.wordpress.com/g.gif?...
Modified the format so that it is easier to understand. How can I take action against these items. I am already using latest version of W3 Total cache plugin.
Pls advise.

A: You can't "optimize" Jetpack. Look at the URL; it's served from wordpress.com. You get what they offer from their servers.


text:
Q: Element assignment in matrix function I have to define a function of two variables that yields a high dimensional matrix, with each entry containing a scalar function, that uses its coordinates in the matrix as input. like this:
f[x_,a_] := {{g[1,1][x]*a, g[1,2][x]*a}, {g[2,1][x]*a, g[2,2][x]*a}}

Is there any way I can assign the elements in a smart way without mapping the whole matrix by hand?
EDIT:
I've been asked for an example of g. This is taken out of the original code:
g[n_, m_] := Table[Chop[
    I*Conjugate[h[[n]][[i]]].(hx[[m]][[i]] - h[[m]][[i]])/
      step, 3*10^-3],
   {i, 1, Length[qvals]}];

A: gs = Flatten @ Table[With[{m = m, n = n}, Sin[m #/n^2] &], {m, 2}, {n, 2}];

{Sin[#1/1^2] & , Sin[#1/2^2] & , Sin[(2*#1)/1^2] & , Sin[(2*#1)/2^2] &}

f[x_, a_] = a Through[gs[x]];
f[u, b]

{b*Sin[u], b*Sin[u/4], b*Sin[2*u], b*Sin[u/2]}


text:
Q: Access a function in a separate module using typescript I am migrating a Nodejs project from JavaScript to TypeScript and I keep getting this error from the code that worked earlier in JavaScript. I have some functions defined in a separated module, I want to access this function from a function in another module depending on the arguments passed to the function.
schemas/users.ts
export const signup = () => {}
export const signin = () => {}

schemas/index.ts
import * as UserSchemas from './users';

export { UserSchemas }

validate.ts
import * as schemas from './schemas';

const validate = (schemaCollection: string, schemaName: string) => {
  const schemaFunc = schemas[schemaCollection][schemaName];

  // Use the schemaFunc in the code following this line.
}

If the validate function is passed called like this: validate('UserSchemas', 'signin'), I want to get the signin function back. I get this error when I run the code:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("...schemas/index")'.
No index signature with a parameter of type 'string' was found on type 'typeof import("...schemas/index")'. ts(7053)

A: The error is basically saying that your typing of validate is too lenient, for example validate("Does", "not exist") is valid, but schemas[schemaCollection][schemaName] will throw an error/return undefined.
The correct way to circumvent this is either a union of literals (or enums), or generics:
const validate = <T extends keyof typeof schemas, K extends keyof typeof schemas[T]>(schemaCollection: T, schemaName: K) => {
  const schemaFunc = schemas[schemaCollection][schemaName];

  // Use the schemaFunc in the code following this line.
}

Playground

Although, if this function uses user supplied data in any way, hard code the possible paths or thoroughly validate the input before using this since this is only a compile-time measure and does not protect you from a user entering invalid information and crashing your application.


text:
Q: How to send a buffer in form-data to SignServer? I have a file in memory (in a buffer), it doesn't exist on the file system (so I can't just stream that).
I'm trying to send it to SignServer using HTTP.
Here's how I try to do it:
var formdata = require('form-data'); var form = new formdata();

form.append('workerName', 'PDFSigner');
form.append('data', file_buffer);
// or
// escape(file_buffer.toString('binary'))
// or
// file_buffer.toString('binary') (without escaping)

var request = form.submit('http://localhost:8080/signserver/process', function(err, res) {});

When I try appending file_buffer SignServer says that data is empty:

Status 400 - Missing file content in upload

When I try appending escape(file_buffer.toString('binary')) (as suggested in How do I send a buffer in an HTTP request?) it's the same story.
When I try appending file_buffer.toString('binary') node.js crashes saying:

node: ../src/stream_base.cc:157 int node::StreamBase::Writev(const v8::FunctionCallbackInfo&): Assertion `(offset) <= (storage_size)' failed.
Aborted (core dumped)

How do I correctly send the file (buffer) through HTTP (multipart/form-data) in Node.JS?

A: You explicitly need to set a filename for the data field, otherwise the buffer isn't uploaded as a file:
form.append('data', file_buffer, { filename : 'document.pdf' });

This is documented (albeit not very clearly) here: https://github.com/form-data/form-data#alternative-submission-methods (scroll down to the fourth example).


text:
Q: how to get file size in cakephp I am using info() but it shows the file_size => 0
 $dir = new Folder('./path_to_folder/');
 $files = $dir->find('.*\.pdf');

 foreach($files as $file){
      debug($file); // here is name of file name
      $file = new File($file);
      debug($file->info());
 }

I can also get the size with php.
debug(filesize($dir->path.'\/'.$file));

How to show the file size by cakephp File component?

A: You have to create a File object for each file name returned by $dir->find().
Also note that File::info() only contains file size information from CakePHP 2.1 onwards.
There's an example in the docs:
foreach ($files as $file) {
    $file = new File($dir->pwd() . DS . $file);

    // Now call size() on that file object
    $size = $file->size();

    // Alternatively, use info() if your version of CakePHP is at least 2.1
    $info = $file->info();
}

A: You can call method size() on file object:
http://api.cakephp.org/2.4/class-File.html#_size


text:
Q: Pass message from C to erlang I try to send message from C code to erlang. I use EI Library.
My C code:
int main (int argc, char** argv)
{
  erl_init (NULL, 0);

  extern const char *erl_thisnodename(void);
  extern short erl_thiscreation(void);

  #define SELF(fd) erl_mk_pid(erl_thisnodename(), fd, 0, erl_thiscreation())

  ETERM *arr[2], *emsg;

  int sockfd, creation=1;

  arr[0] = SELF(sockfd);
  arr[1] = erl_mk_atom("ok");
  emsg   = erl_mk_tuple(arr, 2);

  erl_reg_send(sockfd, "my_server", emsg);
  erl_free_term(emsg);

  return (EXIT_SUCCESS);
}

And my erlang code:
start() ->
    Pid = spawn(?MODULE, loop, []),
    register(my_server, Pid).

loop() ->
    receive
        {ok} ->
            io:format("Ok received \n"),
            loop();
        stop ->
            stop;
        _ ->
            io:format("Somethig else \n")
    end.

stop() ->
    my_server ! stop.

But when i run my C application, erlang application nothing received. What's wrong?
I get error:
[Thread debugging using libthread_db enabled]
Program received signal SIGSEGV, Segmentation fault.
0x08055fac in ei_mutex_lock ()
Thank you.

A: At the very least, your C program passes an uninitialized variable (sockfd) to the erl_mk_pid() function, and again later in the call to erl_reg_send().  That's probably a good place to start.


text:
Q: Estrutura/Organização Projeto C# Tenho um projeto que estou desenvolvendo em camadas, até agora tenho as seguintes: Acesso a dados, apresentação, negócios e objetos de transferência. A dúvida é a seguinte:
Exemplo: Tenho um form para cadastrar uma pessoa jurídica no banco de dados. Para salvar os dados que o usuário inseriu no form seria correto neste form que o usuário inseriu os dados eu criar um objeto pessoaJuridica e passar este objeto para uma classe na camada de negócios com o nome de SalvaPessoaJuridica.cs por exemplo, esta por sua vez acessa a camada de acesso a dados e efetua a gravação no banco?
Para cada form eu teria que criar uma classe para manter os dados ou eu já usaria a camada de acesso a dados diretamente no form e já manteria os dados sem criar uma classe específica para cada tipo de operação?
Exemplo:
    private void button1_Click(object sender, EventArgs e)
    {
        if (txtNome.Text == string.Empty || txtIdade.Text == string.Empty || txtEmail.Text == string.Empty)
        {
            MessageBox.Show("Informe os valores para nome, idade e email do aluno.");
            return;
        }
        else
        {
            try
            {
                string sqlInsert = "Insert into Alunos (Nome,Idade,Email) values (@Nome,@Idade,@Email)";
                string[] campos = { "@Nome", "@Idade", "@Email" };
                string[] valores = { txtNome.Text, txtIdade.Text, txtEmail.Text };
                accDB.Salvar(campos, valores, sqlInsert);
                gdvDados.DataSource = accDB.getRegistro(sqlSelect);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro " + ex.Message);
            }
        }
     }

Ou:
private void button1_Click(object sender, EventArgs e)
    {
             try
            {
                Alunos aluno = new Alunos();
                aluno.Nome = "Teste";
                aluno.Idade = 22;
                aluno.Email = "asd@asd.com"

                SalvaAluno salva = new SalvaAluno();
                salva.Manter(aluno);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro " + ex.Message);
            }
        }
     }

A: O seu segundo exemplo é o que chegou mais próximo das melhores práticas, pois ele está aplicando o conceito de separação de responsabilidades.
Esse segundo código é algo bem parecido com que os conceitos MVC ou MVVM fariam por exemplo.
No primeiro exemplo a camada de apresentação está sendo responsável por lógica de inserção no banco dados, como criar a instrução SQL e salvar. A responsabilidade do form é coletar e exibir dados.
Essa sua classe SalvaAluno seria uma espécie de repositório se estivesse usando o Repository Pattern, pois ela apenas adiciona entidades do tipo aluno.
Para seu código atual ficar melhor ainda em vez de utilizar a classe SalvaAluno diretamente, você poderia utilizar uma interface ISalvaAlunopara aplicar conceitos de injeção de dependência e inversão de controle. Dessa forma você não se preocuparia com o tipo de implementação da sua camada DAL, essa implementação poderia ser tanto com Entity Framework, Dapper etc
Para tudo isso citado há muito conteúdo disponível nesse site e na web.
Respondendo sua pergunta:

Para cada form eu teria que criar uma classe para manter os dados ou
  eu já usaria a camada de acesso a dados diretamente no form e já
  manteria os dados sem criar uma classe específica para cada tipo de
  operação?

Você teria que criar uma classe para persistir dados para cada form(ou melhor para cada entidade) para que haja separação de responsabilidades.


text:
Q: how to compile a modified videoInput.h I need to use the modified videoInput library which has the func
deviceSetupWithSubtype()
(It's not the original videoInput library)
I got the .h and .cpp in the rar at the end of this page:
http://opencv.willowgarage.com/wiki/CameraCapture
I tried to compile it with VC2010 Express C++, and I got my .lib, but when I put it in the program in which I want to use the modified videoInput.h, I get a lot of LNK errors such as:
videoInput.lib(videoInput.obj) :error LNK2001:  unresolved external symbol __imp__CoTaskMemFree@4

videoInput.lib(videoInput.obj) :error LNK2001:  unresolved external symbol _MEDIASUBTYPE_RGB24

videoInput.lib(videoInput.obj) :error LNK2001:  unresolved external symbol _MEDIASUBTYPE_AYUV

videoInput.lib(videoInput.obj) :error LNK2001:  unresolved external symbol _MEDIASUBTYPE_Y211

(I tried also the normal videoInput.lib and it works well, but it's not the version I need).
How can I solve that?
Or if you just have this modified videoInput.lib, could you upload it?
Thank you.
EDIT:
In release mode, I get also this error:
videoInput.lib(videoInput.obj) : error LNK2038: mismatch detected for  '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2'

A: After a lot of searching on the link errors I tried with many libs, at the end I found the solution:
you must add these lines in videoInput.h (eventually adjust the paths in the linker, I didn't need it):
// if gives error LNK2038: mismatch detected for   '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2'
// insert _ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH in the C++ preprocessor option in the project properties
// these are the library needed:
#pragma comment (lib, "oleaut32")
#pragma comment (lib, "ole32")
#pragma comment (lib, "user32")
#pragma comment (lib, "strmbase")

Now the resulting videoInput.lib compiles correctly.


text:
Q: Cargar página PHP en un contenedor tengo un formulario el cual grafica los datos de una consulta en una página nueva, pero quiero que esta gráfica se muestre en un div de un html.
Hice esta función de JS

function grafica(){
  $('#contenedor').load('graf.php')
}

Mi consulta la hace bien puesto que en la nueva pestaña se grafica bien, el problema viene cuando ese PHP lo quiero cargar dentro de otra página, me indica el error "Undefined index: f1"

A: Solo tuve que hacer un script con ajax con unos id que asigné en mis campos

<script>
  $('#Enviar').click(function(){
      var Fechain=document.getElementById('f1').value;
      var Fechafin=document.getElementById('f2').value;

      var ruta="Fein="+Fechain+"&Fefin="+Fechafin;

      $.ajax({
        url: 'graf.php',
        type: 'POST',
        data: ruta,
      })

      .done(function(res){
        $('#respuesta').html(res)
        $('#f1').val('');
        $('#f2').val('');
      })

      .fail(function(){
        console.log("error");
      })
      .always(function(){
        console.log("complete");
      })
  });

</script>


text:
Q: How to send json data and formdata (files) from Angular to an ASP.NET WebAPI Controller action in one shot? Let's say I have an ASP.NET WebAPI Controller that looks like that:
public class StuffController
{
    [HttpGet]
    [Route("api/v1/stuff/{id:int}")]
    [ResponseType(typeof(Model))]
    public async Task<IHttpActionResult> GetAsync(int id)
    {
        // ...
    }

    [HttpPut]
    [Route("api/v1/stuff/{id:int}")]
    [ResponseType(typeof(IHttpActionResult))]
    public async Task<IHttpActionResult> UpdateAsync(int id, Model model)
    {
        // ...
    }

    [HttpPost]
    [Route("api/v1/stuff")]
    [ResponseType(typeof(IHttpActionResult))]
    public async Task<IHttpActionResult> CreateAsync([FromBody] Model model)
    {
        // ...
    }
}

Is there anyway I can send / upload / post from an Angular app (obviously in a service with HttpClient properly injected) a model (which is the json data that would be extracted from the body) and the form data containing files...)?
The problem is... I don't really see how:
const formData = new FormData();

const uploadReq = new HttpRequest('POST', url, formData, {
     reportProgress: true,
     headers: headers
});

It's like whether...:

*

*I add the json data as part of the form data and cannot have it extracted from body as "such" in the Web API Controller action, and I have to keep the key used in the Angular app for json data and then loop over the remaining keys (which are supposedly all files).

*I have to send a different "POST" for each file

A: Send a MIME multipart request (multipart/form-data), each blob is its own FormData entry: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects - on the server-side you can extract different parts from the request in ASP.NET by using the Request.Content.ReadAsMultipartAsync API: https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2
You will need to change your Controller Actions to not use method parameters but to read from Request directly:
public async Task<HttpResponseMessage> PostFormData()
{
    // Check if the request contains multipart/form-data.
    if( !this.Request.Content.IsMimeMultipartContent() )
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    // Temporarily write the request to disk (if you use `MultipartMemoryStreamProvider` your risk crashing your server if a malicious user uploads a 2GB+ sized request)
    String root = this.Server.MapPath("~/App_Data");
    MultipartStreamProvider provider = new MultipartFormDataStreamProvider(root);

    try
    {
        // Read the form data and serialize it to disk for reading immediately afterwards:
        await this.Request.Content.ReadAsMultipartAsync( provider );

        // This illustrates how to get the names each part, but remember these are not necessarily files: they could be form fields, JSON blobs, etc
        foreach( MultipartFileData file in provider.FileData )
        {
            Trace.WriteLine( file.Headers.ContentDisposition.FileName );
            Trace.WriteLine( "Server file path: " + file.LocalFileName );
        }

        return this.Request.CreateResponse( HttpStatusCode.OK );
    }
    catch( System.Exception e )
    {
        return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}


text:
Q: Jupyter Lab not opening on Ubuntu Im using Ubuntu as my OS. I have been able to download and open anaconda-navigator through command line. but I can't open up Jupyter lab or jupyter notebook. it is giving me the following error.
Access to the file was denied
The file at file:///home/basant/.local/share/jupyter/runtime/jpserver-6359-open.html is not readable. It may have been removed, moved or file permissions may be preventing access.

I tried changing permissions but it hasn't helped. uninstalled and re-installed everything. didn't work.

A: I had the same problem after an Ubuntu upgrade. The problem was solved by two steps:

*

*Generate a jupyter config file, from terminal type:
 jupyter notebook --generate-config

*Then open the file, which is saved at /home/username/.jupyter/jupyter_notebook_config.py, append c.NotebookApp.use_redirect_file = False and save. You can now start jupyter.

A: I don't have sufficient reputation to add a comment, which would have been my preference, but found the answer above also resolved a similar issue on Ubuntu 22.04 using jupyter-lab.  I am using Jupyter without Anaconda:
input: jupyter-lab
output: Access to the file was denied
The file at .local/share/jupyter/runtime/jpserver-42340-open.html is not readable.
    It may have been removed, moved, or file permissions may be preventing access.
The file did not exist so changing permissions made no sense.


text:
Q: Sample program turns up files that aren't in Google Drive? I just ran the sample program from Google listing all files in my Drive Folder (not on the computer but on the web service) Sample can be found here.
Weird thing is though, the console output is showing a file that was previously there, but is not there any more. I can't really tell why that is. I made the file as a test in the past, then deleted it as another test. But alas the program show it as still there.

This file named "_meta" does no longer exist in my drive and haven't for more than 24 hours. So what gives?

A: As discussed in comment, read any meta-data information of this file whether the file has been deleted.
Google Drive allows you to access deleted file(s) from drive using its Bin similar to Recycle Bin concept on windows. So, a user may restore a file if needed.
You have discovered that file.Trashed is to be used for any query if you don't want the deleted files in your result.
Please change your condition to file.Trashed == false as it is easy to read compared to file.Trashed != true.


text:
Q: iPhone: Algorithm for fetching required data and images from server only once I have implemented an iPhone App that has FanWall in it where users are allowed to put their comments on FanWall screen and other users can comment on their comment or add new comments. It works fine but very slow as every time FanWall screen loads I get the top 25 comments(I have a load more button to load next 25 comments..) including images, comments and other properties from Server as a Zip file. iPhone App then parses this zip file's plist file to arrange comments and images in Fanwall screen. I do this every time as I need to download any new comments and comments on comment or any changes that have been made to existing plist file! Hope I am clear here! Could anyone please throw their thoughts on optimal fetching strategy please. Thanks.

A: A way to make it faster is to tell the server exactly what you need to download.
Example: please send me the comments added between 2012-01-01 and 2012-01-03.
Pull the rest from a local cache.


text:
Q: Execute multiple tests in the same context managers I have a test setup like this:
def test1():
    with Manager1() as m1, m1.get_m2() as m2:
        do_test1(m1, m2)

def test2():
    with Manager1() as m1, m1.get_m2() as m2:
        do_test2(m1, m2)

which I run with nosetests. Now it turns out that the context managers' __enter__() and __exit__() methods are expensive, so I would like to change to a setup like:
def test():
    with Manager1() as m1, m1.get_m2() as m2:
        do_test1(m1, m2)
        do_test2(m1, m2)

but I would like nose to still report separately for each test. I looked into module level and class level setup() and teardown() methods, but they don't seem to provide the same guarantees for cleanup in the case of exceptions. Is there a clean way to get nose to collaborate with context managers?

A: Have a look at nose test generation. It might work if you change the code to use yield, something like:
from nose.tools import nottest

@nottest
def do_test1(m1, m2):
    m1.write('do_test1 f1')
    m2.write('do_test1 f2')

@nottest
def do_test2(m1, m2):
    m1.write('do_test2 f1')
    m2.write('do_test2 f2')

def test():
    with open('f1.txt', 'wb') as m1, open('f2.txt', 'wb') as m2:
        yield do_test1, m1, m2
        yield do_test2, m1, m2

Running tests gets you:
$ nosetests context.py -v
context.test(<open file 'f1.txt', mode 'wb' at 0x06A5BF40>, <open file 'f2.txt', mode 'wb' at 0x06A5BF98>) ... ok
context.test(<open file 'f1.txt', mode 'wb' at 0x06A5BF40>, <open file 'f2.txt', mode 'wb' at 0x06A5BF98>) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.004s

OK

A: If you are worried about an exception being raised in the setup causing the teardown method not to be called then you could use the ExitStack class in contextlib. The ExitStack can make sure Your manager classes are closed properly if the case of an exception in setup.
from io import StringIO
from contextlib import ExitStack

managers = []
close_managers = None

def setup():
    global close_managers
    with ExitStack() as exit_stack:
        managers[:] = [exit_stack.enter_context(StringIO()) for _ in range(2)]
        # any exception raised before this line will will cause all the __exit__
        # methods of the given context managers to be called. So this should
        # be the last part of setup
        close_managers = exit_stack.pop_all().close

def teardown():
    m1, m2 = managers
    assert m1.getvalue() == 'test1 m1\ntest2 m1\n'
    assert m2.getvalue() == 'test1 m2\ntest2 m2\n'
    close_managers()

def test1():
    m1, m2 = managers
    m1.write('test1 m1\n')
    m2.write('test1 m2\n')

def test2():
    m1, m2 = managers
    m1.write('test2 m1\n')
    m2.write('test2 m2\n')


text:
Q: How to place entities in package for Concrete5 v.8? Question on the version of 8.
How to place entities in package for Doctrine? I have it not mapping to DB(

A: This is taken from a new document I've written on how to do this in V8:
http://documentation.concrete5.org/developers/packages/custom-database-tables-in-packages/including-doctrine-orm-entities-in-your-package-version-8-and-above
Standard Behavior
By default, entities in packages are provided in the following way:

*

*Using the Annotation Driver, which loads database information from annotations provided directly in PHP code.

*If the legacy \Src namespace is enabled in a package, which is the case if the package doesn't use any custom autoloaders, and supports concrete5 prior to version 8, then the entire packages/package_handle/src/ directory is scanned for entities and their annotations.

*If the legacy \Src namespace is not enabled, then the class locations specified by $pkg->getPackageAutoloaderRegistries(), and any files found in packages/your_package/src/Concrete/Entity are scanned for entities.

This behavior can all be found in Concrete\Core\Database\EntityManager\Provider\DefaultPackageProvider, which is the default entity manager provider class used if another one isn't provided.
Annotation Driver Functionality
Much of the documentation found in the earlier Doctrine ORM package documentation is still accurate, with one large change:
If your package contains entity classes that use annotations, and the package requires version 8 or greater, you must include @ORM in your annotations. So instead of this:
<?php

namespace Concrete\Package\Statistics\Src\Entity;
/**
 * @Entity
 * @Table(name="StatisticsUserAgents")
 */
class UserAgent
{

    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Column(type="string")
     */
    protected $value;

    /**
     * @Column(type="string")
     */
    protected $hash;

}

You must import the ORM namespace, and preface all annotations with ORM:
<?php

namespace Concrete\Package\Statistics\Src\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="StatisticsUserAgents")
 */
class UserAgent
{

    /**
     * @ORM\Id @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $value;

    /**
     * @ORM\Column(type="string")
     */
    protected $hash;

}

Why did we do this? Not just to make your life more difficult. Once the @ORM namespace is included, it makes it so that your Doctrine can do much, much more. For example, any packages that run on version 8 will be able to support Doctrine Extensions and more.
Customizable Behavior
It's easy to customize the behavior of the package entity manager. What can you do with a customizable entity manager configuration?

*

*If you have one specific portion of your package that contains entities, and you don't want your entire package's code base scanned for entities, provide a custom package provider that points just to the spots in the filesystem that contain your entity classes.

*Provide additional Doctrine types or extensions

*Provide your entity information in alternate formats, like XML or YAML (instead of annotations in PHP classes.)

To customize the way your package configures the entities it provides, do one of the following

*

*Make your package's controller implement the Concrete\Core\Database\EntityManager\Provider\ProviderAggregateInterface, which will be responsible for implementing the getEntityManagerProvider() method, which returns an object of the Concrete\Core\Database\EntityManager\Provider\ProviderInterface interface,

*Make your package's controller implement the Concrete\Core\Database\EntityManager\Provider\ProviderInterface method, which which returns an array of Concrete\Core\Database\EntityManager\Driver\DriverInterface objects.

In both cases, you'll ultimately be providing at least one Concrete\Core\Database\EntityManager\Driver\DriverInterface object.
Example
Here's a simple example. Let's say you have a package that contains entities in the following locations:

*

*Concrete\Package\YourPackage\Entity (which is automatically loaded by concrete5 from packages/src/your_package/Concrete/Entity)

*PortlandLabs\Testing\Entity, which you have set up as a custom class location using $pkgAutoloaderRegistries:
protected $pkgAutoloaderRegistries = array(
    'src/Testing' => '\PortlandLabs\Testing',
);
Instead of scanning all files found in packages/your_package/src/ (which is the default, standard behavior), you just want to load classes using the standard annotation driver from these two locations. First, modify your package controller so that it implements the ProviderAggregateInterface, and import the interface, as well as the StandardPackageProvider class:
use Concrete\Core\Database\EntityManager\Provider\ProviderAggregateInterface;
use Concrete\Core\Database\EntityManager\Provider\StandardPackageProvider;
class Controller extends Package implements ProviderAggregateInterface

Then, implement the provider class:
public function getEntityManagerProvider()
{
    $provider = new StandardPackageProvider($this->app, $this, [
        'src/Concrete/Entity' => 'Concrete\Package\YourPackage\Entity',
        'src/Testing/Entity' => 'PortlandLabs\Testing\Entity'
    ]);
    return $provider;
}

That's it! The standard package provider is a simple library that most classes that want to use annotated entities but load them from custom locations can use.
Other File Formats
Other classes exist to provide the entity definitions in different formats. Check out Concrete\Core\Database\EntityManager\Provider\YamlProvider and Concrete\Core\Database\EntityManager\Provider\XmlProvider if you want to provide your package entities in YAML or XML formats.


text:
Q: How do I stop my joystick from rotating a 3D graphic? I am trying to use Mathematica to illustrate mixed strategies in Game Theory.  I want my students to be able to use common joysticks as controllers.  What I find, however, is that in addition to doing what I want, moving one of the controls on my gamepad rotates the 3D graphics in such a way as to ruin the presentation.  Basically, all I want the controls to do is change the strategy each player uses. The Graphics3D object should not rotate. Here's a very simplified of the code that illustrates the undesired behavior.
Manipulate[
Column[{x, y,
Show[Graphics3D[{Line[{{x, y, 0}, {x + 1, y + 1, 1}}]},
 Axes -> True, ImageSize -> 400],
     Graphics3D[{Tube[{{x, y, 0}, {x - 1, x - y, 1}}]}]]}],
"X1" -> {{x, 0.71}, 0, 1}, "Z1" -> {{y, 0.5}, 0, 1},
ControllerPath -> "Joystick"]

I also thought it might be useful to show you the following, which is the results from
ControllerState["PLAYSTATION(R)3 Controller", "Mapping"]

(* {"X2" -> "Z Axis", "Y2" -> -"Z Rotation", "JB" -> "Button 11",
 "JB1" -> "Button 11", "JB2" -> "Button 12", "JB3" -> None,
 "TLB" -> "Button 5", "TRB" -> "Button 6", "BLB" -> "Button 7",
 "BRB" -> "Button 8", "X" -> "X Axis", "Y" -> -"Y Axis",
 "Z" -> "Z Axis", "X1" -> "X Axis", "Y1" -> -"Y Axis",
 "Z1" -> "Z Axis", "X2" -> "Z Rotation", "Y2" -> -"Slider",
 "Z2" -> None, "X3" -> "Hatswitch X Axis",
 "Y3" -> -"Hatswitch Y Axis", "Z3" -> None,
 "X4" -> Switch[{"Button 1", "Button 3"},
   {False, False}, 0,
   {True, False}, -1,
   {False, True}, 1,
   {True, True}, 0.00001], "Y4" -> Switch[{"Button 2", "Button 4"},
   {False, False}, 0,
   {True, False}, -1,
   {False, True}, 1,
   {True, True}, 0.00001], "X5" -> Switch[{"Button 7", "Button 5"},
   {False, False}, 0,
   {True, False}, -1,
   {False, True}, 1,
   {True, True}, 0.00001], "Y5" -> Switch[{"Button 8", "Button 6"},
   {False, False}, 0,
   {True, False}, -1,
   {False, True}, 1,
   {True, True}, 0.00001], "X6" -> Switch[{"Button 9", "Button 10"},
   {False, False}, 0,
   {True, False}, -1,
   {False, True}, 1,
   {True, True}, 0.00001], "B1" -> "Button 1", "B2" -> "Button 2",
 "B3" -> "Button 3", "B4" -> "Button 4", "B5" -> "Button 5",
 "B6" -> "Button 6", "B7" -> "Button 7", "B8" -> "Button 8",
 "B9" -> "Button 9", "B10" -> "Button 10", "B11" -> "Button 11",
 "B12" -> "Button 12", "DefaultAbsolute" -> False} *)

Also, for what it's worth, the Sony Playstation gamepad I am using has two main analog controls that appear to move in at least a left right and up down configuration.  Moving the left control left and right appears to correspond to "X1" and moving the right control left and right appears to correspond to "Z1". I'm hoping my problem is not Sony PS3 controller specific but is due to some lack of understanding on my part about how to map the physical controls to Mathematica behavior.

A: This can be achieved by adding the ControllerLinking -> False option to any Graphics3D objects that you do not wish to be affected by the external controller.
For example with
Manipulate[
 Graphics3D[{FaceForm[Hue[x]], Cuboid[]}, ControllerLinking -> False],
 {x, 0, 1}]

my joystick x-axis changes the colour but the cube doesn't rotate.


text:
Q: d3js Star Chart - responsive legend I am working on a d3.js chart - This current model creates a legend segment as a g element. I'd like to ensure the legend stacks below if there is not enough room in the container.
//desktop - ample space

//mobile - not enough space

I've cleaned up the legend part -- you able to clean up the code base and add some more comments here. One of the old features I had - is if there wasn't enough room in the chart the legend stacks underneath - like responsive design - I used to create 2 svg parts but apparently with d3 it should only be 1 svg - http://jsfiddle.net/h066yn5u/13/
see if the chart can be more dynamic with different sizes - I think I had to add a padding of 10 to the radius to give it a little gap between the edges.. maybe though its a case of adding a transform on the svg itself to add that padding
var arcchart = chart.append("g")
    .attr("class", "starchart")
    .attr("transform", "translate("+(r+10)+"," + h / 2 + ")");

var legend = chart.append("g")
    .attr("class", "legend")
    .attr("transform", "translate(" + ((r + 10) * 2) + "," + (h / 4) + ")");

a version where it splits the chart into two svgs
http://jsfiddle.net/h066yn5u/14/

A: There are multiple ways to solve this issue.

*

*Split into 2 svg containers: d3.js is not bound to just one svg container. You can split up the legend and the chart into 2 seperate svg containers and let the HTML handle the flow of the page

*Use foreignObject: If you don't want to do that. You can try to use  tag. Remember, that this is not supported by ie11 (and edge either afaik)

*Calculate everything by hand: calculate the width of your legend (and including text), the width of the chart and get the available width for your whole container. If the whole container width is too small, push the legend below and of course adjust the svg height and width accordingly.


text:
Q: callback also appliying to the first animationend element I want to make something when the first animation finishes > start another animation > and when the second also animationed > alert something
But here, the alert also showing after the first animation finishes? why is this happening?
even when I have said to show the alert when the one animated

<button id="mybtn">
  Animate
</button>

@keyframes test {
      100% {

        height: 0px;
      }
}

#one {
  height: 100px;
  width: 100px;
  background: red;

}

#second {
  height: 70px;
  width: 70px;
  background: blue;

}

#mybtn {
  margin-top: 50px;
}

const overlay = document.getElementById('one');
const second = document.getElementById('second');
const mybtn = document.getElementById('mybtn');

mybtn.addEventListener('click', function(){
        second.style.animation = '4000ms ease forwards test';
     second.addEventListener("animationend", function() {

       one.style.animation = '4000ms ease forwards test';
       one.addEventListener("animationend", function() {
                 alert('hello');
            });
     });
});

here is the full jsfiddle code : - https://jsfiddle.net/hjqxvy89/

A: Evidently parent element receives animationend event on it's children too, so you have two options, either check for the event.target:

const overlay = document.getElementById('overlay');
const second = document.getElementById('second');
const mybtn = document.getElementById('mybtn');

mybtn.addEventListener('click', function(){
        second.style.animation = '4000ms ease forwards test';
     second.addEventListener("animationend", function() {

       overlay.style.animation = '4000ms ease forwards test';
       overlay.addEventListener("animationend", function(e) {
              if (e.target === overlay)
                 alert('hello');
            });
     });
});
@keyframes test {
      100% {

        height: 0px;
      }
}

#overlay {
  height: 100px;
  width: 100px;
  background: red;

}

#second {
  height: 70px;
  width: 70px;
  background: blue;

}

#mybtn {
  margin-top: 50px;
}

<button id="mybtn">
  Animate
</button>

or simply use event.preventPropagation() in the parent event handler:

const overlay = document.getElementById('overlay');
const second = document.getElementById('second');
const mybtn = document.getElementById('mybtn');

mybtn.addEventListener('click', function(){
        second.style.animation = '4000ms ease forwards test';
     second.addEventListener("animationend", function(e) {
            e.stopPropagation();

       overlay.style.animation = '4000ms ease forwards test';
       overlay.addEventListener("animationend", function() {
                 alert('hello');
            });
     });
});
@keyframes test {
      100% {

        height: 0px;
      }
}

#overlay {
  height: 100px;
  width: 100px;
  background: red;

}

#second {
  height: 70px;
  width: 70px;
  background: blue;

}

#mybtn {
  margin-top: 50px;
}

<button id="mybtn">
  Animate
</button>

also:
animationend event also also fires on end of animations of child elements?


text:
Q: NTH-child not working properly On some elements i can use the NTH-child selector, which is an 2nd level element (parent > child)
but in the child ive got a 3rd level element (parent > child > child) which i cant seem to trigger with selectors individually. it only triggers all of them or none.

A: first of all you should use id only once in html.If you want what you have now you should use class not id.
second of all you only have one innerblock in your block div.so instead of innerblock:nth-child(1) you can use innerblock.
section#top .block .innerblock{
    background: #ddd !important;
}

fiddle
UPDATE :
if you want to change .innerblocks seperatly for eatch block.use this css
  section#top .block:nth-child(1) .innerblock{
    background: #ddd !important;
  }

fiddle


text:
Q: Avoiding unnecessary events and infinite loop in "coupled" JSliders? I have a GUI that is issuing commands to a web server based on slider values. Some of these sliders are "coupled" on the web server, so changing one of them may also change another one. The coupling is accomplished by the web server returning a list of the values that were set based on the the issued command.
So I can easily set the appropriate sliders based on this response, but the issue is that doing this causes the ChangeListener to be fired and then a command is issued to the web server again. Ideally, the "coupling" should be well behaved and avoid infinite loops, but that is a potential concern and send all those extra events seems unnecessary.
The two solutions I could think of were:

*

*Temporarily removing the listeners, changing the value, and then putting them back.

*Add a "manual" flag to let the listener know that it should ignore the change.

Neither of those seems like the ideal solution to me, but is one of them "better" than the other? Or is there a third solution that I'm not considering?

A: add an enabled flag to the listeners and disable them before manually setting the value
I wouldn't add and remove listeners as that just triggers more listeners!

A: One author calls this problem fibrillation. This discussion suggests a shared model, in addition to the flag approach suggested by @Pyrolistical.

A: The standard model used in .Net WPF is to fire an event only if value of the property has changed! In your case it is setValue() method.

A: After struggling with this for a while and going into a mess with various booleans, I found that the solution was to simply add a check for hasFocus and respond accordingly.

*

*If a field did NOT have focus, then it would allow an update to itself, but wouldn't trigger updates to any other field.

*If a field DID have focus, then it would trigger changes to other fields.
This way, only the focused field can trigger any change and there is no infinite loop. The code is readable and simple, now, and the logic is easy to follow and update.


text:
Q: What's the difference between malloc and tc_malloc? for a code main.c:
#include <stdio.h>
#include <stdlib.h>
int main()
{
    void* p = malloc(1000);
    free(p);
    return(0);
}

1st compile:  gcc main.c -o a.out
2nd compile:  gcc main.c -ltcmalloc -o a.out
1st use glibc stdlib,2nd use tcmalloc
and I can write main.c like this:
#include <stdio.h>
#include <google/tcmalloc.h>
int main()
{
    void* p = tc_malloc(1000);
    tc_free(p);
    return(0);
}

3rd compile: gcc main.c -ltcmalloc -o a.out
3rd is surely use tcmalloc
Is the 2nd and 3rd compile the same ?
I know tcmalloc support more functions like tc_malloc_size / tc_valloc, I guess use tc_* functions is better option to write main.c, so I have more functions ?
I can't find any man page for functions like tc_valloc / tc_new / tc_newarray / tc_valloc / tc_pvalloc

A: http://sourcecodebrowser.com/google-perftools/1.4/windows_2google_2tcmalloc_8h.html
i find this man page about all tcmalloc functions

A: When tcmalloc is loaded, malloc and free are aliased (see gcc documentation of __attribute alias) to tc_malloc and tc_free.
So your 2nd run and 3rd will be same.
The intention of tc_malloc and tc_free is to be able to use tcmalloc versions of malloc directly regardless of what other allocators are present.


text:
Q: Transfer images from android device to pc using WiFi I want to transfer images and files from Android SD Card to PC Server(FTTP Server) using wifi connection? kindly help me if you can......I will appreciate your time and help

A: here is an example on how to use a wifi connection, from here, you need to use commons ftp to transfer file.
there is an existing question similar to yours.

A: There are some free apps available that can be used for this. One is SwiFTP: https://market.android.com/details?id=org.swiftp&hl=en
Hope this helps! I couldn't determine from the question whether you'd like to code this kind of app yourself or simply use it to transfer the files.