text:
Q: What does the Parameter superb in LAPACKE_dgesvd(..) mean? Putting up questions like this one raises a bad conscience... nevertheless I find it surprisingly difficult to google this one. I am experimenting with
lapack_int LAPACKE_dgesvd(
  int matrix_order, char jobu, char jobvt,
  lapack_int m, lapack_int n, double* a,
  lapack_int lda, double* s, double* u, lapack_int ldu,
  double* vt, lapack_int ldvt, double* superb);

which promises a Singular Value Decomposition. Having already stopped to fear Fortran I found a gold mine of information here: http://www.netlib.no/netlib/lapack/double/dgesvd.f
Actually that link's target explains all parameters but the LAPACKE specific double* superb (well and the order parameter, but in FORTRAN all is COL_MAJOR).
Next, here http://software.intel.com/sites/products/documentation/doclib/mkl_sa/11/mkl_lapack_examples/lapacke_dgesvd_row.c.htm I found a program which seems to hint at 'this is some kind of worker cache'.
However, if that were true what is the reason for LAPACKE_dgesvd_work(..)?
In addition I have a second question: In the example they use min(M,N)-1 as a size for superb. Why?

A: According to http://www.netlib.no/netlib/lapack/double/dgesvd.f , about parameter WORK of the fortran version :
WORK    (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK))
         On exit, if INFO = 0, WORK(1) returns the optimal LWORK; if INFO > 0, WORK(2:MIN(M,N)) contains the unconverged superdiagonal elements of an upper bidiagonal matrix B whose diagonal is in S (not necessarily sorted). B satisfies A = U * B * VT, so it has the same singular values as A, and singular vectors related by U and VT.
There is a chance that superb is the superdiagonal of this upper bidiagonal matrix B which has the same singular values as A. This also explain the length min(n,m)-1
A look at lapack-3.5.0/lapacke/src/lapacke_dgesvd.c downloaded from http://www.netlib.org/lapack/ confirms it.
The source code also shows that the high level function lapacke_dgesvd() calls the middle level interface lapacke_dgesvd_work(). If you use the high level interface, you don't have to care about the optimal size of WORK. It will be computed and WORK will be allocated in lapacke_dgesvd()
I wonder if there is any gain to use the middle level interface instead...Maybe when this function is called many times on little matrices of same sizes...
Bye,
Francis


text:
Q: Gimel function and cofinality. I am supposed to show that under the conditions given below, the next property is true:
Let $\lambda \in Card$, where $Card$ is the class of all infinite cardinals. Then,
If $\kappa>\lambda$ and $\forall\eta<\kappa$ $\eta^{\lambda}<\kappa$ and if cof$(\kappa)\leq\lambda$, then $\kappa^{\lambda}=\kappa^{cof(\kappa)}$
Here $cof(\kappa)$ is the standard notation for cofinality in context of the minimal cardinality of all cofinal subsets of $\kappa$.
One inequality is obvious, i.e. $\kappa^{cof(\kappa)}\leq\kappa^{\lambda}$ because of one of the assumptions above, but I am struggling with the other one.

A: Hint: If $S\subseteq\kappa$ is unbounded, then $\kappa^\lambda\leq\prod_{\alpha\in S}|\alpha+1|^\lambda$.
If you can't figure out why this inequality is true, more details are hidden below.

 A function $f:\lambda\to\kappa$ is determined by its restriction to partial functions $\lambda\to \alpha$ for each $\alpha$ and such a partial function can be thought of as a total function $\lambda\to\alpha+1$ (send the undefined values to $\alpha$).

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP undefined variable For the following code:
line 10: echo "before require: ".$test;
line 11: require( dirname(__FILE__) . 'load.php' );
line 12: echo "after require: ".$test;

The output:
before require:
Notice: Undefined variable: test in /home/test.php on line 12
after require:

If load.php is very simple, there will be no message: "Notice: undefined variable....".  Why and how "load.php" will affect $test variable?

A: If the $test variable is unset inside load.php file.
That will effect your $test variable and you will be shown Notice: Undefined variable.
because variables declared before the include statement will be available inside the included file so any action performed on the variable inside that included file will affect that variable.

A: Your variable is not set, hence the notice message.
If you set a value to the variable $test in load.php, it will have that value.
If you don't, well ... it would stay undefined in your case,  not a good practice.

A: From the documentation:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

A: Shouldn't it be require( dirname(__FILE__) . '/load.php' );? :)
Anyway, it looks like you either unset() variable in load.php, or modify display_errors and/or error_reporting to higher level in load.php.

A:
If you have configured PHP to show all notices, warnings,and
  errors,you will see a notice when you run this script: Notice:
  Undefined variable: testing in /path/to/testtype.php on line 3 Notices
  are turned on by default when you use the php-development.inirather
  than php-production.ini,and can be very helpful when debugging
  scripts.


text:
Q: minimal diagram of a knot and the crossing changes Given any knot diagam, we can deform it into  unknot by switching over arc and under arc of some crossings in the diagram. My question is the following:
Let K be a knot a diagram of a knot, suppose the number of crossings need to exchange in order to obtain an unknot is one, then is it true that the knot diagram K is minimal (i.e K has minimal number of crossings).

A: So, this is definitely not true.  The unknotting number, which you described, is an invariant of the knot.  That means that changing the diagram of the knot you are looking at does not change the value of the invariant.  So, adding crossings by some Reidemeister moves will not increase the unknotting number.  So, if I take any diagram, lets say of the trefoil, and increase the number of crossings by type I moves, it will still have unknotting number one and not be the minimal diagram.

A: Suppose $K$ is non-trivial, and let's use $D(K)$ to distinguish $K$ from a particular diagram representing $K$. Let $u(K)$ be the unknotting number of $K$. If $D(K)$ can be unknotted with one crossing change then, $u(K)\leq 1$. If $u(K)=0$ then by definition $K$ is the unknot and so trivial. We've already ruled out this case. It follows that $u(K)=1$ and so $D(K)$ is a minimal unknotting diagram for the knot $K$.


text:
Q: What's wrong with my update_post_meta function? When I save an acf post, I want to grab an ACF user field called contrib-id for the current user, and save it into a relationship field called contrib-meme. This is giving me a syntax error. What am I missing?
function my_acf_save_post($post_id)
    {

    if ( is_user_logged_in() ) {
        update_post_meta( $post_id, 'contrib-meme', (get_user_meta ( get_current_user_id() ), $key = 'contrib-id', $single = true )) ;
    }
}

add_action('acf/save_post', 'my_acf_save_post');

A: Try this:
function my_acf_save_post($post_id){

            if ( is_user_logged_in() ) {
                update_post_meta( $post_id, 'contrib-meme', get_user_meta( get_current_user_id(), 'contrib-id', true ));

            }
        }

add_action('acf/save_post', 'my_acf_save_post');

Hope this helps


text:
Q: Quarkus: MDC is not exposed in Azure Application Insights how do I get the MDC information to show up in Azure Insights.
Currently I only see it in the trace log.
I am using:

*

*Quarkus 1.13.0.Final

*Application Insights 3.0

I have inserted the Application Insights according to these instructions => Java codeless application monitoring Azure Monitor Application Insights
Source Code
...
import org.slf4j.MDC;

@Provider
@ApplicationScoped
public class DemoRequestFilter implements ContainerRequestFilter {

    private static final String DEMO_TAG = "demoTag";

    @Override
    public void filter(final ContainerRequestContext context) {
        MDC.put(DEMO_TAG, "myDemoTag");

    }

}

application.yaml
log:
    console:
      format: "%d{HH:mm:ss} %-5p [%c{2.}] (%t) requestDemoTag=[%X{demoTag}]  %s%e%n"

Thanks for your help

A: Did you mean that you can only see MDC information in this place? And what's your target?

=============================UPDATE==============================
I'll share my configuration on the project. If we need to add appinsights java agent to our program, we could follow this tutorial.
First, download the jar file mentioned in the tutorial you can save it in your workspace, I stored it in the path:D:/applicationinsights-agent-3.0.2.jar
Then I created a file 'applicationinsights.json' in the same folder as jar file. In the json file, I set the connection string of the azure application insights instance. Creating a new application insights then I can get the connection string in the overview page.
Next, I need to set the jvm args. I used sts as the ide, so Menu bar-> Window-> Preference-> Java-> Installed JREs-> double click the one you used-> Default vm arguments set vaule -Xmx512m -XX:+UseG1GC -javaagent:D:/applicationinsights-agent-3.0.2.jar

Adding the MDC code and starting the program, then I can get the result in the top of my answer.
If you need to deploy your program into azure app service, official doc said agent appinsights hasn't supported app service, but I find another answer which proved to be ok of this feature. That says

Enable application insights for the app service and specify an app
insights instance and Add this application setting;
XDT_MicrosoftApplicationInsights_Java -> 1

Let's see log4j2 configuration in my side.

log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="FATAL">
    <Properties>
        <Property name="pattern">%d{HH:mm:ss} %-5p [%c{2.}] (%t) requestDemoTag=[%X{demoTag}]  %s%e%n</Property>
        <Property name="logPath">logs</Property>
    </Properties>
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="${pattern}"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>


text:
Q: How to enable Image adjustment (to set width and height) in TYPO3 v7? In TYPO3 v7, how can I display the height and width options in Backoffice to resize images uploaded?
I think they should appear in the section Image Adjustment in "Appeareance" tab when I edit an image.
However, I only see the following options:
Appearance options screenshot

Does anyone know if I have to configure something somewhere? Any extension to install that solves this?

A: Try to deinstall EXT:gridelements. Maybe problem is there. As a admin user you don't need special permission to see fields height and width.


text:
Q: mapping of the real line to interval [0,1) What is a mapping (bijection) of the real line (−∞,∞) to the interval [0,1)? I'm trying out logs and exponentials but they don't seem to work?

A: What about the following function:
$$f(x)=\tanh|x|$$


text:
Q: Linear Regression model (using Gradient Descent) does not converge on Boston Housing Dataset I've been trying to find out why my linear regression model performs poorly when compared to sklearn's linear regression model.
My linear regression model (update rules based on gradient descent)
w0 = 0
w1 = 0
alpha = 0.001
N = len(xTrain)
for i in range(1000):
  yPred = w0 + w1*xTrain
  w0 = w0 - (alpha/N)* sum(yPred - yTrain)
  w1 = w1 - (alpha/N)*sum((yPred - yTrain) * xTrain)

Code for plotting the values of x from the training set and the predicted values of y
#Scatter plot between x and y
plot.scatter(xTrain,yTrain, c='black')
plot.plot(xTrain, w0+w1*xTrain, color='r')
plot.xlabel('Number of rooms')
plot.ylabel('Median value in 1000s')
plot.show()

I get the output as shown here https://i.stack.imgur.com/jvOfM.png
On running the same code using sklearn's inbuilt linear regression, I get this
https://i.stack.imgur.com/jvOfM.png
Can anyone help me where my model is going wrong? I have tried changing a number of iterations and learning rates, but there were no significant changes.
Here's the ipython notebook on colab if it helps: https://colab.research.google.com/drive/1c3lWKkv2lJfZAc19LiDW7oTuYuacQ3nd
Any help is highly appreciated

A: You can set a bigger learning rate such an 0.01. And it more times such as 500000 times. Then you will get a similar result.

Or you can initialize the w1 with a bigger number such as 5.


text:
Q: How to Authenticate Google Vision/Cloud Using ENV Variable in Ruby on Rails My app is hosted on Heroku, so I'm trying to figure out how to use the JSON Google Cloud provides (to authenticate) as an environment variable, but so far I can't get authenticated.
I've searched Google and Stack Overflow and the best leads I found were:
Google Vision API authentication on heroku
How to upload a json file with secret keys to Heroku
Both say they were able to get it to work, but they don't provide code that I've been able to get work. Can someone please help me? I know it's probably something stupid.
I'm currently just trying to test the service in my product model leveraging this sample code from Google. Mine looks like this:
def self.google_vision_labels
  # Imports the Google Cloud client library
  require "google/cloud/vision"

  # Your Google Cloud Platform project ID
  project_id = "foo"

  # Instantiates a client
  vision = Google::Cloud::Vision.new project: project_id

  # The name of the image file to annotate
  file_name = "http://images5.fanpop.com/image/photos/27800000/FOOTBALL-god-sport-27863176-2272-1704.jpg"

  # Performs label detection on the image file
  labels = vision.image(file_name).labels

  puts "Labels:"
  labels.each do |label|
    puts label.description
  end
 end

I keep receiving this error,
RuntimeError: Could not load the default credentials. Browse to
https://developers.google.com/accounts/docs/application-default-credentials for more information
Based on what I've read, I tried placing the JSON contents in secrets.yml (I'm using the Figaro gem) and then referring to it in a Google.yml file based on the answer in this SO question.
In application.yml, I put (I overwrote some contents in this post for security):
GOOGLE_APPLICATION_CREDENTIALS: {
  "type": "service_account",
  "project_id": "my_project",
  "private_key_id": "2662293c6fca2f0ba784dca1b900acf51c59ee73",
  "private_key": "-----BEGIN PRIVATE KEY-----\n #keycontents \n-----END PRIVATE KEY-----\n",
  "client_email": "foo-labels@foo.iam.gserviceaccount.com",
  "client_id": "100",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url":
  "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url":
  "https://www.googleapis.com/robot/v1/metadata/x509/get-product-labels%40foo.iam.gserviceaccount.com"
}

and in config/google.yml, I put:
GOOGLE_APPLICATION_CREDENTIALS = ENV["GOOGLE_APPLICATION_CREDENTIALS"]

also, tried:
GOOGLE_APPLICATION_CREDENTIALS: ENV["GOOGLE_APPLICATION_CREDENTIALS"]

I have also tried changing these variable names in both files instead of GOOGLE_APPLICATION_CREDENTIALS with GOOGLE_CLOUD_KEYFILE_JSON and VISION_KEYFILE_JSON based on this Google page.
Can someone please, please help me understand what I'm doing wrong in referencing/creating the environmental variable with the JSON credentials? Thank you!

A: It's really annoying that Google decides to buck defacto credential standards by storing secrets via a file instead of a series of environment variables.
That said, my solution to this problem is to create a single .env variable GOOGLE_API_CREDS.
I paste the raw JSON blob into the .env then remove all newlines. Then in the application code I use JSON.parse(ENV.fetch('GOOGLE_API_CREDS') to convert the JSON blob into a real hash:
The .env file:
  GOOGLE_API_CREDS={"type": "service_account","project_id": "your_app_name", ... }

Then in the application code (Google OCR client as an example):
  Google::Cloud::Vision::ImageAnnotator.new(credentials: JSON.parse(ENV.fetch('GOOGLE_API_CREDS'))

Cheers

A: Building on Dylan's answer, I found that I needed to use an extra line to configure the credentials as follows:
Google::Cloud::Language.configure {|gcl| gcl.credentials = JSON.parse(ENV['GOOGLE_APP_CREDS'])}

because the .new(credentials: ...) method was not working for Google::Cloud::Language
had to look in the (sparse) ruby reference section of Google Cloud Language.
And yeah... storing secrets in a file is quite annoying, indeed.

A: I had the same problem with Google Cloud Speech, using the "Getting Started" doc from Google.
The above answers helped a great deal, coupled with updating my Google Speech Gem to V1 (https://googleapis.dev/ruby/google-cloud-speech-v1/latest/Google/Cloud/Speech/V1/Speech/Client.html)

A: I simply use a StringIO object so that Psych thinks that it's an actual file that I read:
google:
  service: GCS
  project: ''
  bucket: ''
  credentials: <%= StringIO.new(ENV['GOOGLE_CREDENTIALS']) %>


text:
Q: How can I handle simultaneous requests for authenticated API, pause all but first while it fetches new access token? For this question, I'm going to state that I'm using JWT tokens. The complexity and handling of these tokens are working great. There are refresh tokens and access tokens, and for this question, we only need to worry about how and when to send the request for retrieving a new access token.
My application (NextJS) is requesting to retrieve data. The endpoint requires an authentication token. This token, along with its expiry date, is stored in memory (React state, I've built a custom hook (useAuth), and its state is available globally in my app.
When the request gets made, we check the expiry, and if the token is deemed invalid (by the expiration date being in the past), we request a new one before proceeding with our fetch request.
If the endpoint gets tried without a valid token, we get a return value of false.
This procedure works well when there is one fetch request, and the issue I have (and therefore this question) is if I have multiple fetch requests happening almost simultaneously. While it will work, each request wants to retrieve a new access token, and we end up with too many requests for an access token when one would suffice.
Ideally, I would like the first request to retrieve the access token (if needed) and the other fetches to wait until a new access token gets granted before proceeding.
Time for some code examples
For the fetch requests I'm using useSWR (https://swr.vercel.app/). Here is one example.
const auth = useAuth();

// Example of ONE fetch (multiply this and use different endpoints, variable deconstruction etc)

const {
        data: venue,
        error: venueError,
        mutate: venueMutate,
    } = useSWR(auth?.isLoggedIn ? ['/api/venues/getVenue', venueUUID] : null, (url, venueUUID) =>
        auth.fetchWithUUID(url, venueUUID)
    );

You do not need to concern yourself with variables such as auth?.isLoggedIn or VenueUUID; know that this (these) request is (are) happening.
The function - auth.fetchWithUUID() - looks like this;
const fetchWithUUID = async (url, uuid, payload = {}) => {
    if (!ref?.current?.accessToken?.expiry || ref?.current?.accessToken?.expiry < +new Date()) {
        console.log('new call');
        await retrieveAccessToken('/api/getAccessToken', true);

        let apiResponse = await fetch_retry(url, uuid, payload, 3);
        return apiResponse?.res;
    } else {
        let apiResponse = await fetch_retry(url, uuid, payload, 3);
        return apiResponse?.res;
    }
};

ref?.current allows us to access current state (https://www.npmjs.com/package/react-usestateref)
The function - retrieveAccessToken() - looks like this;
const retrieveAccessToken = async (url, override = false) => {
    if (!isLoggedIn || override === true) {
        let apiResponse = await fetch(url, {
            method: 'GET',
        }).then((res) => {
            if (res.status >= 300 && res.status != 401) throw new Error('API Client error');
            return res.json();
        });

        console.log('setting access token');

        setUser(apiResponse?.user);

        return isLoggedInRef.current === true ? true : false;
    }

    return null;
};

and lastly, fetch_retry() is this;
const fetch_retry = async (url, uuid, payload, n) => {
    try {
        let thisRes = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${ref?.current?.accessToken?.token}`,
            },
            body: JSON.stringify({
                UUID: uuid,
                ...payload,
            }),
        }).then((res) => {
            if (res.status >= 300 && res.status != 401) throw new Error('API Client error');
            return res.json();
        });

        if (thisRes === false) {
            if (n === 1) return false;

            return await fetch_retry(url, uuid, payload, n - 1);
        } else {
            return thisRes;
        }
    } catch (err) {
        if (n === 1) throw err;
        return await fetch_retry(url, uuid, payload, n - 1);
    }
};

In this current configuration, I am getting all the results from the fetches as intended. Other endpoints behave the same way; they fetch different data. But they all request access tokens, and they are happening milliseconds apart.
expiry 1632450789126
date now - 1632450800173
new call

expiry 1632450789126
date now 1632450800177
new call

expiry 1632450789126
date now 1632450800180
new call

expiry 1632450789126
date now 1632450800182
new call

So, who can put me on a new path? :) Do I need to create a queuing system?

A: You can use semaphore something like this
const tokenRequest = useRef(false);
function checkTokenRequest() {
    return new Promise(function(resolve, reject) {
        (function waitForTokenRequest() {
            if (!tokenRequest.current) return resolve();
            setTimeout(waitForTokenRequest, 30);
        })();
    });
}

const retrieveAccessToken = async (url, override = false) => {
    if (!isLoggedIn || override === true) {
        if (tokenRequest.current) {
            await checkTokenRequest();
        } else {
            tokenRequest.current = true;

            let apiResponse = await fetch(url, {
                method: 'GET'
            }).then((res) => {
                if (res.status >= 300 && res.status != 401) throw new Error('API Client error');
                return res.json();
            });

            console.log('setting access token');

            setUser(apiResponse?.user);

            tokenRequest.current = false;
        }

        return isLoggedInRef.current === true ? true : false;
    }

    return null;
};

Thus, no more than one token request will be launched at the same time
Minimal example here https://codesandbox.io/s/white-paper-lp7vg
More example of the wait function can be found here


text:
Q: Aligning different parts of a text string to left and right side of div I have added a chat window to my current project which uses razor. The problem I am having is that when a new line occurs its shifting everything to the left... A screenshot of the problem is  the red line shows where the highlighted text should be aligned-right.. The current code that displays this area looks like this:

    Latest received events:

 @For Each item In xList
   If item.Contains("System Message") Then
       @
@@item.Split("-")(0)  - @item.Split("-")(1) : @item.Split("-")(3)
   ElseIf item.Contains("*******@******online.com") Then
       @
@@item.Split("-")(0) (@item.Split("-")(1))  : @item.Split("-")(2)
   ElseIf item.Contains("************") Then
      @
@@item.Split("-")(0) (@item.Split("-")(1))  : @item.Split("-")(2)
   ElseIf item.Contains("************") Then
       @
@@item.Split("-")(0) (@item.Split("-")(1))  : @item.Split("-")(2)
   Else
        @
@@item.Split("-")(0) (@item.Split("-")(1))  : @item.Split("-")(2)
   End If
Next

Any ideas on how to achieve this feat? I have tried using align-left in the third  of every type and that does not work..

A: That markup with the inline styles is pretty hard to deal with, so here is a simple example in plain HTML and CSS that you can learn from:
HTML

        User 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        User 2

Duis aute irure dolor in reprehenderit.

        User 1

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

CSS
strong, p {
    display: block;
    width: 50%;
    float: left;
    margin-bottom: 1em;
}

Demo


text:
Q: Compile templateFile with scope in controller I'm trying to build a function for a type of list, that will take the item in a scope that you clicked on, and render it in a modal (like clicking on an article in a category, and getting the full article in a modal).
The following code is located in a page controller, and not a directive. I would later on like to move this code over to my Modal service, to more easily build modal templates.
I can retrive the template from $templateCache, and render it in the modal:
app.controller('FlowController', function($log, $scope, $compile, $templateCache, Modal) {
  $scope.modal = function(){
    var template = $templateCache.get('/frontend/flow/partials/classifiedModal.html');
    Modal.dialog(template);
  };
});

Now, I want to combine that template with a scope:
app.controller('FlowController', function($log, $scope, $compile, $templateCache, Modal) {
  $scope.modal = function(index){
    var template = $templateCache.get('/frontend/flow/partials/classifiedModal.html');
    var compiled = $compile(template)($scope.classifieds[index]);
    Modal.large(compiled);
  };
});

This keeps giving me an error Undefined is not a function
TypeError: undefined is not a function
    at textInterpolateLinkFn (http://localhost:3001/angular/angular.js:6975:23)
    at nodeLinkFn (http://localhost:3001/angular/angular.js:6711:13)
    at compositeLinkFn (http://localhost:3001/angular/angular.js:6105:13)
    at compositeLinkFn (http://localhost:3001/angular/angular.js:6108:13)
    at publicLinkFn (http://localhost:3001/angular/angular.js:6001:30)
    at Scope.$scope.modal (http://localhost:3001/flow/flow.js:54:47)
    at Parser.functionCall (http://localhost:3001/angular/angular.js:10846:21)
    at ngEventDirectives.(anonymous function).compile.element.on.callback (http://localhost:3001/angular/angular.js:19133:17)
    at Scope.$get.Scope.$eval (http://localhost:3001/angular/angular.js:12701:28)
    at Scope.$get.Scope.$apply (http://localhost:3001/angular/angular.js:12799:23) {{title}}


text:
Q: How to use MassTransit InMemory? I want to register consumer by interface, send message, initialize it by interface from container, then consume:
public sealed class TestConsumer<T> : IConsumer<T>
    where T : class
{
    private readonly Func<ConsumeContext<T>, Task> _onConsume;
    private readonly EventWaitHandle _handle;
    public TestConsumer(Func<ConsumeContext<T>, Task> onConsume)
    {
        _onConsume = onConsume;
        _handle = new EventWaitHandle(false, EventResetMode.ManualReset);
    }

    public async Task Consume(ConsumeContext<T> context)
    {
        try
        {
            await _onConsume(context).ConfigureAwait(false);
        }
        finally
        {
            _handle.Set();
        }
    }

    public async Task GetTask()
    {
        while (!_handle.WaitOne(0))
            await Task.Delay(100);
    }
}

public class MyRequest { }

[TestFixture]
public class ConsumerTests
{
    [Test]
    public async Task Test()
    {
        var services = new ServiceCollection();
        var tc = new TestConsumer<MyRequest>(async (c) => Console.WriteLine("request"));
        services.AddSingleton<IConsumer<MyRequest>>(tc);
        services.AddSingleton<IBusControl>(x => Bus.Factory.CreateUsingInMemory(cfg =>
        {
            cfg.ReceiveEndpoint("foobar", c => { c.Consumer<IConsumer<MyRequest>>(x); });
        }));

        var sp = services.BuildServiceProvider();

        await sp.GetRequiredService<IBusControl>().StartAsync();

        //and how do I send it?
        //this will obviously not work with Uri!!!
        var sendEndpoint = await sp.GetRequiredService<IBusControl>().GetSendEndpoint(new Uri("foobar", UriKind.Relative));
        await sendEndpoint.Send(new MyRequest());

        await tc.GetTask();
        Console.WriteLine("done");
    }
}

Honestly, lack of documentation is driving me crazy. There is such thing as harness, but it works only if you throw your DI container into garbage can or write a ton of adapters.
How do one can use InMemory and combine it to completely uncompatible Uri in Send method?


text:
Q: azure vm creation using puppet module i'm getting the error below when i want to create a vm on azure :
does not have authorization to perform action 'Microsoft.Storage/register/action' over scope
I created an application on the classic portal and followed this tutorial :
https://azure.microsoft.com/en-us/documentation/articles/resource-group-create-service-principal-portal/
after that i created a resource group on the new portal and assigned owner to this application.
I'm using this puppet script to create the vm :
azure_vm { 'sample':
    ensure         => present,
    location       => 'westus',
    image          => 'canonical:ubuntuserver:14.04.2-LTS:latest',
    user           => 'azureuser',
    password       => 'Password',
    size           => 'Standard_A0',
    resource_group => 'puppettest123',
}

when i run it i get this exact error :
Error: {"error"=>{"code"=>"AuthorizationFailed", "message"=>"The client '5b0bc6d-fcad-4223-8527-a2c9afc2661' with object id '5b0bc6d-fcad-4223-8527-a2c9afc2661' does not have authorization to perform action 'Microsoft.Storage/register/action' over scope '/subscriptions/5ad96a9-45de-4fe1-91e8-2514dd5e6a9'."}}
Error: /Stage[main]/Main/Azure_vm[sample]/ensure: change from absent to present failed: {"error"=>{"code"=>"AuthorizationFailed", "message"=>"The client '5b0bc6d-fcad-4223-8527-a2c9afc2661' with object id '5b0bc6d-fcad-4223-8527-a2c9afc2661' does not have authorization to perform action 'Microsoft.Storage/register/action' over scope '/subscriptions/5ad96a9-45de-4fe1-91e8-2514dd5e6a9'."}}

https://forge.puppet.com/puppetlabs/azure
Any ideas on how i can fix this issue ?
I fixed the problem using this command :
azure role assignment create --objectId 7dbc8265-51ed-4038-8e13-31948c7f4ce7 -o Owner -c /subscriptions/{subscriptionId}/

A: azure role assignment create --objectId 7dbc8265-51ed-4038-8e13-31948c7f4ce7 -o Owner -c /subscriptions/{subscriptionId}/


text:
Q: semantic error TS6059: 'rootDir' is expected to contain all source files I have error when i run nx library:build:

semantic error TS6059: File
'/media/user/DATA/Admin/project/libs/smart-ui/customer-info-ui/src/index.ts'
is not under 'rootDir'
'/media/user/DATA/Admin/project/libs/collab/workspace/src'. 'rootDir'
is expected to contain all source files.

When check, library was imported "@project-ui/customer-info-ui" not use path
I'm check library and don't see "package.json" , i create it:
{
    "name": "@project-ui/customer-info-ui",
    "version": "0.0.1"
}

And run build, but it fail


text:
Q: MFMailComposeViewController programmatically call the "Send" button I am trying to send an automatic email with an UIImage as an
attachment when user presses 'Send Photo' button.
Is there any way that we can programmatically call the "Send" button in the MFMailComposeViewController. If not could you please suggest me some other method of doing this.
Any help will be appreciated.
Thanx in advance.

A: Apple might reject your submission for this, but if you really wanna do it, here's how:
-(void)showController {
    MFMailComposeViewController *mailController;
    //alloc, init, set properties, do whatever you normally would
    [self.navigationController presentModalViewController:mailController animated:YES];
    [mailController release];

    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hackMail:) userInfo:mailController repeats:NO];
}

-(void)hackMail:(NSTimer*)theTimer {
    MFMailComposeViewController *mailController = theTimer.userInfo;
    UIBarButtonItem *sendBtn = mailController.navigationBar.topItem.rightBarButtonItem;
    id targ = sendBtn.target;
    [targ performSelector:sendBtn.action withObject:sendBtn];
}

This will show a mail controller, wait 3 seconds, and then send the e-mail. Happy hacking :)


text:
Q: Expected distance/ time for a bouncing ball to stop. I saw someone on YouTube glue half of a bouncy ball to a golf ball. I thought of an interesting expected value problem using it.
Consider when you drop the ball it lands on the bouncy or non bouncy side with equal probability. When it lands on the bouncy side it returns to  $a\%$ of its height before the bounce and if it lands on the golf side it bounces and returns to $b\%$ of its height before the bounce. With $0<b<a<100$
Lets say the ball stops bouncing when it first bounces up less than $m$ centimetres.
For example, let $a = 50$, $b=10$ and $m=1$ you drop the ball from $1$ metre and it lands on the bouncy side so returns to $50$ cm. It then bounces on the golf side so returns to $5$ cm. It then bounces on the bouncy side three times so goes $2.5$, $1.25$, $0.625$ and stops bouncing.
I had a few problems that I am sure are very related.

*

*If you drop the ball from $1$ metre what is the expected number of bounces?

*If you drop the ball from $1$ metre what is the expected distance it travels before it stops bouncing.

I am happy to consider only the second question and allow for infinite bouncing, I feel like the condition on stopping bouncing will make calculations very hard.
Can we relate these two problems nicely?
My ideas:

*

*Let $H$ denote the height of the ball after $n$ bounces. (Starting from $1$ metre)
$H = a^X \cdot b^{n-X}$ Where $X\sim$ Bin($n,\frac{1}{2}$) denotes the number of "bouncy bounces"

*We could probably uses logarithms to find out all different combinations that yield $H< m$ and binomial co-efficents then manually calculate EV

*We could say on average each bounce reduces our ball's height by $\frac{b+a}{2}$ and then think use logs to work out how many bounces it would take reducing at the rate of $\frac{b+a}{2}$ to stop. But I don't think this will give a very accurate answer because of the RV.s in the exponent.

*We can just run some code.
Please no full solutions I want to tackle this myself! Just hints for now


text:
Q: doctrine avoid automatic hydration I'm working with an old version of DoctrineExtension.Tree and I don't have buildTree. So I'd like to do the same but I keep running into a problem:
Everytime I use findHierarchy(see below) and iterate on all my children in the hierarchy it gets everything twice. Because Doctrine still queries to find the children (even though I loaded them in find Hierarchy) Here is some useful code:
The two functions in my entity
/**
 * Add children
 *
 * @param BGCom\MontreuxBundle\Entity\Category $children
 */
public function addChildren(\BGCom\MontreuxBundle\Entity\Category $children)
{
    $children->setParent($this);
    $this->children[] = $children;
}

/**
 * Get children
 *
 * @return Doctrine\Common\Collections\Collection
 */
public function getChildren()
{
    return $this->children;
}

find hierarchy in my repo:
public function findHierarchy() {
    $qb = $this
        ->createQueryBuilder('node')
        ->where('node.lvl < 2')
        ->andWhere('node.in_menu = 1')
        ->orderBy('node.root, node.lvl', 'ASC');

    // set hint to translate nodes
    $query = $qb->getQuery()->setHint(
        Query::HINT_CUSTOM_OUTPUT_WALKER,
        'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
    );
    $res = $query->getResult();
    //Now build the right entity
    // build tree in english
    $i = 0;
    $j = 0;
    // We rebuild the tree
    $parent = array();
    while($i < count($res)) {
        $cur = $res[$i];
        $parent[] = $cur;
        $i++;
        while ($i < count($res) && $res[$i]->getRoot() === $cur->getId()) {
            $cur->addChildren($res[$i]);
            $i++;
        }
    }
    return $parent;
}

my view:
{% for root in trees %}

    {{ root.name }}

       {% for twig in root.getChildren() %}

               {{ twig.name }}

       {% endfor %}

{% endfor %}

So to be clear: Is there a way to avoid doctrine from querying if some children are already present in the Entity?
Thanks a lot for your help

A: Doctrine2 will never instantiate 2 instances of the same database row.
You probably have the same object twice.
You could avoid setting a Category twice in the $children array by doing this:
public function addChildren(\BGCom\MontreuxBundle\Entity\Category $children)
{
    $children->setParent($this);

    if (!$this->children->has($children)) {
        $this->children[] = $children;
    }
}


text:
Q: Regex optional match in python fails tickettypepat = (r'MIS Notes:.*(//p//)?.*')
retype = re.search(tickettypepat,line)
if retype:
  print retype.group(0)
  print retype.group(1)

Given the input.
MIS Notes: //p//

Can anyone tell me why group(0) is
MIS Notes: //p//

and group(1) is returning as None?
I was originally using regex because, before I ran into problems the matching was more complex than just matching //p// here's the full code. I'm fairly new at this so forgive my noobness, I'm sure there are better ways of accomplishing much of this and if anyonee feels like pointing those out that would be awesome. But aside from the problem with the regex for //[pewPEW]// being too greedy it seems to be functional. I appreciate the help.

Takes Text and cleans up / converts some things.
filename = (r'.\4-12_4-26.txt')
import re
import sys
#Clean up output from the web to ensure that you have one catagory per line
f = open(filename)
w = open('cleantext.txt','w')

origdatepat = (r'(Ticket Date: )([0-9]+/[0-9]+/[0-9]+),( [0-9]+:[0-9]+ [PA]M)')
tickettypepat = (r'MIS Notes:.*(//[pewPEW]//)?.*')

print 'Begining Blank Line Removal'
for line in f:
    redate = re.search(origdatepat,line)
    retype = re.search(tickettypepat,line)
    if line == ' \n':
        line = ''
        print 'Removing blank Line'
#remove ',' from time and date line
    elif redate:
        line = redate.group(1) + redate.group(2)+ redate.group(3)+'\n'
        print 'Redating... ' + line

    elif retype:
        print retype.group(0)
        print retype.group(1)

        if retype.group(1) == '//p//':
            line = line + 'Type: Phone\n'
            print 'Setting type for... ' + line
        elif retype.group(1) == '//e//':
            line = line + 'Type: Email\n'
            print 'Setting type for... ' + line
        elif retype.group(1) == '//w//':
            line = line + 'Type: Walk-in\n'
            print 'Setting type for... ' + line
        elif retype.group(1) == ('' or None):
            line = line + 'Type: Ticket\n'
            print 'Setting type for... ' + line

    w.write(line)

print 'Closing Files'
f.close()
w.close()

And here's some sample input.
Ticket No.: 20100426132
Ticket Date: 04/26/10, 10:22 AM
Close Date:
Primary User: XXX
Branch: XXX
Help Tech: XXX
Status: Pending
Priority: Medium
Application: xxx
Description: some issue
Resolution: some resolution
MIS Notes: some random stuff //p// followed by more stuff
Key Words:

Ticket No.: 20100426132
Ticket Date: 04/26/10, 10:22 AM
Close Date:
Primary User: XXX
Branch: XXX
Help Tech: XXX
Status: Pending
Priority: Medium
Application: xxx
Description: some issue
Resolution: some resolution
MIS Notes: //p//
Key Words:

Ticket No.: 20100426132
Ticket Date: 04/26/10, 10:22 AM
Close Date:
Primary User: XXX
Branch: XXX
Help Tech: XXX
Status: Pending
Priority: Medium
Application: xxx
Description: some issue
Resolution: some resolution
MIS Notes: //e// stuff....
Key Words:

Ticket No.: 20100426132
Ticket Date: 04/26/10, 10:22 AM
Close Date:
Primary User: XXX
Branch: XXX
Help Tech: XXX
Status: Pending
Priority: Medium
Application: xxx
Description: some issue
Resolution: some resolution
MIS Notes:
Key Words:

A: MIS Notes:.*(//p//)?.* works like this, on the example of "MIS Notes: //p//" as the target:

*

*MIS Notes: matches "MIS Notes:", no surprises here.

*.* immediately runs to the end of the string (match so far "MIS Notes: //p//")

*(//p//)? is optional. Nothing happens.

*.* has nothing left to match, we are at the end of the string already. Since the star allows zero matches for the preceding atom, the regex engine stops reporting the entire string as a match, and the sub-group as empty.

Now when you change the regex to MIS Notes:.*(//p//).*, the behavior changes:

*

*MIS Notes: matches "MIS Notes:", still no surprises here.

*.* immediately runs to the end of the string (match so far "MIS Notes: //p//")

*(//p//) is necessary. The engine starts to backtrack character by character in order to fulfill this requirement. (Match so far "MIS Notes: ")

*(//p//) can match. Sub-group one is saved  and contains "//p//".

*.* runs to the end of the string. Hint: If you are not interested in what it matches, it is superfluous and you can remove it.

Now when you change the regex to MIS Notes:.*?//(p)//, the behavior changes again:

*

*MIS Notes: matches "MIS Notes:", and still no surprises here.

*.*? is non-greedy and checks the following atom before it proceeds (match so far "MIS Notes: ")

*//(p)// can match. Sub-group one is saved and contains "p".

*Done. Note that no backtracking occurs, this saves time.

Now if you know that there can be no / before the //p//, you can use: MIS Notes:[^/]*//(p)//:

*

*MIS Notes: matches "MIS Notes:", you get the idea.

*[^/]* can fast-forward to the first slash (this is faster than .*?)

*//(p)// can match. Sub-group one is saved and contains "p".

*Done. Note that no backtracking occurs, this saves time. This should be faster than version #3.

A: Regex are greedy, which means that .* matches as much as it can, the entire string. So there is nothing left to match for the optional group. group(0) is always the entire matched sting.
From you comment, why do you event want regex? Isn't something like this enough:
if line.startswith('MIS Notes:'): # starts with that string
    data = line[len('MIS Notes:'):] # the rest in the interesting part
    if '//p//' in data:
        stuff, sep, rest = data.partition('//p//') # or sothing like that
    else:
        pass #other stuff

A: The pattern is ambiguous for your purposes.  It would be good to group them by prefix or suffix.  In the example here, I've chosen prefix grouping.  Basically, if //p// occurs in the line, then prefix is non-empty.  Suffix will everything after the //p// item, or everything in the line if it doesn't exist.
import re
lines = ['MIS Notes: //p//',
    'MIS Notes: prefix//p//suffix']

tickettypepat = (r'MIS Notes: (?:(.*)//p//)?(.*)')
for line in lines:
    m = re.search(tickettypepat,line)
    print 'line:', line
    if m: print 'groups:', m.groups()
    else: print 'groups:', m

results:
line: MIS Notes: //p//
groups: ('', '')
line: MIS Notes: prefix//p//suffix
groups: ('prefix', 'suffix')


text:
Q: How to update existing and create new form fields in laravel i have a form that saves structured data into sections and i came up with a tricky situation when i want to edit these fields. The form has dynamic fields, so you can add any amount of sections and fields inside each section.
I have a main table which stores "Routines" which can have multiple "sections" and those can have multiple entries of "exercises".
Right now my solution is to delete the current entries and save everything as a completely new routine.
 public function update(Request $request, $id)
    {
        $user = auth()->user();
        $user->routines()->whereId($id)->delete();

        $requestArr = $request->all();
        $routine = new Routine();
        $routine->user_id = auth()->user()->id;
        $routine->name = $requestArr['name'];
        $routine->description = $requestArr['description'];
        $routine->save();

        $routine_id = $routine->id;

        foreach($requestArr['sections'] as $item){
            $section = new Section();
            $section->name = $item['name'];
            $section->description = $item['description'];
            $section->routine_id = $routine_id;
            $section->save();

            $section_id = $section->id;

            if( array_key_exists( 'exercises', $item ) ){
                foreach($item['exercises'] as $item2){
                    $exercise = new Exercise();
                    $exercise->name = $item2['name'];
                    $exercise->description = $item['description'];
                    $exercise->duration = 60;
                    $exercise->duration_unit = 'seconds';

                    $section->exercises()->save($exercise);
                }
            }
        }

        return redirect('/routines');
    }

Im sure there is a more "elegant" way of doing this.
My migrations:
Routines:
Schema::create('routines', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id');
    $table->string('name');
    $table->string('description');
    $table->timestamps();

    $table->foreign('user_id')
        ->references('id')
        ->on('users')
        ->onDelete('cascade');
});

Sections:
   Schema::create('sections', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('routine_id');
        $table->string('name');
        $table->string('description');

        $table->timestamps();

        $table->foreign('routine_id')
            ->references('id')
            ->on('routines')
            ->onDelete('cascade');
    });

Exercises:
Schema::create('exercises', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('description');
    $table->integer('duration');
    $table->string('duration_unit');

    $table->timestamps();

});

Routines - one to Many - Sections
Sections - many to many - Exercises (i have a exercise_section middle table)
So my question is, how can i update entries without deleting current ones? Since in case some new sections/exercises get added only those inserts should happen, rest just ->update();

A: There are multiple strategies you could implement to achieve this. Recreating the entries instead of updating them is a really expensive task, which could produce bottlenecks on your service depending on the activity.
For example, it's possible to determine which fields should be updated on a routine entry with some if clauses to check if some value is "dirty" (Even Eloquent provides some methods which could help you on this).
For the subsequent related entries (section and exercises) you'll need to implement a strategy which involves both back and front-end. For example, if the update method is receiving new and existing sections you could evaluate which didn't have an id to determine which need to be created.
However this is one of many strategies which could be implemented to avoid recreating the entries. It may looks like too many comparisons, but it results in a less expensive workload compared to recreating all of the entries.


text:
Q: Web API Returning Nested JSON Values I am working with a JSON structure being returned by a web api, but but have a problem.
Say, I have two tables, Teams and Players. They are joined by TeamID (PK on Teams and FK on Players).
I want my API call to return some JSON format similar as below:
[
    {
        TeamId: 1,
        TeamName: 'Chicago Bulls',
        TeamPlayers: [
            {PlayerId: 1, PlayerName: 'Pau Gasol'},
            {PlayerId: 2, PlayerName: 'Derrick Rose'},
            {PlayerId: 3, PlayerName: 'Joakim Noah'},
            {PlayerId: 4, PlayerName: 'Jimmy Butler'},
            {PlayerId: 5, PlayerName: 'Taj Gibson'}]
    },
    {
        TeamId: 2,
        TeamName: 'Cleveland Cavaliers',
        TeamPlayers: [
            {PlayerId: 1, PlayerName: 'Lebron James'},
            {PlayerId: 2, PlayerName: 'Kyrie Irving'},
            {PlayerId: 3, PlayerName: 'Anderson Varejao'},
            {PlayerId: 4, PlayerName: 'Dion Waiters'},
            {PlayerId: 5, PlayerName: 'Shawn Marion'}]
    },
    {
        TeamId: 3,
        TeamName: 'Los Angeles Clippers',
        TeamPlayers: [
            {PlayerId: 1, PlayerName: 'Chris Paul'},
            {PlayerId: 2, PlayerName: 'Blake Griffin'},
            {PlayerId: 3, PlayerName: 'DeAndre Jordan'},
            {PlayerId: 4, PlayerName: 'Jamal Crawford'},
            {PlayerId: 5, PlayerName: 'Matt Barnes'}]
    }
]

Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using MyApp.Models;

namespace MyApp.Controllers
{
    public class TeamsController : ApiController
    {
        private DataModel db = new DataModel();

        // GET: api/teams
        public IQueryable<TeamsWithPlayers> GetTeamsAndPlayers()
        {
            var query = from x in db.Teams
                        join y in db.Players on x.TeamId equals y.TeamId
                        select
                        {
                            // This is where I need some help...
                        }
        }
    }
}

TeamAndPlayer Class:
namespace MyApp.Models
{
    public class TeamAndPlayers
    {
        public int TeamId { get; set; }
        public string TeamName { get; set; }
        public Players players { get; set; }
    }
}

Players Class:
namespace MyApp.Models
{
    public class Players
    {
        public int TeamId { get; set; }
        public int PlayerId { get; set; }
        public string PlayerName { get; set; }
    }
}

Can someone provide some insight?

A: *

*I will assume that the JSON structure is the source of truth here not the models (TeamWithPlayers/Players) - see my comments.

*My solution assumes that you are using Entity Framework to retrieve the data from the database because I am using "Include" method, but can replace it to use "Join".
1- Define TeamDto and PlayerDto classes to be like :
public class TeamDto
{
    public int TeamId { get; set; }
    public string TeamName { get; set; }
    public IEnumerable<PlayerDto> TeamPlayers { get; set; }
}

public class PlayerDto
{
    public int PlayerId { get; set; }
    public string PlayerName { get; set; }
}

2- Your TeamsController will be like this:
public class TeamsController : ApiController
{
    private readonly TeamDbContext _dbContext = new TeamDbContext();

    // GET api/teams
    public IEnumerable<TeamDto> GetTeamsAndPlayers()
    {
        var teams = _dbContext
            .Teams
            .Include("Players") // Load the players associated with each Team, (this depends on your declaration, but you mentioned that there is a FK from Player => TeamId)
            // you can use the join if you like or if you don't use entity framework where you cannot call Include, but the following code will stay the same
            .Select(t => new TeamDto
            {
                TeamId = t.TeamId,
                TeamName = t.TeamName,
                TeamPlayers = t.Players.Select(p => new PlayerDto
                    {
                        PlayerId = p.PlayerId,
                        PlayerName = p.PlayerName
                    })
            }).ToList();

        return teams;
    }
}

Hope that helps.

A:    var query = from x in db.Teams
    join y in db.Players on x.TeamId equals y.TeamId
    select new TeamsWithPlayers
    {
      TeamId = x.Id,
      TeamName= x.TeamName,
      Players = y
    }.ToList();

A: Love the suggested answer, VERY HELPFUL!
I used the suggested answer to make a similar solution for msyelf for learning and then tried to fit the above solution code into a getbyid method.
I had a couple of struggles but came up with the following working solution, in case anyone ever stumbles across this post like I did and wants to know how to use the above solution with a getbyid method.
Here is the default WebAPI getbyid method that VS created:
    // GET: api/teams/5
    [ResponseType(typeof(teams))]
    public IHttpActionResult Getteams(long id)
    {
        teams teams = db.teams.Find(id);
        if (teams == null)
        {
            return NotFound();
        }

       return Ok(teams);
    }

Here is the updated Getbyid method using the structure used for the answer in this post:
    // GET: api/teams/5
    [ResponseType(typeof(teams))]
    public IHttpActionResult Getteams(long id)
    {
            var teams = _dbContext
            .Teams
            .Where(t => t.TeamId == id)
            .Include("Players")
            .Select(t => new TeamDto
            {
                TeamId = t.TeamId,
                TeamName = t.TeamName,
                TeamPlayers = t.Players.Select(p => new PlayerDto
                    {
                        PlayerId = p.PlayerId,
                        PlayerName = p.PlayerName
                    })
            })
        });

        if (request == null)
        {
            return NotFound();
        }

        return Ok(requests);
    }


text:
Q: Webdeploy - precompile asp.net application error with excluded connectionstrings in excluded app_data folder I try to use webdeploy for our asp.net application. Today I tried to activate the "Precompile during publishing" flag. It seems that this flag doesn`t work together with the "Exclude files from the App_Data folder".
Before I activated the precompiling in webdeploy everything worked fine. If I remove the configSource from my connectionStrings and run the webdeploy with precompiling it works again.
The problem is that I have to load the external connectionstring file, because it will be managed by the administrators for production-environments.
The error message I get from webdeploy is:
"An error occurred loading a configuration file: Directory 'C:\MyProject\obj\Release\AspnetCompileMerge\Source\App_Data' does not exist. Failed to start monitoring file changes."
My current setup is the following:
Web.Config:
<configuration>
  <!-- Section stuff here -->
  <connectionStrings configSource="App_Data\DBConnection.xml" />
  <!-- More stuff here -->
</configuration>

New webdeploy settings:

A: Try excluding the config file from the package by adding the following MSBuild script to either your project file or a wpp.targets file:
<ItemGroup>
  <ExcludeFromPackageFiles Include="App_Data\DBConnection.xml">
    <FromTarget>Project</FromTarget>
  </ExcludeFromPackageFiles>
</ItemGroup>

A: Hey this did not work for us. But we also updated our tfs in the last days and we had a look into the webdeploy parameters which can be set easily with the release Manager from our new tfs. So we just readded he connectionstrings into the web.config and than we compile everything. In the end we decided where it's going to be deployed and than we set automatically the connectionstrings, which are hidden for us Devs.


text:
Q: Selecting characteristics for prediction of stock returns (Adaptive Group Lasso in R) In attempt to find out what drives the predictive power and not the explanatory power of cross sections of expected return. We attempt to split the characteristics of stocks in quadratic splines, these quadratic splines of stock characteristics is then used in an Group LASSO, to try to select the variables that have predictive power. The model here chooses an array of characteristics. These characteristics are used in the next step to use an Adaptive Group LASSO, as the Group LASSO selects too many characteristics.
The Adaptive Group LASSO selects what seem to be reasonable characteristics, but we have a hard time using the model to predict.
We are using the OEM package in R to try to predict. The model seems to be good, but the prediction seems off.
Main question is: When using the selected variables to predict, should the AGLasso model (x) from the OEM be used with the quadratic splines or the original data (raw stock characteristics)?
Please help


text:
Q: Android : Change the color of radio button in custom layout for spinner I want to change the color of radio button on being tapped. I am using custom layout with on custom edit text and radio button in it.This is my xml for layout item.

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true">

    <com.ekcoffee.ekcoffeeapp.widgets.AppTextView
        android:id="@+id/textViewCountryCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:paddingRight="@dimen/dimen_10dp"
        android:text="+91 (India)"
        android:textColor="@color/color_black_text"
        android:textSize="@dimen/dimen_16sp"
        app:textStyle="@integer/OPEN_SANS_REGULAR" />

</RelativeLayout>

<RadioButton
    android:id="@+id/selector"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:backgroundTint="@color/color_accent"
    android:checked="false"
    android:clickable="false"
    android:focusable="false"

    />

This is my xml for spinner
<android.support.v7.widget.AppCompatSpinner
    android:id="@+id/spinnerCountryCode"
    style="@style/spinner_style"
    android:layout_width="@dimen/dimen_1dp"
    android:layout_height="@dimen/dimen_1dp"
    android:layout_alignParentBottom="true"
    android:hint="+91"
    android:spinnerMode="dialog"
    android:textColor="@color/color_splash_screen_text"
    android:textColorHint="@color/color_white"
    android:textSize="@dimen/dimen_25dp" />

i have used style also for spinner
<style name="spinner_style" parent="Widget.AppCompat.Spinner.Underlined">
    <item name="android:background">@color/color_primary</item>
    <item name="android:layout_marginLeft">@dimen/dimen_48dp</item>
    <item name="android:layout_marginRight">@dimen/dimen_24dp</item>
    <item name="android:layout_marginBottom">10dp</item>
    <item name="android:checkMark">@drawable/ic_radio_checked</item>
    <item name="android:paddingLeft">8dp</item>
    <item name="android:layout_marginTop">100dp</item>
    <item name="android:paddingBottom">5dp</item>
</style>

A: More simple, just set the buttonTint color: (only works on api level 21 or above)
<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/radio"
    android:checked="true"
    android:buttonTint="@color/your_color"/>

in your values/colors.xml put your color in this case a reddish one:
<color name="your_color">#e75748</color>

Result:

A:   int textColor = Color.parseColor(#000000);
    yourradiobutton.setButtonTintList(ColorStateList.valueOf(textColor));

put above code inside your button's onClick method

A: In your styles.xml put -
  <!-- custom style -->
  <style name="radionbutton"
         parent="Base.Widget.AppCompat.CompoundButton.RadioButton">
    <item name="android:button">@drawable/radiobutton_drawable</item>
  </style>

Your radio button in xml should look like-
<RadioButton
    android:layout_width="wrap_content"
    style="@style/radionbutton"
    android:checked="false"
    android:layout_height="wrap_content"
    />

Now all you need to do is make a radiobutton_drawable.xml in your drawable folder. Here is what you need to put in it-
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/radio_unchecked" android:state_checked="false" android:state_focused="true"/>
  <item android:drawable="@drawable/radio_unchecked" android:state_checked="false" android:state_focused="false"/>
  <item android:drawable="@drawable/radio_checked" android:state_checked="true" android:state_focused="true"/>
  <item android:drawable="@drawable/radio_checked" android:state_checked="true" android:state_focused="false"/>
</selector>

Your radio_unchecked.xml-
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="oval">
  <stroke android:width="1dp" android:color="@color/colorAccent"/>
  <size android:width="30dp" android:height="30dp"/>
</shape>

Your radio_checked.xml-
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="oval">
      <stroke android:width="1dp" android:color="@color/colorAccent"/>
      <size android:width="30dp" android:height="30dp"/>
    </shape>
  </item>
  <item android:top="5dp" android:bottom="5dp" android:left="5dp" android:right="5dp">
    <shape android:shape="oval">
      <solid android:width="1dp" android:color="@color/colorAccent"/>
      <size android:width="10dp" android:height="10dp"/>
    </shape>
  </item>
</layer-list>

Just replace @color/colorAccent with the color of your choice.


text:
Q: Determinant of a special nxn matrix I need to calculate the determinant of $A$, where $A$ is a $N$x$N$ matrix.
With $A = (a_{ij})$ with $a_{ij} = i+j$
For a 1x1 matrix i found $det(A) = 2$ and same for a 2x2 $det(A) = 2$
But nof for a 3x3 I've founr $det(A) = 0$. So I got an inconsistency.
Anyone can help me further?

A: I will give here a matrix explanation.
Let us consider for example the case $4 \times 4$, which is in fact illustrative of the general case $n \times n$.
You can write $A$ as the sum:
$$\pmatrix{1&1&1&1\\2&2&2&2\\3&3&3&3\\4&4&4&4}+\pmatrix{1&2&3&4\\1&2&3&4\\1&2&3&4\\1&2&3&4}=\pmatrix{1\\2\\3\\4}\pmatrix{1&1&1&1}+\pmatrix{1\\1\\1\\1}\pmatrix{1&2&3&4}$$
which the sum of 2 rank-1 matrices, thus has rank $\leq 2$, and in fact effectively two.
Thus, due to the rank-nullity theorem, $\dim \ker A= 4 -2>0$ (and more generally $n-2$). Thus $\det(A)=0$.
It explains the "barrier" beyond $n=2$.

A: If $n\ge 3:$ $$\det A=\begin{vmatrix} 2 & 3 & \ldots & n+1\\ 3 &4 & \ldots & n+2  \\ 4 &5 & \ldots & n+3 \\ \vdots&&&\vdots \\ \end{vmatrix}\underbrace{=}_{R_2-R_1,R_3-R_2}\begin{vmatrix} 2 & 3 & \ldots & n+1\\ 1 &1 & \ldots & 1  \\ 1 &1 & \ldots & 1 \\ \vdots&&&\vdots \\ \end{vmatrix}=0.$$

A: Actually the value of $\operatorname {det}_{A_{1\times 1}} =2$ and $\operatorname {det}_{A_{2 \times 2}} =2\times 4 -3\times 3=-1$. After that the determinant is always zero.
That is because $R_3-R_1, R_4-R_1,\cdots R_n-1$ for a matrix $A _{n \times n}$ is always a multiple of $R_2-R_1$ where that entire row will be filled with ones. Hence, by the fundamental property, we have the determinant as zero. Hope it helps.


text:
Q: Android HttpsUrlConnection javax.net.ssl.SSLException Connection closed by peer handshake error when using local truststore I'm having trouble with getting Android to connect to a simple OpenSSL server using the HttpsUrlConnection object (I've combed through StackOverflow and a bunch of online tutorials, and followed the examples pretty much line for line and I still can't figure out why mine is broken when I use my local truststore).
I currently have an Android activity that attempts to connect to a simple OpenSSL server (I can connect to my server using a OpenSSL client), once the HttpsUrlConnection.connect() is called I receive a "javax.net.ssl.SSLException: Connection closed by peer" error during the SSL handshake.  Perhaps I am setting up my sample server incorrectly?
Things to note:

*

*no client authorization at the moment

*am able to connect to https://www.google.com when loading default trust store

*am not able to connect to server on localhost with self-signed certificate

*do not want to trust all certificates

*do not want to use Apache HttpClient

*want to use local truststore only

*created local truststore with bouncy castle

*am able to correctly load truststore into

*behind a proxy firewall, proxy is set on my android virtual device

*AVD set to Android 4.1 API 16.

Things I have already tried:

*

*connecting to both 127.0.0.1 and 10.0.2.2

*using a new SecureRandom() with the SSLContext.init()

*creating the URL with 'URL u = new URL("https", "10.0.2.2", 443, "/");'

*using TrustManagerFactory.getDefaultAlgorithms() instead of the "X509"

*

*gives "Unexpected response code error 503" instead of "Connection closed by peer"

Thank you in advance for taking the time to review my question!
Simple server started with command:
$ sudo openssl s_server -accept 443 -cert server-cert.pem -key server-key.pem -pass file:passphrase.txt -state -www -verify 0

Client connection tested with command:
$ openssl s_client -connect 127.0.0.1:443

Android activity code (edited to remove complete running code for simplification - please let me know if more code is needed) - error output is below the code.
    try {
        TrustManagerFactory tmf;

        // local trust store
        tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(loadLocalKeyStore(getApplicationContext()));

        // default trust store - works for https://www.google.com
        // tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // tmf.init((KeyStore) null);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
        URL u = new URL("https://10.0.2.2");

        HttpsURLConnection urlConnection = (HttpsURLConnection) u.openConnection();

        urlConnection.setSSLSocketFactory(context.getSocketFactory());
        urlConnection.setHostnameVerifier(hostnameVerifier);
        urlConnection.connect();

        System.out.println("Response Code: " + urlConnection.getResponseCode());
        System.out.println("Response Code: " + urlConnection.getCipherSuite());
    }

    ...

    private KeyStore loadLocalKeyStore(Context context) {
        InputStream in = context.getResources().openRawResource(R.raw.newserverkeystore);
        KeyStore trusted = null;
        try {
           trusted = KeyStore.getInstance("BKS");
           trusted.load(in, "thisisasecret".toCharArray());
        } finally {
           in.close();
        }
       return trusted;
    }

Output when connecting correctly to https://www.google.com:
09-09 21:58:09.947: I/System.out(669): Response Code: 200
09-09 21:58:09.947: I/System.out(669): Response Code: TLS_ECDHE_RSA_WITH_RC4_128_SHA

Output when trying to connect to my server with self-signed certificate:
09-09 22:03:23.377: D/HttpsProxy(717): Https Request error
09-09 22:03:23.377: D/HttpsProxy(717): javax.net.ssl.SSLException: Connection closed by peer
09-09 22:03:23.377: D/HttpsProxy(717):  at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method)
09-09 22:03:23.377: D/HttpsProxy(717):  at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:395)
09-09 22:03:23.377: D/HttpsProxy(717):  at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:210)
09-09 22:03:23.377: D/HttpsProxy(717):  at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
09-09 22:03:23.377: D/HttpsProxy(717):  at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:442)
09-09 22:03:23.377: D/HttpsProxy(717):  at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
09-09 22:03:23.377: D/HttpsProxy(717):  at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
09-09 22:03:23.377: D/HttpsProxy(717):  at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
09-09 22:03:23.377: D/HttpsProxy(717):  at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)
09-09 22:03:23.377: D/HttpsProxy(717):  at com.example.myfirstapp.HttpsUrlConnectionActivity$3.doInBackground(HttpsUrlConnectionActivity.java:257)
09-09 22:03:23.377: D/HttpsProxy(717):  at com.example.myfirstapp.HttpsUrlConnectionActivity$3.doInBackground(HttpsUrlConnectionActivity.java:1)
09-09 22:03:23.377: D/HttpsProxy(717):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-09 22:03:23.377: D/HttpsProxy(717):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-09 22:03:23.377: D/HttpsProxy(717):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-09 22:03:23.377: D/HttpsProxy(717):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-09 22:03:23.377: D/HttpsProxy(717):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-09 22:03:23.377: D/HttpsProxy(717):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-09 22:03:23.377: D/HttpsProxy(717):  at java.lang.Thread.run(Thread.java:856)

Thanks again!!

A: I solved my problem - I needed to use a certificate with 10.0.2.2 as the common name (CN) so it matched Android localhost ip address of 10.0.2.2 instead of 'localhost' or '127.0.0.1'.
Edit: you could probably create a certificate with localhost as the CN and '127.0.0.1' and '10.0.2.2' as Subject Alternative Names (SAN).
Once I created 10.0.2.2 cert and private key pem files, I was able to hit my server running with the following command:
openssl s_server -accept 8888 -cert 10.0.2.2-cert.pem -key 10.0.2.2-key.pem  -state -www

If you want to force the client to provide a certificate (though it won't be checked), add the flag -Verify 1 to the command above.
To test the server at the command line you can use the following (note openssl is able to connect via 127.0.0.1):
openssl s_client -connect 127.0.0.1:8888

And to add a client cert if the server requires it, add the flags -cert client-cert.pem -key client-key.pem
In my Android client I used the following code to connect (error checking removed):
// use local trust store (CA)
TrustManagerFactory tmf;
KeyStore trustedStore = null;
InputStream in = context.getResources().openRawResource(R.raw.mycatruststore); // BKS in res/raw
trustedStore = KeyStore.getInstance("BKS");
trustedStore.load(in, "insertBksPasswordHere".toCharArray());
tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustedStore);

// load client certificate
KeyStore clientKeyStore = loadClientKeyStore(getApplicationContext());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(clientKeyStore, "insertPasswordHere".toCharArray());

SSLContext context = SSLContext.getInstance("TLS");

// provide client cert - if server requires client cert this will pass
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;

// connect to url
URL u = new URL("https://10.0.2.2:8888/");
HttpsURLConnection urlConnection = (HttpsURLConnection) u.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
urlConnection.setHostnameVerifier(hostnameVerifier);
urlConnection.connect();
System.out.println("Response Code: " + urlConnection.getResponseCode());

You should get a response code of 200, and can dissect the response from there.
Here's the code to load the client credentials, which is identical to loading the server key store but with a different resource filename and password:
private KeyStore loadClientKeyStore(Context context) {
    InputStream in = context.getResources().openRawResource(R.yourKeyStoreFile);
    KeyStore trusted = null;
    trusted = KeyStore.getInstance("BKS");
    trusted.load(in, "yourClientPassword".toCharArray());
    in.close();
    return trusted;
}

A: I wasted my 6 - 7 hours fixed this problem and finally it worked with
public void URLConnection(String webUrl) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        //TLSSocketFactory objTlsSocketFactory = new TLSSocketFactory();
        URL url = new URL(webUrl);
        HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
        urlConnection.setRequestMethod("GET");
        //urlConnection.setSSLSocketFactory(objTlsSocketFactory);

        int responseCode = urlConnection.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());
    }

And it worked !!!!!!


text:
Q: Why won't Linux let me play with /dev/dsp? I'm working through a Linux textbook, and it's telling me about devices.  It says that if I send the appropriate output to /dev/dsp, then it will play a sound.  The example is cat file.wav > /dev/dsp, where file.wav is just any .wav file.
When I do this I get permission denied.  If I run this with sudo I still get permission denied.  If I su first, no sound plays.
Why do I get permission denied with sudo?  Why does no sound play even with su?

A: /dev/dsp is part of OSS, which hasn't been part of the Linux kernel in... a very long time. It has long been supplanted by ALSA, which uses different devices, different programs, and a different API.
There is an emulation layer module though. If it is available then loading the snd-pcm-oss module will enable you to use the PCM devices for OSS such as /dev/dsp.
Or just stick to piping data to aplay or paplay instead.

A:
If I run this with sudo I still get permission denied.

By this statement, it sounds like you are trying a command like:
sudo cat file.wav > /dev/dsp

The reason you continue to get "permission denied" is that your shell first tries to open the /dev/dsp device for output, before running the command (which is sudo). To have the shell open the redirection with root privileges, you would have to do something like:
sudo sh -c 'cat file.wav > /dev/dsp'

A: Out of date book, as noted.
So to make the examples work with more modern linux, where it says something like
cat music.wav > /dev/dsp

change it to:
cat music.wav | aplay
# or
aplay music.wav


text:
Q: Remove before character (like backspace) I have some text like this: "I am a gaot[BS][BS][BS]oat"
And It should look like this: "I am a goat"
How can I use "[BS]" as 'backspace'? So remove the character before backspace.
I tried preg_replace but it replaced only 1 backspace.
Can someone help?
I tried this:
$text = preg_replace('/.{1}\[BS\]/', '', $text);

But this works only with 1 [BS].

A: There are two ways of doing this that I can see.
The "easy but long" way:
do {
    $text = preg_replace("/.\[BS\]/","",$text,-1,$c);
} while($c);

The "voodoo shortcut" way:
$text = preg_replace("/.(?R)*\[BS\]/","",$text);


text:
Q: Iterate over some chunks of data starting with certain strings I have worked on a program that could count the numbers of letters in a give data set, which start with >chrome followed by long chains of letters (a,b,c,d at random).
The chunks of data exactly look like this:
("\n" shows space in the command line):
    ">chrome0001"\n"abcdbadbcbdabdcbdbbbbadbcbbdab>chrome0011"    \n"bbbbadbcbabdbaaaadbcbddcdda>chrome0111"\n" ....
(the total number of ">chrome" is 10)."
I want to count the numbers of letters that appear after each >chrome. And expected output should be like:
>>chrome0001
a:4 b:6 c:10 d: 11
I've been thinking about whether I could use \n and >chrome to get the program working but got stuck and studied many questions and answers on this website only to dig a hole deeper... can anybody help me with this, please?

A: This is a relatively straight forward parsing problem.  First, you want to split the string on the chromeXYZ\n bits and group it with the following string.  We can do this fairly easily with regular expressions -- Here's one that works if I understand your input correctly:
>>> import re
>>> s = ">chrome0001\nabcdbadbcbdabdcbdbbbbadbcbbdab>chrome0011\nbbbbadbcbabdbaaaadbcbddcdda>chrome0111\n"
>>> re.findall(r'(>chrome\d+\n)([^>]+)', s)
[('>chrome0001\n', 'abcdbadbcbdabdcbdbbbbadbcbbdab'), ('>chrome0011\n', 'bbbbadbcbabdbaaaadbcbddcdda')]

The regular expression is straight forward (at least as far as regex go ...):

*

*(>chrome\d+\n) -- ">chrome", some numbers, and a newline

*([^>]+) -- Matches all characters until the next > or the end of the input.

From here, counting the number of characters in the subsequence is fairly easy.  You can use a collections.Counter to do the heavy lifting:
>>> from collections import Counter
>>> for chrome, alpha in re.findall(r'(>chrome\d+\n)([^>]+)', s):
...   print(chrome, Counter(alpha))
...
('>chrome0001\n', Counter({'b': 14, 'd': 7, 'a': 5, 'c': 4}))
('>chrome0011\n', Counter({'b': 10, 'a': 7, 'd': 7, 'c': 3}))


text:
Q: Creating a mobile application for a specific device I was looking to create a mobile application for this handheld thermal printer device.
This application is Win CE based. Does anyone know if there is a similar device with Android O.S(Having printer and barcode reader) ?

A: The sourcecode for the zxing project is open source and fairly simple to use, could that not work for what you want?
Google code ZXing
As far as Im aware there aren't any devices such as that one, but it may happen later on down the line, if the manufacturers who sell those devices see Android as a viable / cost effective route to take (but this would involve losing all the investment in the windows CE platform)


text:
Q: Most of the times, I am unable to read the letters when asked to verify. Why do you have to make it so difficult?
Possible Duplicate:
Impossible Captcha with non-keyboard characters

Why can't you make it easier on the eyes and show the words clearly, so that I can be able to read it without having to refresh it until I can understand the words?

A: The point of reCAPTCHA is to help digitize/translate old text, see here: http://www.google.com/recaptcha
Sorry if you have to go through a couple till you get it right, it is helping to treasure old text books.


text:
Q: How do I keep track of the bandwidth usage through my Airport Extreme wireless router? I have 3 Macs, 1 iPad, and 1 Apple TV (using HD Netflix, mostly).
I need to keep an eye on bandwidth usage.  What is the best way to monitor the bandwidth usage (preferably per device) that passes through my Airport Extreme router?
Thanks!
Rob

A: The Airport Express/Extreme allows monitoring via SNMP if you enable it via the Airport Configuration Utility (version 5.6 ONLY).
Apple removed advanced configuration parameters from Airport Configuration Utility 6.0. Please download a version 5.6 of the utility from Apple's support page to get a full access to all configuration parameters of your router. SNMP configuration is located under Advanced settings.
From there, ANY snmp polling engine can get traffic as a whole.
You would be hard-pressed to find anything that could differenciate traffic between devices that isn't a real router (Cisco, etc) or custom built Linux box.
I just found this during a quick serach: NetUseApp via iTunes Store allows you to monitor any SNMP device with a pretty interface.


text:
Q: Improving Chrome performance on OSX There are a number of sites that do not display properly on Safari and I need to switch to Chrome. Although when the content of the sites requires flash player, Chrome will consume a significant amount of CPU. Running more than 3 windows, will cause my MBP to overheat, start the fans, and reduce battery life way more than Safari.

What I am looking for is suggestions on ways to improve performance of
  Chrome running flash. I know Safari is optimised for OSX, but any improvement is welcome.

Following I have a demo to display the issue. I am running same youtube video on Safari 6 and Chrome 21,both updated,at the same time. Both browsers have been reseted and have no extensions. This is run on MBP 13" 2012 with 2.9 i7 running OSX 10.8.1.

p.s If any additional details can help please let me know.


text:
Q: Difference of mixed="true" and xs:extension in XML Schema What is the practical diference between these two:
<xs:element name="A">
 <xs:complexType mixed="true">
  <xs:attribute name="att" type="xs:boolean"/>
 </xs:complexType>
</xs:element>

<xs:element name="B">
 <xs:complexType>
  <xs:simpleContent>
   <xs:extension base="xs:string">
    <xs:attribute name="att" type="xs:boolean"/>
   </xs:extension>
  </xs:simpleContent>
 </xs:complexType>
</xs:element>

A: The two are different. Your first example uses mixed="true" which denotes mixed content, i.e. character data mixed in with child elements. Whereas your second example restricts the element content to the xs:string type. Both indicate the presence of an attribute.
With your example, both are practically the same. However, if you do not plan on having mixed content, i.e. you do not plan to add child elements, the second version is much clearer.


text:
Q: GAE Python get default bucket fxn returns None I'm a GCS newbie trying to write an app that uploads a file to a bucket I have created. I've followed the tutorial and created a bucket using the browser interface. However when I programmatically try to access my bucket, I get an error. Instead of printing my default bucket name, my app ouputs "None". My ENTIRE app code is as shown:
import webapp2
from google.appengine.api import app_identity

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write(app_identity.get_default_gcs_bucket_name())

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)

What am I doing wrong?

A: Update:
Seems you can now create a default bucket in the new console too by visiting your app engine's application settings in the cloud console https://console.cloud.google.com/appengine/settings?project=

Original:
You're getting NONE  because by default there's no longer a default bucket

About default Cloud Storage buckets
Applications created using the old App Engine console could use a
  default Cloud Storage bucket, which had free quota and didn't require
  billing to be enabled for the app. These applications continue to work
  as before in the Google Cloud Platform Console.
However, new App Engine projects created in the Google Cloud Platform
  Console don't have a default Cloud Storage bucket. Instead you must
  use a standard Cloud Storage bucket as described above.

But since you manually created the bucket, you will already have its name and so can probably skip app_identity.get_default_gcs_bucket_name() and hardcode the bucket name or call it from a config variable, etc, etc.
You can then use the gcloud-python lib to upload files to your bucket:
from gcloud import storage

client = storage.Client()
bucket = client.get_bucket('<bucket-name>')
my_file = bucket.blob('/path/to/be/saved/in/bucket')
my_file.upload_from_filename(filename='/path/to/local/file')

You'll have to vendor the gcloud lib if you're doing this on app engine.
All that said and done if you still want the old behaviour of getting the default bucket which is in the format <project-id.appspot.com>, you can follow GAEfan's answer, in short:

Go to the old console, appengine.google.com > Application Settings > Cloud Integration > Create


text:
Q: What is the behavior if a spam question is edited to a meaningful question Here is the scenario I have in mind:

*

*A question is posted on Stack Overflow.

*Apparently, it is spam (like test questions, eqruiosdsadsldfjdsd)

*Someone flagged it is spam.

*Question is edited, and spam content is removed.

What will happen to following?

*

*Question: will it be deleted? (It was spam at the time of reporting)

*If the question is not deleted, how the flag will look like in the flag history page?

(Declined or disputed or deemed helpful)

*Is there a way to revert the flag if once spam is indicated for such scenarios?

A: If a post truly was spam, there's no way it can be edited into a legitimate post.
Said another way; if a post can be edited into a legitimate post, it should not have been flagged as spam.
Spam flags are for posts that serve no purpose other than to advertise a product. You note in an above comment that you flagged this post as Spam (10k+ only). That post is not spam at all, so that flag was not valid to begin with.

If someone edited a true spam post into a valid question somehow, then they are significantly (totally) changing the meaning of the post, and that would be an invalid edit to begin with.


text:
Q: Answer to comment conversion change suggestion I would suggest that answers can't be changed to comments until none of the answers has been accepted yet.
Why not allow conversion before answer acceptance?
Because people may likely edit their answers to become more informative and provide much more information than initially posted. Posting quickly and editing afterwards is a common technique my many users. Allowing conversion before acceptance may convert some of the answers too quickly.
And what about when an answer is just a link, but to a JSFiddle working example that may get accepted as the correct answer?
Example
A good example where this has been done too soon is this answer. I've afterwards added a new answer and removed the comment, but It proves my point.
Answers should not be allowed to be converted to comments until OP accepts an answer.
Additional edit - grace period for answer amendment
It is true that when OP doesn't accept an answer, such answers would be stuck as answers instead of being converted. A 5 minute grace period to amend an answer is simply not enough because a decent answer may on some topic may take considerably longer to complete.
So when can answers get converted then?

*

*When user accepts an answer.

*After 24 hours if no answer gets accepted - this would also work with those users that don't just sit and wait for the answers but may do other things as well, so communication with them is more sporadic.

A: I disagree. If you post an answer which is at most a comment, you are explicitly taking the risk of it being converted to a comment. If this is caused by a lack of information provided by the OP, then hold off on providing an answer. Ask for clarification first.
I see no reason why we should allow poor answers to exist, assuming they might be improved somewhere in the future. Either write a real answer to begin with, or make it a comment if it is not a real answer. Bad content should be filtered out as quickly as possible and not be allowed to exist simply because it might be improved.


text:
Q: Django form Wizard: Create "Add Another Record" button on same form I am using django form wizard with 9 steps. My problem is that i need to populate a listview with with multiple records using same form(on step5).
In short on step5 i want my form to have "Add another record" button. When i click this button staying on the same page i populate the table below, usage of this button will be optional. Then i proceed to next steps and complete my process.
my get_form currently looks like this:
def get_form(self, step=None, data=None, files=None):

    # determine the step if not given
    if step is None:
        step = self.steps.current

    return form

what should be my approach?


text:
Q: Switch ribbon category for the user I have a program written in C++ using MFC. It has a ribbon UI, Office style.
I would like to achieve the following - Suppose the user has highlighted category A of the ribbon, and clicks a button in that category, I would like my program to switch to category B and highlight it for him in response to that click.
This might sound strange, but I really have a use case where the user might not realize that he needs to switch categories, so I would like to do it for him automatically.
Can this be done?

A: Perhaps you're looking for CMFCRibbonBar::SetActiveCategory.
There is a similar question on CodeProject that includes a sample function for programmatically selecting a category by name. Reproduced below for information:
int CYourClassName::ActivateCategoryByName( CString strCategoryName)
{
    // Grab Pointer to MainFrame
    CMainFrame* pMainFrame = ( CMainFrame*) AfxGetMainWnd();

    // Grab Pointer to RibbonBar
    CMFCRibbonBar* pmrb = &pMainFrame->m_wndRibbonBar;

    // Get Category Count
    int nCategoryCount = pmrb->GetCategoryCount();

    // Scan Category
    for ( int nCategoryNdx = 0; nCategoryNdx < nCategoryCount; nCategoryNdx++)
    {
        // Grab Pointer to Category
        CMFCRibbonCategory* pmrc = pmrb->GetCategory( nCategoryNdx);

        // Get Category Name
        CString strName = pmrc->GetName();

        // Check for Requested Category
        if ( strName == strCategoryName)
        {
            pmrb->ShowCategory( nCategoryNdx, TRUE);
            pmrb->SetActiveCategory( pmrc, TRUE);
            return nCategoryNdx;
        }
    }

    return -1;
}


text:
Q: How to obtain difference in minutes between two raw dates in javascript? How to obtain difference in minutes between two raw dates in javascript? i.e. to use as '2 minutes ago', '10 minutes ago', etc.
By RAW I mean this format -> 2015-02-05T03:11:33.301Z (var x = new Date())
This is what I have but I always get NaN in the return value...
function getMinutesBetweenDates(startDate, index) {
    var endDate = new Date();
    var diff = endDate - startDate;
    return (diff / 60000);
}

Thanks for your help.

A: I think problem would be the way you will be calling your function.
You should call it like bellow
var startDate = new Date("2015-02-05T03:11:33.301Z");
getMinutesBetweenDates(startDate);

It will print something like bellow
11.711916666666667

Just use Math.floor before returning value to get the result as 11.

A: Try this,
You have to convert startDate to a Date object even it's in the JSON format of Date object. The reason is, when you subtract, the valueOf method of the Date objects are called and subtracted. The return values of valueOf method are different in Date objects and JSON strings.

function getMinutesBetweenDates(startDate) {
    var endDate = new Date();
    var startDate = new Date(startDate);
    document.write(startDate.valueOf());
    var diff = endDate - startDate;
    return (diff / 60000);
}

document.write(getMinutesBetweenDates("2015-02-05T03:11:33.301Z"));

A: Modern browsers will correctly parse a string in the OP format (a version of ISO 8601) however older browsers like IE 8 and lower will not. It's much safer to manually parse the string:
function parseISOutc(s) {
  var b = s.split(/\D/);
  return new Date(Date.UTC(b[0], b[1] - 1, b[2], b[3], b[4], b[5], (b[6] || 0)));
}

Now your function can be:
function getMinutesBetweenDates(startDate) {
    return ((new Date() - parseISOutc(startDate)) / 6e4 | 0) + ' minutes ago';
}

The index parameter was unused so I removed it.


text:
Q: NodeJS - C/C++ Addon communication (stdin stdout) I am trying to pass an audio stream to C/C++ Addon. But first I want to understand and implement some basic examples. The whole objective is to use stdin and stdout to pipe information between nodeJS and the addon.
In nodejs I can see the stdout with this code:
var fs = require('fs');
var readableStream = fs.createReadStream('file.txt');
var data = '';

readableStream.on('data', function(chunk) {
    data+=chunk;
});

readableStream.on('end', function() {
    console.log(data);
});

But now, How can I pass it to c/c++ addon?

A: You cannot pass data directly from NodeJS to C++. You can write/develop your own Node addon/module in C++ which exposes some functions to (Node) JS then pass the data to these functions:
var myModule = require('mymodule'); // The Node addon you wrote
myModule.processData(data);

Now, processData receives data from JS and it is a C++ implementation so there you go.

A: Here is an example of creating a native addon in Linux. Hope this helps:
#include <node.h>
using namespace v8;

void foo(const FunctionCallbackInfo<Value>& args) {

// extract the parameter(s)
int value = args[0]->NumberValue();
// do stuff with value.

//optionally, return a value.
args.GetReturnValue().Set(value + 10);
}

void init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "processData", foo);
}
NODE_MODULE(addon, init)

Build: Linux (ia32):
g++  -I./deps/v8/include  -I./src -shared -m32 -o mymodule.node mymodule.cc

*

*NODE_MODULE macro directs node to register amodule named 'mymodule' and export a method called 'processData' which is internally mapped to 'foo'

*This makes the handshake between JS space and the C++ space for method calls.

*Now you can make a call to 'processData' as suggested marekful.

A: Assuming nodejs script:
var addon = require('./build/Debug/addon.node');
var fs = require('fs');
var readableStream = fs.createReadStream('file.txt');
var data = '';

readableStream.on('data', function(chunk) {
    data+=chunk;
});

readableStream.on('end', function() {
    console.log("loaded");
    console.log('addon invocation:', addon.read_stream(data));
});

This script can load the file information:
#include <node.h>
#include <iostream>
#include <string>

using namespace v8;
using namespace std;

void read_stream(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  if (args.Length() < 1) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong number of arguments")));
    return;
  }

  v8::String::Utf8Value param1(args[0]->ToString());
  std::string auxiliar = std::string(*param1); //JS---->C++

}

void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "read_stream", read_stream);
}

NODE_MODULE(addon, Init)

In the debug "auxiliar" string will have the text of "file.txt". Now its time to try with wav files.