text:
Q: Handling googleapi client errors I am reading and creating the calendar event for set of emails through Google calendar API. Now If I give one email id is wrong it's throwing an error .
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.goo
gleapis.com/calendar/v3/calendars/xxx%40gmail.com/events?timeMin=2019-1
2-18T00%3A00%3A00%2B05%3A30&maxResults=240&timeMax=2019-12-18T23%3A59%3A00%2B05%
3A30&singleEvents=true&orderBy=startTime&alt=json returned "Not Found">

I can understand there is wrong in the email and I am getting this error. But I want to handle this exception,like if my email is wrong also it should skip the wrong email and it should go further and display the proper result.
What I tried is
from googleapiclient.errors import HttpError

def my_funtion():

        try:
            ----
            -----
        except HttpError as err:
            print("The exception is",err)
        finally:
            return "I am returning whatever i get it from try

Is it correct try catch block?
for the above code I am getting the same googleclientapi error,It's not going inside the excpet block
What I expect here is
It should go to the try block,if one of the email id is wrong,it should skip the email id and it should return the result of whatever is getting fetched from the try block.
I can say it should omit the apiclient but and return the result.
#for calendar_id in calendar_ids:
    eventsResult = service.events().list(calendarId=["a@gmail.com","b@gmail.com","c@gmail.com"],timeMin=start_date,timeMax=end_date,singleEvents=True,orderBy='startTime').execute()
    events = eventsResult.get('items', [])
    if not events:
        print('No upcoming events found.')
    print(events)
    while True:
        for event in events.get('items', []):
            print(event['summary'])
        page_token = events.get('nextPageToken') #check if any event present in next page of the calendar
        if page_token:
            events = service.events().list(calendarId='primary', pageToken=page_token).execute()
        else:
            break

    for calendar_id in calendar_ids:
        count = 0
        print('\n----%s:\n' % calendar_id)
        try:
            eventsResult = service.events().list(
                calendarId=calendar_id,
                timeMin=start_date,
                timeMax=end_date,
                singleEvents=True,
                orderBy='startTime').execute()
            events = eventsResult.get('items', [])
            if not events:
                print('No upcoming events found.')
            for event in events:
                if 'summary' in event:
                    if 'PTO' in event['summary']:
                        count += 1
                        start = event['start'].get(
                            'dateTime', event['start'].get('date'))
                        print(start, event['summary'])
        except exception as err:
            print("I am executing",err)
        finally:
            print('Total days off for %s is %d' % (calendar_id, count))```

A: I have got the answer for this post. I have used 'pass' in exception block and it worked well.Thanks


text:
Q: ms-rest-nodeauth (azure-sdk-for-js) : Error: credentials argument needs to implement signRequest method Trying to follow the samples from https://github.com/Azure/ms-rest-nodeauth
When passing authresponse to a client to generate a client to ping resources, I end up getting:
Error: credentials argument needs to implement signRequest method
I am trying to read through the documents to see if I need to sign the token's I am getting back from the SDK/Azure AD, but the documentation for the new SDK doesnt show anything

A: Figured it out, have to call .credentials on the authresponse

A: Adding the code, using @azure/arm-billing, in case the full code file is helpful.
// auth.json
// Create auth file with Azure CLI:`az ad sp create-for-rbac --sdk-auth > auth.json`
{
"clientId": "",
"clientSecret": "",
"subscriptionId": "",
"tenantId": "",
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
"resourceManagerEndpointUrl": "https://management.azure.com/",
"activeDirectoryGraphResourceId": "https://graph.windows.net/",
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
"galleryEndpointUrl": "https://gallery.azure.com/",
"managementEndpointUrl": "https://management.core.windows.net/"
}

// index.js
const msRest = require("@azure/ms-rest-js");
const msRestAzure = require("@azure/ms-rest-azure-js");
const msRestNodeAuth = require("@azure/ms-rest-nodeauth");
const armBilling = require("@azure/arm-billing");
const path = require('path');

// list billing information
const lists = async (client) => {

    try {
        let lists = [];

        const enrollmentAccounts = await client.enrollmentAccounts.list();
        lists.push(enrollmentAccounts);

        const billingPeriods = await client.billingPeriods.list();
        lists.push(billingPeriods);

        const invoices = await client.invoices.list();
        lists.push(invoices);

        return lists;
    } catch (err) {
        console.log(err);
        throw (err);
    }

}

// sample auth file created from Azure CLI - removed PII
const authenticationFile = path.join(__dirname, "./auth.json");
const options = {
    filePath: authenticationFile
};

// get subscriptionId from auth file
const subscriptionIdFromAuthFile = require('./auth.json').subscriptionId;

// authenticate and getting billing information
msRestNodeAuth.loginWithAuthFileWithAuthResponse(options).then(async (response) => {

    console.log("authenticated");

    // --- CHANGE response parameter to -> response.credentials
    const client = new armBilling.BillingManagementClient(response.credentials, subscriptionIdFromAuthFile);
    console.log("client created");

    const results = await lists(client);
    console.log(`The result is:${JSON.stringify(results)}`);

}).catch((err) => {
    console.error(err);
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: loop over an arraylist of strings I'm writing java code to loop over an ArrayList of Strings. If the length of the String is 4, then add in front of it a certain character.
This is the code i have written. When I do things explicitly it works, but when I write the loop it doesn't and I can't find where my mistake is.
An example is below. I want the output to be ("hello", "**", "me")
import java.util.ArrayList;
public class Client {
    public static void main(String[] args) {
        ArrayList<String> list= new ArrayList<String>();
        list.add("hello");
        list.add("me");
        //without loop: this gives me correct output
        if(list.get(0).length()==2) list.add(0, "**");
        if(list.get(1).length()==2) list.add(1, "**");
        /* when i loop i get an error,
        for(int i=0; i<list.size()-1; i++) {
            if(list.get(i).length()==2) list.add(i, "**");
        }
        */
        System.out.println(list);
    }
}

A: size() - 1 was wrong, and adding needs to skip extra.
for (int i=0; i < list.size(); i++) {
    if (list.get(i).length() == 2) {
        list.add(i, "**");
        i++; // Do skip the item
    }
}

BTW: one may write:
    List<String> list = new ArrayList<>();
    Collections.addAll(list, "hello", "me");

A: You could use an enhanced for loop to loop through all of the string and have direct access instead of having to index to access them.
for (String s : list)
{
    /* CODE */
}

And instead of having to use the get method to access the string and it's length, you can just use the s variable and use s.length()

A: You should do like this
import java.util.ArrayList;
public class Client {
public static void main(String[] args) {
            ArrayList<String> list= new ArrayList<String>();
            ArrayList<String> newList= new ArrayList<String>();
            list.add("hello");
            list.add("me");
            for(int i=0; i<list.size(); i++) {
                if(list.get(i).length()==2)
                    newList.add("**");
                else
                    newList.add(list.get(i));
            }
            System.out.println(newList);
}


text:
Q: Trouble trying to update a scope variable using Firebase facebook connect and AngularJS here's the thing...
I'm using AngularJS, and trying to use firebird's facebook connect to try a few things.
Everything is almost fine, it connects to my facebook, and returns the information of my account, but here is the thing, as i'm using angular, i'll use the ng-show and ng-hide to show and hide the connect button right?
so i have a structure like that:

        Login with Facebook
        check

        Logout

The logedUser verifies if the user is loged or not, so its true or false, making one div to be showing, and the other to be hiding.
the problem is when i try to update this variable thought my angular controller, here is the code:
app.controller('LoginCtrl', function($scope) {

$scope.loginFacebook = function() {
    auth.login('facebook', {
        rememberMe: true,
        scope: 'email,user_likes'
    });
};

$scope.logout = function() {
    auth.logout();
};

$scope.checkAuth = function() {
    console.log($scope);
};

var loginRef = new Firebase('https://angulartodolist.firebaseIO.com/');

var auth = new FirebaseSimpleLogin(loginRef, function(error, user) {
    if (error) {
        // an error occurred while attempting login
        console.log(error);

        $scope.logedUser = false;
    } else if (user) {
        // user authenticated with Firebase
        console.log(user);

        $scope.logedUser = true;
    } else {
        // user is logged out
        $scope.logedUser = false;
    }
}); });

so what is happening, when i click on login, it calls the loginFacebook() function, it authenticates, and then returns my users info, after that, i change the logedUser variable to true, using $scope.logedUser = true;
But in my front-end its not changing the divs, so i created a function called checkAuth(), just to access the controller, and making a simple console.log, after i execute that function, it changes the divs, making the login div to disappear, and the logout div to appear...
shouldnt it happens automaticaly just by setting the variables in the Firebase's callback?

A: Add
$scope.$apply()

in FirebaseSimpleLogin callback function :)
Usually, every callback outside "angular's world" need this to refresh its scope.


text:
Q: Excel-like user input in python GUI applications Does python have any library to let user enter input values in cells in application GUI?
I mean, I will copy 10 values from an excel sheet (A1:A10) end paste it into cells in python GUI, and application will accept those 10 values.

A: Yeah. Copy and paste, select and set color, adjust col and row width/height. You name it, you get it. Haven't done it in many years and can't remember all the tricks. But it is quite easy to do in Boa Constructor, http://boa-constructor.sourceforge.net/. Also see this very helpful blog: http://www.blog.pythonlibrary.org/2010/03/18/wxpython-an-introduction-to-grids/. A real example that I wrote a few years back: http://sourceforge.net/projects/deday/


text:
Q: Disconnected Network Adapter on VMware - only power cycle solve this I have a weird issue:
On a VMware 5.1.0 installed on a Dell R620, the network adapter gets disconnected.

Hitting the 'D'  button for additional info, shows the following.

*

*I tried to reset the iDrac - with no results.

*the iDrac shows the network cable connected

*Testing the management network fails

*I tried the reset Management network - (ofc, not with hopes but I had to try)

But the adapter is still disconnected.

*

*it is connected to an HP switch - resetting the switch didn't change

*Yes, I did replace the cable :-/

*Dell has already replaced one network interface (this is the new one = previous had the same behavior)

*The only thing that works is a full shutdown/power up cycle - of the host - which is ofc not the solution.

*I am not sure what to look for in the system logs.

*Is there a VM patch I need to look for?
-- UPDATE: I have moved my VM's to another vswitch, leaving only the management network on NIC1 (this was after a restart) and everything worked - after some time (can't say exactly) the same thing happned: vmnic0 has become disconnected (with only the management network on it)

A: A few quick items to resolve this:

*

*Update the firmware on your Dell PowerEdge R620 hardware and NICs. Firmware updates are super-important on server hardware like this. See this post on the Dell forums: "DELL R720 & ESXi 5.0 Network Connectivity Loss on Intel I350 NIC"

*Upgrade to the current release of ESXi. The current build is 914609. It's a good thing to do in general. The process is quick and easy.

*Also make sure you install the Dell CIM agents for ESXi. It's an offline .VIB bundle. This gives you hardware-specific monitoring.

*And please use multiple NICs for your management/VM network... even if this is a standalone host.

A: The issue can be maybe because you changed the speed and duplex of vmnic, try to reset it, login in support mode and list your vmnic and see if is 0mbps this mean that you've changed the settings.
first see details with: esxcfg-nics -l
So reset in this way: esxcfg-nics -a vmnic1 or esxcfg-nics -s 100 -d full vmnic1
More details here: http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1004089

A: Apparently the issue was with a broken/malfunctioning adapter.
Manufacturer replaced it, and it works.


text:
Q: Parsing generic XHR response into JSON objects Say that we use XMLHttpRequest to perform a GET request on an API endpoint. The endpoint returns some kind of JSON response (it can be one JSON object or an array of JSON objects). What is the best way to take these response and convert it into a generic JSON object to save in memory?
For example, here is some code
var xhr = new XMLHttpRequest();
xhr.open('get', myURL);
arr = []
xhr.onload = function ()
{
    if(xhr.readyState == 4 && xhr.status == 200){
        response = xhr.response
        // save every incoming JSON object into arr
    }
}

I want to be able to write something generic (ie. it will work on any API endpoint that returns a JSON). Does anyone have any recommendations or a library to go about this?


text:
Q: How to do Text classification using tensorflow? I am new to tensorflow and machine learning. I am facing issues with writing a tensorflow code which does the text classification similar to one I tried using sklearn libraries. I am facing major issues with vectorising the dataset and providing the input to tensorflow layers.
I do remember being successful in one hot encoding the labels but the tensorflow layer ahead did not accept the created array.
Please note, I have read majority of text clasification answered questions on stackoverflow but they are too specific or have complex needs to resolve.
My problem case is too narrow and requires very basic solution.
It would be great help if anyone could tell me the steps or tensorflow code similar to my sklearn machine learning algorithm.
Dataset used is avaialable at : https://www.kaggle.com/virajgala/classifying-text

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import SGDClassifier
from sklearn.pipeline import Pipeline

#Reading the csv dataset
df = pd.read_csv(('/Classifyimg_text.csv'), index_col=False).sample(frac=1)

#Splitting the dataset
train_data, test_data, train_labels, test_labels = train_test_split(df['sentence'], df['label'], test_size=0.2)

#Vectorization and Classification
streamline = Pipeline([('vect', TfidfVectorizer(max_features=int(1e8))),
                           ('clf', SGDClassifier())]).fit(train_data, train_labels)

#Prediction
Output = streamline.predict(["This is my action to classify the text."])

A: If you want to achieve seminal scores I'd rather use some embedder. Natural language is rather quite hyper-dimensional. Nowadays there's a lot of pretrained architectures. So, you simply encode your text to latent space and later train your model on those features. It's also much easier to apply resampling techniques, once you have numerical feature vector.
Myself, I mostly use LASER embedder from Facebook. Read more about it here. There's unofficial pypi package, which works just fine. Additionally, your model will be working on dozens of languages out-of-the-box, which is quite cute.
There's also BERT from Google, but the pretrained model is rather bare, so you have to push it a bit further first.


text:
Q: Showing images in markdown for gatsby I am following the Working with images in markdown posts and pages  tutorial for gatsby and installed the following plugins

*

*gatsby-image

*gatsby-transformer-sharp

*gatsby-plugin-sharp

My images are in the same directory as my Markdown files in src/content. But my posts are still without images. I suspect I have to change something in my src/templates/blog-post.js to show the images but am unsure of the next step. Can someone tell me what changes I need to make?
Github

A: In order to embed images in markdown you also need gatsby-remark-images. Run yarn add gatsby-remark-images or npm install --save gatsby-remark-images.
Add this to your gatsby-config.js:
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 590,
            },
          },
        ],
      },
    },


text:
Q: In Copula, pseudo-observation used with kendall tau, but not with Maximum likelihood, Why? This is not a coding question! I am confused about using pseudo-observation with some functions but not with MLE in copula model. That is, in copula package, the authors wrote that,
## A Gumbel copula
    set.seed(7) # for reproducibility
    gumbel.cop <- gumbelCopula(3, dim=2)
    x <- rCopula(n, gumbel.cop) # "true" observations (simulated)
    u <- pobs(x)                # pseudo-observations
    ## Inverting Kendall's tau
    fit.tau <- fitCopula(gumbelCopula(), u, method="itau")
    fit.tau

here the author used pseudo-observations with inversion Kendall's tau, the same for log likelihood function. However, the author wrote this for MLE,
## Maximum likelihood -- use 'x', not 'u' ! --
    fit.ml <- fitCopula(gumbelCopula(), x, method="ml")
    summary(fit.ml) # now prints a bit more than simple 'fit.ml'
    ## ... and what's the log likelihood (in two different ways):
    (ll. <- logLik(fit.ml))
    stopifnot(all.equal(as.numeric(ll.),
                loglikCopula(coef(fit.ml), u=x, copula=gumbel.cop)))

So, why do we need to use pseudo-observation for inversion Kendall's tau and log likelihood functions but we cannot do that for MLE? any idea please?


text:
Q: How can I compare two values in angularjs in HTMl How can I compare two scope values using angularjs in HTML only?
for example:

 show if equals

I want this to cover certain scanrios

A: You are assigning something this way...
To check for equality you need == or ===, but 3 should be used as Doug says -

"If there is every anything that causes unwanted effects and can be
  solved by something else, use the something else..."

Ok maybe he didnt say that exactly but you get the point....

 show if equals


text:
Q: Node & React - npm start - is running BUT localhost:3000 "cant be reached" (having node version 12 and npm version 6)

*

*Backend: Node.js

*Front: React.js
i cloned repository
cd into the directory
ran

npm install (installing dependencies etc...)
and when i ran
npm start

and i get
[Ben@Mac:~/Desktop/test]$ npm start

> answers-entry-level-exam@1.0.0 start /Users/Ben/Desktop/test
> lerna run start --parallel

lerna notice cli v3.22.1
lerna info Executing command in 1 package: "npm run start"
@ans-exam/server: > @ans-exam/server@1.0.0 start
/Users/Ben/Desktop/test/server
@ans-exam/server: > ts-node-dev index.ts
@ans-exam/server: Using ts-node version 8.5.2, typescript version 3.7.2
@ans-exam/server: server running 3232

*

*which seems like the server is running okay

*but localhost:3000 cant be reached
not opening anything
the first time it did open and there was a MacOS popup on the right side of the screen related to node ( i think that is the issue but cant figure out how to fix)
my package.json:
{
 "name": "answers-entry-level-exam",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
 "b": "npm run bootstrap",
 "bootstrap": "lerna bootstrap",
 "test": "echo \"Error: no test specified\" && exit 1",
 "start": "lerna run start --parallel",
 "postinstall": "npm run bootstrap"
},
 "author": "",
 "license": "ISC",
 "devDependencies": {
 "lerna": "^3.22.1"
}
}

Thanks!

A: I cloned again the repo and it fixed that
Cheers to all those who tried to help :)

A: Try localhost:3232. I see in your output server running 3232


text:
Q: Slow single connection internetspeed So my problem is that my downloads only seem to use all available download speed if they are multi connected to the file server,
if i download a file with a single connection i only get a very low download rate, doesn't matter which server.
Multi connection speed test:

*

*https://i.imgur.com/D2Mv05h.png,

*https://i.imgur.com/FK8CgUx.png
Single connection speed test:

*

*https://i.imgur.com/Eoq9xzB.png

*https://i.imgur.com/B9dJGbZ.png
You can see that i get like 10 times the speed if i try to download the Nvida driver with more then one connection via jdownloader.
A technician was already here but he was not competently and never heard of single and multi connection so he could not find any error and said that's a problem of my PC.
I tried different Browsers and resetting my network settings
I am using Realtek PCIe GBE Family Controller and i had no such problem with my former internet provider.
If you have any suggestions i would be very thankful.
Edit : I tried to download the Nvida Drivers on Ubuntu 18.04 and now i having normal speed like 400 Mbits or higher. So the problem is somehow Windows related.
Edit2 : I am using Windows 10 updated to the latest version
Edit 3: I fixed it myself i somehow had "autotuninglevel=disable"
I changed it to "autotuninglevel=normal" with "netsh int tcp set global autotuninglevel=normal" and now everything is normal again.
Thanks for your help anyway


text:
Q: How can I inject an instance into the current scope? I would like to do something like the following:
public class LightInjectTests
{
    [Fact]
    public void CanInjectItemIntoScope()
    {
        var container = new ServiceContainer();
        container.Register<IService, Service>(new PerScopeLifetime());

        var txId = Guid.NewGuid();
        var context = new Context(txId);

        using (var scope = container.BeginScope())
        {
            scope.Inject<IContext>(context);

            var service = scope.GetInstance<IService>();

            service.Context.Should().BeSameAs(context);
        }
    }

    interface IContext { }
    class Context : IContext
    {
        public Context(Guid txId) => TxId = txId;

        public Guid TxId { get; }
    }

    interface IService
    {
        IContext Context { get; }
    }
    class Service : IService
    {
        public Service(IContext context) => Context = context;

        public IContext Context { get; }
    }

}

Is this possible? How would I go about it?


text:
Q: What is the purpose of an arrow "->" in OCaml I've been learning OCaml recently and as of now it would seem an arrow is used by the compiler to signify what the next type would be. For instance, int -> int -> <fun> an integer which returns an integer, which returns a function.
However, I was wondering if I can use it natively in OCaml code. In addition, if anyone would happen to know the appropriate name for it. Thank you.

A: The operator is usually called type arrow where T1 -> T2 represents functions from type T1 to type T2. For instance, the type of + is int -> (int -> int) because it takes two integers and returns another one.
The way -> is defined, a function always takes one argument and returns only one element. A function with multiple parameters can be translated into a sequence of unary functions. We can interpret 1 + 2 as creating a +1 increment function (you can create it by evaluating (+) 1 in the OCaml command line) to the number 2. This technique is called Currying or Partial Evaluation.
Let's have a look at OCaml's output when evaluating a term :
# 1 + 2;;
- : int = 3

# (+) 1 ;;
- : int -> int = <fun>

The term1+2 is of type integer and has a value of 3 and the term (+) 1 is a function from integers to integers. But since the latter is a function, OCaml cannot print a single value. As a placeholder, it just prints <fun>, but the type is left of the =.
You can define your own functions with the fun keyword:
# (fun x -> x ^ "abc");;
- : bytes -> bytes = <fun>

This is the function which appends "abc" to a given string x. Let's take the syntax apart: fun x -> term means that we define a function with argument x and this x can now appear within term. Sometimes we would like to give function names, then we use the let construction:
# let append_abc = (fun x -> x ^ "abc") ;;
val append_abc : bytes -> bytes = <fun>

Because the let f = fun x -> ... is a bit cumbersome, you can also write:
let append_abc x = x ^ "abc" ;;
val append_abc : bytes -> bytes = <fun>

In any case, you can use your new function as follows:
# append_abc "now comes:" ;;
- : bytes = "now comes:abc"

The variable x is replaced by "now comes:" and we obtain the expression:
"now comes:" ^ "abc"

which evaluates to "now comes:abc".
@Charlie Parker asked about the arrow in type declarations. The statement
type 'a pp = Format.formatter -> 'a -> unit

introduces a synonym pp for the type Format.formatter -> 'a -> unit. The rule for the arrow there is the same as above: a function of type 'a pp takes a formatter, a value of arbitrary type 'a and returns () (the only value of unit type)
For example, the following function is of type Format.formatter -> int -> unit (the %d enforces the type variable 'a to become int):
utop # let pp_int fmt x = Format.fprintf fmt "abc %d" x;;
val pp_int : formatter -> int -> unit = <fun>

Unfortunately the toplevel does not infer int pp as a type so we don't immediately notice(*). We can still introduce a new variable with a type annotation that we can see what's going on:
utop # let x : int pp = pp_int ;;
val x : int pp = <fun>
utop # let y : string pp = pp_int ;;
Error: This expression has type formatter -> int -> unit
       but an expression was expected of type
         string pp = formatter -> string -> unit
       Type int is not compatible with type string

The first declaration is fine because the type annotation agrees with the type inferred by OCaml. The second one is in conflict with the inferred type ('a' can not be both int and string at the same time).
Just a remark: type can also be used with records and algebraic data types to create new types (instead of synonyms). But the type arrow keeps its meaning as a function.
(*) Imagine having multiple synonymes, which one should the toplevel show? Therefore synonyms are usually expanded.

A: The given answer doesn't work for ADTs, GADTs, for that see: In OCaml, a variant declaring its tags with a colon
e.g.
type 'l generic_argument =
| GenArg : ('a, 'l) abstract_argument_type * 'a -> 'l generic_argument


text:
Q: Mac won't startup I just bought an macbook pro several weeks ago, it should be Mac OS X Lion, 10.8 I guess. This morning, after I press the power button, it keeps staying at a grey screen with an apple logo and a spinning progress disk, and refused to log in, I've been waiting for a long time. I forced to shut it down and use shift key and press power button again, it did not work, and I shut down again and with option key pressed and I start up again, and it did not work.
What should I do? Thanks

A: The first step is to narrow down which sequence your Mac is failing.

*

*Intel-based Mac: Startup sequence and error codes, symbols - HT2674
Sadly, that article links to an old archived version of how to troubleshoot startup issues. You'll want to start on Recovery boot to see if you can fix this hang or need to perhaps reinstall the OS.

*

*OS X: About OS X Recovery - HT4718

*http://www.apple.com/osx/recovery/
In your case, the Apple logo and spinning gear means that the kernel was found but didn't finish setting up all the system resources. You could re-boot the Mac in verbose mode (hold Command-V at the start chime) to see exactly which part of the kernel /system is not progressing. You also will want to disconnect all peripherals just in case it's an external dependency failing. Usually, this step fails due to a hardware problem or the system needing a clean erase and reinstall (which you can do in recovery using Disk Utility to erase your drive and then re-download Mountain Lion).


text:
Q: Accessing SharedPreferences before displaying the first activity? In my application, I'd like to access SharedPreferences before displaying the first Activity (this should be done to determine whether the user is "logged in" or not, and then either display the login screen or the main screen). Can this be achieved? Or do I have to make a short splash screen to cover up the clutter?

A: I would suggest something like this:
Make a SplashScreen Activity and test there if the user is logged in and then decide which Activity to show. If you just check the SharedPreferences you can also display just a black View, it will display such a short time, the user won't notice.
You can do it also in your fist Activities' onCreate Method before setContentView and then decide which View to show.

A: Just access SharedPreferences inside onCreate() method of Login activity. Check if the user has logged in. If yes, go to Main activity. If not, then we already are in Login page. In this case when the user logs in, set the "loggenIn" to True in SharedPreferences.
SharedPreferences sp =  referenceManager.getDefaultSharedPreferences(getApplicationContext());

if(sp.getBoolean("loggedIn",false)){  //if the user is logged in
        Intent intent = new Intent(Login.this, Main.class); // go to the Main page
        Login.this.startActivity(intent);
        }

A:
In my application, I'd like to access SharedPreferences before displaying the first Activity (this should be done to determine whether the user is "logged in" or not, and then either display the login screen or the main screen). Can this be achieved?

Well, not really, since the way a user enters your app is via some "main" activity, the user necessarily has to start something before you can do anything.

Or do I have to make a short splash screen to cover up the clutter?

You have 3 options:

*

*Splash Screen as you suggested: detect login state, open login or main activity, finish yourself.

*MainActivity: check if logged in, if not, open LoginActivity and check result. If user logged in continue, if not exit or otherwise handle failure.

*Log in activity: check if logged in, if so, open Main and finish yourself.

Personally I would choose option (3) since a log in activity would be doing this "redirect on log in" logic anyway and means you don't need to have the splash screen or clutter main with  login logic checks. But follow your heart.
Hope that helps!


text:
Q: Inheritance not working as tutorial. what is the problem? I'm studying 'inheritance' in Pycharm.
I just followed tutorial. And it doesn't work. What's the problem
##Chef.py##
class Chef:

    def make_chicken(self):
        print("The chef makes a chicken")

    def make_salad(self):
        print("The chef makes a salad")

    def make_special_dish(self):
        print("The chef makes bbq ribs")

##another.py##
from Chef import Chef

class another(Chef):

##app.py##
from another import another
a = another()

a.make_salad()

run>>>
error message :
Traceback (most recent call last):
  File "C:/Users/NEWS1/PycharmProjects/exc/app.py", line 1, in <module>
    from another import another
  File "C:\Users\NEWS1\PycharmProjects\exc\another.py", line 9

    ^
SyntaxError: unexpected EOF while parsing

Process finished with exit code 1

What is the problem....

A: The issue is in your 'another' class, there's nothing following the colon. You can either add methods to the class or just a 'pass' like so
##another.py##
from Chef import Chef

class another(Chef):
    # other content
    pass


text:
Q: Excel CSV export encoding According to my tests, Excel on Mac, when asked to save data as CSV file, uses MacRoman encoding. My questions are:

*

*Does it always happen or there is some setting that controls it?

*If there's a setting, is there a way to make it save as UTF-8? If not, is there a way to export Excel file with characters not in MacRoman preserving these characters?

A: I have found a blog post which outlines an Applescript solution to a similar problem. I've adapted it to your needs. Note that I haven't done any proper quoting of cell values or anything, it will need some tweaking to be more robust. It's also not the fastest solution in my minimal testing… but it's a start.
The key is write X to openFile as «class utf8»
tell application "Microsoft Excel"
    activate

    set outFile to (path of active workbook)
    set fileName to (name of active workbook)
    set outFile to (outFile & ":" & fileName & ".csv")
    set openFile to open for access file outFile with write permission
    set eof openFile to 0

    set lastCol to count of columns of used range of active sheet
    set lastRow to count of rows of used range of active sheet

    repeat with r from 1 to lastRow
        set rowStr to (value of cell r of column 1 of active sheet)
        repeat with c from 2 to lastCol
            set cellVal to (value of cell r of column c of active sheet)
            set rowStr to rowStr & "," & cellVal
        end repeat
        write rowStr & return to openFile as «class utf8»
    end repeat
    close access openFile
end tell

A: Having done a fair amount of research on this I think I can safely say that you can't change the export encoding. However what you could do is add a step to your export procedure whereby after saving the csv to disk you could open it in a text editor (I used Coda but quite a few others will do this) and use that to then save it out using another encoding.

A: Why not just simply open the created file in TextEdit and then use cmd+shift+S to save a duplicate and then choose from dropdownlist UTF-8?

The big advantage is that you do not have to know explicit the encoding created by Excel like in method proposed by Bart. For my language (polsih) it was not Macroman, but some variation of it.

A: I found the easiest thing to do was to just let excel export to csv in its own dumb way, then open up a terminal and do the following:
iconv -t UTF8 -f MACROMAN < file.csv > file-utf8.csv

A: Simply use an editor like "Editra"
- Open the csv-file
- Change the encoding, e.g. to UTF-8, by klicking the encoding-type in the status bar of editor window
- Save the file again (it is now UTF-8)
- Done :o)

A: Use Open Office to save the csv file. There you can choose the encoding.


text:
Q: Extra text shown on overflow: hidden I'm keeping the main content area of the webpage small, so that footer navigation can be seen "above the fold". This is done by javascript setting the main content <div> thus:
sec.style.height = '265px';
sec.style.overflow = 'hidden';

And then using javascript to insert a button to change the style back to normal:
sec.style.height = 'auto';

The problem is that the cut-off point of 265px (dictated by the size of an image which I don't want to hide) doesn't quite match the gap between lines of text. This means that there the tops of tall letters show as funny little marks. Is there any way to hide text which is partially showing in a <div style="overflow: hidden;">?
Screenshot http://timothy.green.name/Temp/overflow.jpg
Edit to add: Full javascript
var overflow = {
    hide: function() {
        var sec = app.get('content_section');
        sec.style.height = '263px';
        sec.style.overflow = 'hidden';
        overflow.toggle(false);
    },
    toggle: function(value) {
        var cnt = app.get('toggle_control');
        if (value) {
            var func = 'hide';
            cnt.innerHTML = 'Close « ';
        } else {
            var func = 'show';
            cnt.innerHTML = 'More » ';
        }
        cnt.onclick = function() {eval('overflow.' + func + '();'); return false;};
        cnt.style.cursor = 'pointer';
        cnt.style.fontWeight = 'normal';
        cnt.style.margin = '0 0 0 857px';
    },
    show: function() {
        var sec = app.get('content_section');
        sec.style.height = 'auto';
        overflow.toggle(true);
    }
}

if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', overflow.hide, false);
} else {
    window.onload = function() {return overflow.hide();};
}

A: You could apply a semi-transparent gradient above the "More »" bar, so it looks like the text is fading out, making the cut bottoms less of a problem.
example http://img687.imageshack.us/img687/7564/sitametsit.png

A: No - this isn't really possible. I do question your decision to keep the footer navigation above the fold, though. The fold really isn't important as once thought - I don't feel like looking up the articles, but there is plenty of research on that. And besides, your primary navigation shouldn't be in your footer.

A: In order to do that you need to:

*

*Find out the height in pixels of a line

*Have all lines of the same height

For #1, setting a line-height in pixels may do the trick (I haven't tested it) but it can affect your layout in monitors with different DPI settings (you set font sizes in relative units, don't you?). Otherwise, you can render a dummy DOM node with two lines and read its height from its computed style.
For #2, I'm unsure. Having no pictures, subscripts or superscripts is a good beginning.
Whatever, I'm pretty sure it's not worth the effort. Users are not as smart as developers think but they aren't as dumb as usability experts believe.


text:
Q: Display all portfolio items with a button in javascript I am building a portfolio website.  Within the portfolio items I want to display 6 items by default and click a button (Show More) to show the remaining items, in which the text of the button should change to (Show Less). The items should return to its original state when the (Show Less) button is clicked again. I was able to sort each item by category filter but displaying all items is the problem. Check my code snippet below.

// PORFOLIO CATEGORIES
$('.port_cat').on('click', function() {
  $('.port_cat').removeClass('active-port');
  $(this).addClass('active-port');
});

// PORTFOLIO FILTER
$(".port_cat").click(function() {
  var value = $(this).attr('data-filter');
  if (value == "all") {
    $('.filter').show('1000');
  } else {
    $(".filter").not('.' + value).hide('3000');
    $('.filter').filter('.' + value).show('3000');
  }
});
.project {
  position: relative;
  overflow: hidden;
}

.project .overlay {
  display: inline-block;
  text-align: center;
  position: absolute;
  z-index: 3;
  padding: 10% 8%;
  top: 0;
  left: 0;
  content: "";
  width: 100%;
  height: 100%;
  color: black;
  opacity: 0;
  background: rgba(60, 235, 226, 0.9);
  -webkit-transition: background 0.5s, opacity 0.5s 0.5s;
  -moz-transition: background 0.5s, opacity 0.5s 0.5s;
  -o-transition: background 0.5s, opacity 0.5s 0.5s;
  -ms-transition: background 0.5s, opacity 0.5s 0.5s;
  transition: background 0.5s, opacity 0.5s 0.5s;
}

.project .overlay:hover {
  opacity: 1;
  -webkit-transition: background 0.25s, opacity 0.25s 0s;
  -moz-transition: background 0.25s, opacity 0.25s 0s;
  -o-transition: background 0.25s, opacity 0.25s 0s;
  -ms-transition: background 0.25s, opacity 0.25s 0s;
  transition: background 0.25s, opacity 0.25s 0s;
  transition-delay: 0;
  -webkit-transition-delay: 0;
}

.project .overlay:hover .content {
  opacity: 1;
  opacity: 0.2s;
  filter: alpha(opacity=20s);
}

.project .overlay:hover h3 {
  opacity: 1;
  -moz-transition: opacity 0.3s, -moz-transform 0.3s;
  -webkit-transition: opacity 0.3s, -webkit-transform 0.3s;
  transition: opacity 0.3s, transform 0.3s;
  -webkit-transform: translateY(0px);
  -moz-transform: translateY(0px);
  -ms-transform: translateY(0px);
  -o-transform: translateY(0px);
  transform: translateY(0px);
}

.project .overlay:hover p {
  opacity: 1;
  -webkit-transform: translateY(0px);
  -moz-transform: translateY(0px);
  -ms-transform: translateY(0px);
  -o-transform: translateY(0px);
  transform: translateY(0px);
}

.project .content {
  position: relative;
  opacity: 0;
  text-align: center;
  vertical-align: middle;
  display: inline-block;
  width: 100%;
  min-height: 165px;
  word-break: break;
  opacity: 0.5s;
  filter: alpha(opacity=50s);
  -webkit-perspective: 300px;
  -moz-perspective: 300px;
  -o-perspective: 300px;
  -ms-perspective: 300px;
  perspective: 300px;
}

.project h3 {
  opacity: 0;
  font-weight: 400;
  -webkit-transform: translateY(-20px);
  -moz-transform: translateY(-20px);
  -ms-transform: translateY(-20px);
  -o-transform: translateY(-20px);
  transform: translateY(-20px);
  -moz-transition: opacity 0.2s, -moz-transform 0.2s;
  -webkit-transition: opacity 0.2s, -webkit-transform 0.2s;
  transition: opacity 0.2s, transform 0.2s;
}

.project p {
  font-size: 1em;
  color: black;
  opacity: 0;
  -webkit-transform: translateY(-20px);
  -moz-transform: translateY(-20px);
  -ms-transform: translateY(-20px);
  -o-transform: translateY(-20px);
  transform: translateY(-20px);
  -moz-transition: background-color 0.5s, opacity 0.5s 0.15s, -moz-transform 0.5s 0.15s;
  -webkit-transition: background-color 0.5s, opacity 0.5s 0.15s, -webkit-transform 0.5s 0.15s;
  transition: background-color 0.5s, opacity 0.5s 0.15s, transform 0.5s 0.15s;
}

.label-danger {
  width: 400px;
}

STUFFS I'VE WORKED ON

Stuffs i am able to do that define my strenght and weakness

ALL

WEBSITE

GRAPHICS

UI DESIGN

APPLICATION

THIS IS A SAMPLE HEADING

Sample project description goes in here

            Web Design

THIS IS A SAMPLE HEADING

Sample project description goes in here

            Web Design

THIS IS A SAMPLE HEADING

Sample project description goes in here

            Web Design

THIS IS A SAMPLE HEADING

Sample project description goes in here

            Web Design

THIS IS A SAMPLE HEADING

Sample project description goes in here

            Web Design

THIS IS A SAMPLE HEADING

Sample project description goes in here

            Web Design

THIS IS A SAMPLE HEADING

Sample project description goes in here

            Web Design

THIS IS A SAMPLE HEADING

Sample project description goes in here

            Web Design

THIS IS A SAMPLE HEADING

Sample project description goes in here

            Web Design

  View All Items

A: I think jQuery could be a nice way to go here:
https://www.w3schools.com/jquery/eff_slidedown.asp
HTML:

This is a paragraph.

<button class="btn1">Slide up</button>
<button class="btn2">Slide down</button>

jQuery:


text:
Q: Prevent window.open from refreshing parent window When I call window.open the parent window refreshes. I haven't seen anything about how to prevent this from occurring. Any help would be appreciated.
left = Number((screen.width/2)-(730/2)),
top = Number((screen.height/2)-(450/2));

var windowFeatures = 'location=0,menubar=0,resizable=0,scrollbars=0,status=0,width=700,height=500,top='+top+',left='+left;
    window.open('access-modal.html', '', windowFeatures);

win.moveTo(left, top);

A: While there were problems with my post after editing. The ultimate solution was preventing the default action.
$('.button').on('click', function(e) {

    e.preventDefault();

        left = Number((screen.width/2)-(730/2)),
        top = Number((screen.height/2)-(450/2));

        var windowFeatures = 'channelmode=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=0,status=0,width=700,height=500,top='+top+',left='+left;
            win = window.open('access-modal.html?env=' + Data.currentOauth + '&url=' + Data.currentAddr, '', windowFeatures);

        win.moveTo(left, top);
        win.focus();

    }

});

A: I am not sure if it is your edit or not.. I know there is an error on win.moveTo(left, top). win is not defined.. the following code is working for me.
<script language="javascript" type="text/javascript">
            function windowOpen() {
                left = Number((screen.width / 2) - (730 / 2)),
                top = Number((screen.height / 2) - (450 / 2));

                var windowFeatures = 'location=0,menubar=0,resizable=0,scrollbars=0,status=0,width=700,height=500,top=' + top + ',left=' + left;
                var win = window.open('access-model.htm', '', windowFeatures);

                win.moveTo(left, top);
            }
        </script>


text:
Q: How to hide feedback button in the toolbar? How to hide the feedback button in the Aviary toolbar using Objective C?

A: I'm afraid that the short answer will be "Purchase a white label package for $275/month".
This link clearly shows that "White label" option doesn't have a feedback button (along with any Aviary branding): http://developers.aviary.com/upgrades
Another option will be disassembling the Aviary code and removing feedback button by hand (which is not a trivial thing to do and you still wouldn't be able to publish the app on the App Store).


text:
Q: Right align Ionic datetime picker's date on the label Do you have any clue to right align Ionic date picker. I have tried with float-right and float-end. But no luck :(
Note: I need to right align the final date on the label.
You can play with stackblitz
    <ion-list>
        <ion-item>
            <ion-label fixed>Compl. Date</ion-label>
            <ion-datetime displayFormat="D MMM, YYYY" [(ngModel)]="completionDate" float-end></ion-datetime>
        </ion-item>
    </ion-list>

A: The only possible way to maintain clickability of the label while aligning the datetime on the right (without additional custom code) is to have the date-time take up full 100% width and then text-align right as shown below.
<ion-list>
    <ion-item>
        <ion-label fixed>Compl. Date</ion-label>
        <ion-datetime  style="width: 100%; text-align: right;"displayFormat="D MMM, YYYY" [(ngModel)]="completionDate"></ion-datetime>
    </ion-item>
</ion-list>

You could also use position: absolute; right: 0; instead of the full width + text-align, but then you'd have to create a custom click function for the label to activate the date picker modal.

A: I think i have got it
    <ion-list>
    <ion-item>
        <ion-label style=" text-align: right;">Compl. Date</ion-label>
        <ion-datetime displayFormat="D MMM, YYYY" [(ngModel)]="completionDate" float-end></ion-datetime>
    </ion-item>
</ion-list>


text:
Q: Algorithm that partitions landscape into connected components classified as hillsides and valleys I am considering the following problem:
Given an nxm array h that contains height data for given points in the plane. Does there exist an algorithm that partitions the points in the plane to connected areas that one could classify by their height profile, i.e. does a point belong to a hillside or a valley?
I completely understand that this question does not have a unique answer as there is no hard definition of a hillside or a valley but I think roughly speaking any human would be able to make such a decision and I wonder if there is an algorithm that does anything close to it?

A: Iterate through the points, and compute the slope between the current point and the next point. Then, iterate over these slopes, and find all points of inflection. To do this-  compute a new "slope'" / change between each pair of adjacent slopes (like we did with the points themselves), and mark the ones that change the current sign (positive/negative). The slope shared between the sign change contains our POI, so one endpoint is a hill, the other a valley. Just look at the sign of the slope' to figure out which (positive is a valley, since the slope is increasing / curving upwards, negative is a hill).


text:
Q: Combining rows dynamically in sql I know there are similarly worded questions but I can't seem to find one that fits my specific case. I have something that more or less looks like this:
GUID  | FIRST_NAME | LAST_NAME | LOAN_NUMBER | LOAN_AMOUNT
---------------------------------------------------------
0001  | FIRST      | LAST      | 01          | 1000
0001  | FIRST      | LAST      | 02          | 1500
0002  | SECOND     | PERSON    | 03          | 1250
0002  | SECOND     | PERSON    | 04          | 2000
0002  | SECOND     | PERSON    | 05          | 1250

etc (any person can have any number of different loans for different amounts)...
and I need it to look like this:
GUID | FIRST_NAME | LAST_NAME | LOAN_AMOUNT1 | LOAN_AMOUNT2 | LOAN_AMOUNT3
--------------------------------------------------------------------------
0001 | FIRST      | LAST      | 1000         | 1500         |
0002 | SECOND     | PERSON    | 1250         | 2000         | 1250

this sql result is going to end up getting passed into a C# application in any case, so if this is more easily done in c# then I may go that route instead.

A: You can use row_number() to rank each person's loans, and then pivot with conditional aggregation:
select
    guid,
    first_name,
    last_name,
    max(case when rn = 1 then loan_amount end) loan_amount1,
    max(case when rn = 2 then loan_amount end) loan_amount2,
    max(case when rn = 3 then loan_amount end) loan_amount3
from (
    select
        t.*,
        row_number() over(partition by guid order by loan_number) rn
    from mytable t
) t
group by guid, first_name, last_name

If you need to handle more than 3 loans per person, you can extend the select clause with more conditional expressions.


text:
Q: How to solve this Sylvester-equation-like matrix system? I'd like to find solutions for $T$ and $\alpha$ in
$$\forall i: TA_i=\sum_{j=1}^{\tilde b}\alpha_{ij}\tilde A_jT$$
where $A_i$ are $b$ given matrices of shape $n\times n$, and $\tilde A_j$ are $\tilde b$ given matrices of shape $\tilde n\times\tilde n$. The unknowns are the matrix $T$ of shape $\tilde n\times n$ and the scalar coefficients $\alpha_{ij}$. The matrices $A_i$ and $\tilde A_j$ happen to have zero trace. Essentially this is solving $TA=\tilde A T$ where $A$ and $\tilde A$ are bases in form of a matrix.
How can I solve this for both unknowns?
If I knew $T$ I know how to use matrix vectorization to solve it for $\alpha_{ij}$. However, I don't know how to guess the right $T$ or which conditions it should satisfy.


text:
Q: Visual Studio 2022 Crashing when adding a Database or Data Connection I started a new Windows Forms App and am trying to add a SQL Server database connection to the app. I'm using the following method: DataSources Window -> Add New Data Source -> Database -> Dataset -> New Connection
Each time I start to enter the Server Name for the new connection, Visual Studio simply freezes and crashes.
Here's a photo of where the crash keeps happening.
[]
Does anyone know what is causing this or how  to fix it?
I'm rolling back to the 2019 ver. to see if that helps at all.
Seems absurd that I wouldn't be able to add a database connection to a project. I've done it so many times before.
UPDATE: I tried adding a connection string through the application settings. It crashed as soon as I chose Connection String...
[]


text:
Q: Move marker without clearing GoogleMap I added a TileOverlay and some Markers into a map and I want to move a specific Marker on a map without using googleMap.clear() because TileOverlay will get cleared too. Is it possible to do it?
public void onPositionChanged(LatLng newPosition) {
    myMarker.position(newPosition);
    // myMarker should be updated on a map
}

A: From the code that you have posted. I can see that you only need 1 marker at a time (or you are adding more? doesn't matter). You will have to store the reference to the marker some where your method can access. Then you could just create a dummy marker(or check if the marker doesn't exists, then create one and save the reference to it) and move it using dummy.setPosition(LatLng latlng).
Here is an example code:
private Marker marker;
public void onPositionChanged(LatLng newPosition) {
    if (marker == null) {
        marker = map.addMarker(new MarkerOptions().position(newPostion));
    } else {
        marker.setPostion(newPosition);
    }
}

Reference https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/model/Marker

A: Don't Clear Just add new Marker to map
    public void AddMarkerAndSetCameraPosition(LatLng latlng)
    {
        //GMap.Clear();
        CurrentMarker = GMap.AddMarker(new MarkerOptions()
                                                .SetPosition(latlng));
        GMap.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(latlng, 15f));
        GMap.CameraPosition.Zoom = 15f;
        CurrentMarker.ShowInfoWindow();

    }


text:
Q: How can I check efficiently check variables for a particular value in R and flag rows containing it? I want to create a variable that flags whether one or more of multiple variables has a particular value.
week  Mon  Tues  Weds  Thurs  Fri  Sat
1     jon  jon   jon   jon    mary mary
2     jane jane  jane  jane   jane jane
3     mary mary  mary  mary   mary jane

I want to create a binary variable that flags for each week whether Mon, Weds, or Sat of that week == "jon" or "mary" Is there a way to do this without creating a long ifelse statement that checks each variable individually?
week  Mon  Tues  Weds  Thurs  Fri  Sat  flag
1     jon  jon   jon   jon    mary mary 1
2     jane jane  jane  jane   jane jane 0
3     mary mary  mary  mary   mary jane 1

I tried
df %>%
  rowwise() %>%
  mutate(flag = +any(c_across(Mon, Weds, Sat)
  %in% ("jon", "mary")) %>%
  ungroup()

but I get an error
Error: Problem with `mutate()` input `flag`.
x unused arguments (Mon, Weds, Sat)
i Input `flag` is `+...`.
i The error occurred in row 1.

A: df %>%
  mutate(flag = colSums(apply(cbind(Mon, Weds, Sat), 1, `%in%`, c("jon", "mary"))) > 0)
#   week  Mon Tues Weds Thurs  Fri  Sat  flag
# 1    1  jon  jon  jon   jon mary mary  TRUE
# 2    2 jane jane jane  jane jane jane FALSE
# 3    3 mary mary mary  mary mary jane  TRUE

I think the problem with across is that it's trying to do something to each column, not a summary of sorts of all of them. Let's try purrr::pmap insteadL
library(purrr)
df %>%
  mutate(flag = pmap(list(Mon, Weds, Sat),
                     ~ +any(unlist(...) %in% c("jon", "mary"))))
#   week  Mon Tues Weds Thurs  Fri  Sat flag
# 1    1  jon  jon  jon   jon mary mary    1
# 2    2 jane jane jane  jane jane jane    0
# 3    3 mary mary mary  mary mary jane    1

A third (using your request for c_across):
df %>%
  rowwise() %>%
  mutate(flag = +any(c_across(c(Mon, Weds, Sat)) %in% c("jon", "mary"))) %>%
  ungroup()
# # A tibble: 3 x 8
#    week Mon   Tues  Weds  Thurs Fri   Sat    flag
#   <int> <chr> <chr> <chr> <chr> <chr> <chr> <int>
# 1     1 jon   jon   jon   jon   mary  mary      1
# 2     2 jane  jane  jane  jane  jane  jane      0
# 3     3 mary  mary  mary  mary  mary  jane      1

A: Instead of the rowwise or looping over the rows, we can make it more efficient if we loop over the columns with map and reduce it
library(purrr)
library(dplyr)
df %>%
     mutate(flag = map(select(., Mon, Weds, Sat), `%in%`, c("jon", "mary")) %>%
          reduce(`|`) %>% `+`)
#  week  Mon Tues Weds Thurs  Fri  Sat flag
#1    1  jon  jon  jon   jon mary mary    1
#2    2 jane jane jane  jane jane jane    0
#3    3 mary mary mary  mary mary jane    1

A corresponding option in base R is lapply/Reduce
df$flag <- +(Reduce(`|`, lapply(df[c('Mon', 'Weds', 'Sat')],
          `%in%`, c("jon", "mary"))))

data
df <- structure(list(week = 1:3, Mon = c("jon", "jane", "mary"), Tues = c("jon",
"jane", "mary"), Weds = c("jon", "jane", "mary"), Thurs = c("jon",
"jane", "mary"), Fri = c("mary", "jane", "mary"), Sat = c("mary",
"jane", "jane")), class = "data.frame", row.names = c(NA, -3L
))

A: Here is another base R option using rowSums + Reduce
df$flag <- +(rowSums(
  Reduce(
    `+`,
    lapply(
      c("jon", "mary"),
      `==`,
      df[c("Mon", "Weds", "Sat")]
    )
  )
) > 0)

such that
  week  Mon Tues Weds Thurs  Fri  Sat flag
1    1  jon  jon  jon   jon mary mary    1
2    2 jane jane jane  jane jane jane    0
3    3 mary mary mary  mary mary jane    1


text:
Q: Android FusedLocationProviderClient problem I have been following a tutorial however it is quite old and uses the deprecated googleApiClient. Weirdly though, when I use
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'

It works as should do by displaying the location on the map. I assumed it wouldn't work and when debugging before it wouldn't build.
I have tried to impelement a new way using the updating version whereby the fusedLocationApi isn't included.
Attached are the working version with fusedLocationApi & googleClientApi, and the newer code which builds but isn't showing the location on the map when the app builds.
Maybe there is something missing in the updated code that isn't producing the location to show on the map??
I'm new to Android to any help appreciated :)
Old Working Version - https://pastebin.com/VG4AUJrv
Updated Not Working Version - https://pastebin.com/xa674c5f

A:  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
            {
                // add here
                fusedLocationProviderClient?.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
                mMap.isMyLocationEnabled = true
            }else
            {
                checkLocationPermission()
            }
        }

Your problem is here.
When you grant an application permission it will not perform a location search so you need to write a method to do it if you have granted it permission.


text:
Q: Zsh completion case insensitive _multi_parts function I have a script that takes file like arguments (multi part arguments), I am fetching the possible values and putting them in an array called raw and then using
_multi_parts / "(${raw[@]})"

to autocomplete. The problem is that this is case sensitive, how can I make it so that it I type mycommand get fo and press Tab it will autocomplete to mycommand get Foo/ if Foo is one of the things in raw.
The full completion is here for reference:
_mycommand() {
  local curcontext="$curcontext" state line

  _arguments "1: :->command" "*: :->label"

  case $state in
  command)
    _arguments "1: :(add get ls rm)"
  ;;
  *)
    case $words[2] in
      add|get|ls|rm)
        if [ -f ~/.pts ]; then
          IFS=$'\n' read -d '' -r raw <<< "$(mycommand ls)"
          _multi_parts / "(${raw[@]})"
        fi
      ;;
      *)
        _files
      ;;
    esac
  esac
}

_mycommand "$@"

mycommand ls outputs path like names like the following:
Foo/Bar/x
Foo/Bar/y
Derp/z
Placeholder/z

A: Okay I figured it out:
Change lines
IFS=$'\n' read -d '' -r raw <<< "$(mycommand ls)"
_multi_parts / "(${raw[@]})"

To
IFS=$'\n' raw=($(mycommand ls))
_multi_parts -M "m:{[:lower:][:upper:]}={[:upper:][:lower:]}" / raw


text:
Q: Nginx and gzip not working. Where I wrong I using nginx and php-fpm, but can't get gzip to compress anything. Server is Centos 6.5 with compiled nginx, command:--sbin-path=/usr/sbin/nginx --with-http_stub_status_module --conf-path=/etc/nginx/nginx.conf --pid-path=/var/run/nginx.pid --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --user=nginx --with-http_gzip_static_module
Here is nginx.conf:
    include       /etc/nginx/mime.types;
default_type  application/octet-stream;
access_log off;
log_not_found off;
sendfile        on;
tcp_nopush     on;
tcp_nodelay on;
client_body_timeout   30;
client_header_timeout 30;
keepalive_timeout     45;
send_timeout          30;
reset_timedout_connection on;
output_buffers 1 8M;
gzip              on;
gzip_static       on;
gzip_buffers      16 8k;
gzip_comp_level   5;
gzip_http_version 1.1;
gzip_min_length   2;
gzip_types        text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/json application/xml+rss;
gzip_vary         on;
gzip_proxied any;
#gzip_disable "MSIE [1-6]\.(?!.*SV1)";
gzip_disable msie6;
server_names_hash_max_size 1024;
server_names_hash_bucket_size 128;
open_file_cache max=20000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
client_body_buffer_size 1024k;
fastcgi_buffers 64 64k;
include /etc/nginx/conf.d/domains/*.conf;

and here is domain.conf:
    server {
    listen xx.xx.xx.xx:80;
    server_name xxxxxxxx.com;
    if ( $host ~* ^(?!(www|cdn)\.) ) {
       rewrite .* $scheme://www.$host$request_uri permanent;
    }
    index index.php;
    charset utf-8;.
    if ($request_uri ~* "^(.*(?<!expert)/)index\.php$") {
        return 301 $1;
    }
    root /home/ftpaccess/xxxxxxx/www;
    location ~* ^.+\.(txt|js|css|doc|xls|pdf|ppt|rtf|jpg|jpeg|gif|bmp|ico|zip|tgz|gz|bz2|exe|tar|wav|avi|flv|mpg|mpeg|mp4|mp3|png)$ {
        expires 720h;
        add_header Pragma public;
        add_header Cache-Control "public";
    }
    location ~ /\.ht {
        deny all;
    }
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt { access_log off; log_not_found off; allow all;}
    location = /apple-touch-icon.png { access_log off; log_not_found off; }
    location = /apple-touch-icon-precomposed.png { access_log off; log_not_found off; }
    error_page 404 /404.php;
    include /etc/nginx/conf.d/redirect/xxxxxx.conf;
    location ~ \.php$ {
        include /etc/nginx/php.conf;
        include        /etc/nginx/fastcgi_params;
    }
}

and php.conf:
fastcgi_split_path_info ^(.+\.php)(/.+)$;
try_files $uri =404;
fastcgi_pass   unix:/var/run/php5-fpm.sock;
fastcgi_index  index.php;
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
fastcgi_read_timeout 300;

curl -I -H 'Accept-Encoding: gzip,deflate' http://www.xxxxxx.com  response:
HTTP/1.1 200 OK
Server: nginx/1.6.2
Date: Mon, 03 Nov 2014 22:14:23 GMT
Content-Type: text/html; charset: iso-8859-1
Connection: keep-alive
Set-Cookie: PHPSESSID=0pi4o2i83gvof758gep5nc01m5; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

curl -I -H 'Accept-Encoding: gzip,deflate' http://www.xxxxxxx.com/js/pop.js response:
HTTP/1.1 200 OK
Server: nginx/1.6.2
Date: Mon, 03 Nov 2014 22:15:21 GMT
Content-Type: application/javascript
Content-Length: 5241
Last-Modified: Mon, 03 Nov 2014 21:21:28 GMT
Connection: keep-alive
Expires: Wed, 03 Dec 2014 22:15:21 GMT
Cache-Control: max-age=2592000
Pragma: public
Cache-Control: public
Accept-Ranges: bytes

Where I doing wrong and how to fix? Tried almost everything and can't success.

A: Your gzip_types does not include the types that you refer.
As you can see, the following types are covered by your configuration:
text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/json application/xml+rss but you reference both text/javascript and application/javascript.


text:
Q: Avg in sql adds zeros after the number when i use AVG in sql it gets 2.7500 but i only want it to get the first 2 numbers 2.7/5 on the average rating
    $ratesavg =  "SELECT AVG(round(vote_num,1)) AS myAvg FROM post_votes WHERE post_id=$post_id GROUP BY post_id";
$avgrows = mysqli_query($conn, $ratesavg);
while($row = mysqli_fetch_assoc($avgrows)) {
  print_r($row);
  $a = $row['myAvg'];
  echo $a;
}

A: You can format the number as a string or convert it to a decimal/numeric:
select cast(avg(x) as numeric(4, 1))

A: This how it works
$ratesavg =  "SELECT round(AVG(vote_num), 1) AS myAvg FROM post_votes WHERE post_id=$post_id GROUP BY post_id";


text:
Q: SignInManager uses fixed claimTypes while UserManager uses configurable ones. Is it correct? I am looking a bit under the AspNetCore/Identity/UserManager and SignInManager still wondering if I should use this implementation or should I just copy and adapt to whatever i need.
Looking over the SignInManager I noticed something really wierd, and perhaps somebody could help clarify this for me.
The userManager class has the ClaimTypes configurable and the default value for the userId is ClaimTypes.NameIdentifier.
The SignInManager does not use the same approach.

*

*Is there a reason why they are using ClaimTypes.Name in SignInManager to check for the userId?

*Is the implementation of the method in the SignInManager correct? What happens if I decide to change the type of the claim for the name and userid in the UserManager options

Maybe I don't understand but I hope that somebody can explain it to me.
Thanks


text:
Q: Why does `p var if var = 0.zero?` raise an error? I was recently given this as a hard programming question:

What is the output of p var if var = 0.zero?(question mark is part of the code).

My assumption is that first 0.zero? would be evaluated, return true, then var = true, which would set var to true and return true, so p var if true would then print true.
But this is not what happens. Ruby raises an error undefined local variable or method `var' ...
p var if var = 0.zero?
# => NameError: undefined local variable or method `var' for main:Object
from (irb):19
from /usr/bin/irb:11:in `<main>'

p var if var = (0.zero?)
# => true

p var if (var = 0).zero?
# => 0

p var if (var = 0.zero?)
# => true

p var if var = 0
# => (irb):23: warning: found = in conditional, should be == 0

What is going on here?

A: Check out Local Variables and Methods

The local variable is created when the parser encounters the
  assignment, not when the assignment occurs


text:
Q: How to read the battery level in Ubuntu? I've searched for a while on how to do this without any special library or anything, and it took a while to find something that's working properly.
It's possible to use
/sys/class/power_supply/BAT0/subsystem/BAT0/charge_now
/sys/class/power_supply/BAT0/subsystem/BAT0/charge_full

I was wondering, is there a better way to get the battery status using C/C++ in Ubuntu 18.04?

A: In case this is never answered.. this is my solution:
#define PATH_BATT_CHARGE_NOW "/sys/class/power_supply/BAT0/subsystem/BAT0/charge_now"
#define PATH_BATT_CHARGE_FULL "/sys/class/power_supply/BAT0/subsystem/BAT0/charge_full"

int getBattState(void)
    {
        int chargedPercent = 0;

        FILE *battChargeNow;
        FILE *battChargeFull;
        long unsigned int battMax_mAh = 0;
        long unsigned int battRemain_mAh = 0;

        if (NULL == (battChargeNow = fopen(PATH_BATT_CHARGE_NOW, "r")))
        {
            fclose(battChargeNow);
            return -1;
        }
        if (NULL == (battChargeFull = fopen(PATH_BATT_CHARGE_FULL, "r")))
        {
            fclose(battChargeNow);
            fclose(battChargeFull);
            return -1;
        }

        fscanf((FILE *)battChargeFull, "%lu", &battMax_mAh);
        fscanf((FILE *)battChargeNow, "%lu", &battRemain_mAh);

        chargedPercent = 100.00 * ((float)battRemain_mAh / (float)battMax_mAh);
        return chargedPercent;
    }


text:
Q: Uncaught TypeError: d3.arc(...).outerRadius(...).innerRadius(...).text is not a function I've encountered an error while coding my chart on my "card" bootstrap.
The thing is I only want the label to show on my pie chart but the problem is console on google chrome says "Uncaught TypeError: d3.arc(...).outerRadius(...).innerRadius(...).text is not a function"
In which i don't get why.
Below is my code for the pie-chart:
var data = [
    {"platform": "Android", "percentage": 40.11},
    {"platform": "Windows", "percentage": 36.69},
    {"platform": "iOS", "percentage": 13.06}
];

var svgCirWidth = 600, svgCirHeight = 300, radius = Math.min(svgCirWidth, svgCirHeight) / 2;

const pieContainer = d3.select("#pieChart")
.append("svg")
.attr("width", svgCirWidth)
.attr("height", svgCirHeight);

//create group element to hold pie chart

var g = pieContainer.append("g")
.attr("transform", "translate(" + 170 + "," + radius + ")");

var color = d3.scaleOrdinal(d3.schemeCategory10);

var pie = d3.pie().value(function(d){
    return d.percentage;
});

var path = d3.arc()
.outerRadius(radius)
.innerRadius(0);

var arc = g.selectAll("arc")
.data(pie(data))
.enter() //means keeps looping in the data
.append("g");

arc.append("path")
.attr("d", path)
.attr("fill", function(d){
    return color(d.data.percentage);
})

var label = d3.arc()
.outerRadius(radius)
.innerRadius(0)
.text(function(d){
    return d;
});

A: d3.arc returns a path's d attribute. This cannot contain text.
In SVG, text must be enclosed inside <text>.
Since your variable arc is a selection of a g element, you could append <text> to it:
arc.append('text')
     .text(/* ... */)

Edit after receiving a comment that "it still won't work"
Please be specific whenever reporting problems, in order to receive proper help: is there any error message? What is the observed behaviour, and what was the expected one?
Using arc.append('text') seems to work just fine.
Debugging tip
It is often helpful to use console.log as shown below to see what is going on:
arc.append('text')
  .text(function(d){
    console.log('text', d)
    return d;
  })

The code above will show that d is an object, this is why the labels are shown in the page as [object object].
I assume that the desired behaviour is rather to show the platform and percentage values.
Then instead of return d, we know thanks to the console.log output that we should rather use d.data.platform and d.data.percentage:
return d.data.platform + ': ' + d.data.percentage;

Labels placement
Another issue observed is that all labels are overlapping. This is normal, no position has been defined for them.
A quick use of search engine shows us this example, where arc.centroid is used together with text-anchor: middle to position each label in a suitable location.
Solution is illustrated in the snipped below.

var data = [
    {"platform": "Android", "percentage": 40.11},
    {"platform": "Windows", "percentage": 36.69},
    {"platform": "iOS", "percentage": 13.06}
];

var svgCirWidth = 600, svgCirHeight = 300, radius = Math.min(svgCirWidth, svgCirHeight) / 2;

const pieContainer = d3.select("#pieChart")
.append("svg")
.attr("width", svgCirWidth)
.attr("height", svgCirHeight);

//create group element to hold pie chart

var g = pieContainer.append("g")
.attr("transform", "translate(" + 170 + "," + radius + ")");

var color = d3.scaleOrdinal(d3.schemeCategory10);

var pie = d3.pie().value(function(d){
    return d.percentage;
});

var path = d3.arc()
.outerRadius(radius)
.innerRadius(0);

var arc = g.selectAll("arc")
.data(pie(data))
.enter() //means keeps looping in the data
.append("g")

arc.append("path")
.attr("d", path)
.attr("fill", function(d){
    return color(d.data.percentage);
})

arc.append('text')
  .text(function(d){
    return d.data.platform + ': ' + d.data.percentage;
  })
  .attr('transform', function(d){
    return 'translate(' + path.centroid(d) + ')'
  })
  .attr('text-anchor', 'middle')


text:
Q: play http live stream MP3 in iphone Browser? i have successfully transcode RTSP live stream to HTTP live stream (audio MP3) using VLC

this is the url to my new live stream if i stream this url in VLC it works fine
    http://174.60.175.62:8080

Live DEMO
QUESTION
How can i play this http stream in iphone safari
this is what i have tried and didn't work
   <video id="video" src="http://174.60.175.62:8080" autoplay="autoplay">

A: It's MP3 so use HTML5 Audio Element
<audio controls="controls" loop="loop">
    <source src="http://westciv.com/podcasts/youmayknowmypoetry.mp3">
</audio>

Here is all information you needed for HTML5 Audio and Video


text:
Q: IPN simulator error: Cannot GET /webapps/developer/applications/ipn_simulator/ I'm having problems with the IPN simulator here:
https://developer.paypal.com/webapps/developer/applications/ipn_simulator/
Sometimes a page is displayed with the error:
Cannot GET /webapps/developer/applications/ipn_simulator/
Sometimes it displays the page as expected, but on submitting the form the page just reloads. No message that ipn was sent, just as if the page was opened for the first time.
I have used this ipn simulator page before (a few months ago) and it was working fine. I was receiving ipn data, sending it back, and getting the confirmation.
Here is the first part of the ipn handler code. It just saves the ipn data before sending it back to have Paypal verify it. However, this is never executed, since the ipn data is never sent from the simulator. The error:
"Cannot GET /webapps/developer/applications/ipn_simulator/" is displayed when loading the ipn simulator page, before attempting to send anything.
$raw_post_data = file_get_contents('php://input');

// Log initial ipn data, before verification
error_log(date('[Y-m-d H:i e] '). "Pre validation ipn data:  ".PHP_EOL.$raw_post_data. PHP_EOL.PHP_EOL, 3, LOG_FILE);

Update: As of Feb 8 2016, 7:49 pm GMT, it is currently working.
Update: Never mind, it worked once, and quit again with same error as in question title.


text:
Q: Issue with meta tags for children routes, rendered via router-view, not being set on server side TLDR: Pre-rendered views of child-routes are using the parent meta info, but I'd like them to use the meta info defined on the child-route component.
I've got a Nuxt/Vue site set up that has a landing page, /items/index.vue that provides a grid of items, and child-routes set up as children to that landing page in my router.js file. These child-routes are rendered as modals within the /items/index.vue via the nuxt-child or router-view components. The child-route calls a component called /components/ItemsModal.vue which sets the appropriate meta tags (title, og:data, ect)
When I enter the URL for a child route, the meta/head info updates as expected, after an initial flash of the parent /items/index.vue meta info. However, my SEO info is showing the parent meta/head info, and not the updated info that is defined by the child-route component. When I view-source, I see that the pre-rendered delivered page does indeed have the parent info, and not the child-route info, nor any of the content associated with the child-route component.
Anyone have any experience configuring child routes to pre-render with the head info defined in the child-route component? I would expect a child-route to render its associated component before calling it good on the pre-render.
Code below, truncated/modified for clarity.
router.js
{
    path: '/items',
    name: 'item-index',
    component: ItemIndex,
    children: [
      {
        path: ':slug',
        component: ItemModal, // defined as a var earlier in file
        name: 'item-modal'
      }
    ],
    alias: []
  },

/item/index.js
<template lang='pug'>
  ThePage
    ItemGrid
    nuxt-child
</template>

<script>
import ItemGrid from '~/components/ItemGrid'
export default {
components: {
  ItemGrid
}
head() {
  return {
    title: 'Parent Title,
    meta: [{
         hid: 'description',
         name: 'description',
         content: 'Parent description'
    }]
  }
}
</script>

/item/index.js
<template lang='pug'>
  ThePage
    Item
</template>

<script>
import Item from '~/components/Item'
export default {
components: {
  Item
}
head() {
  return {
    title: 'Child Title,
    meta: [{
         hid: 'description',
         name: 'description',
         content: 'Child description'
    }]
  }
}
</script>

A: I neglected to mention that I was using vue-portal to lift the modal up in the DOM, and discovered, by more fully reading the documentation. SSR and Vue-Portal aren't compatible.
What I ended up doing was bypassing the vue-portal on SSR, just using nuxt-child to load the modal, and then triggering the vue-portal implementation on mounted. The SSR meta contact is properly handled through nuxt-child, and the UX is proper on mounted on the client side.


text:
Q: Python parse dirs, remove subdirectory tree I have a long list of directories, with something like this
C:\Users\vanstrie\Desktop\ntnu\SCHEMA\2012\07_paper\results\026\onsets

I want to parse through folders 001-040 (026 shown above) and remove the onsets subdirectory with all files and subfolders that are in it. I am unsure how to achieve this with python 3. If you have a solution, please advise. Many thanks in advance.
Niels

A: I would think that something like this should work...
import glob
import os.path
import shutil
files_dirs = glob.glob(r'C:\Users\vanstrie\Desktop\ntnu\SCHEMA\2012\07_paper\results\*')
for d in files_dirs:
    head,tail = os.path.split(d)
    try:
        if (0 < int(tail) < 41) and (len(tail) == 3):  #don't want to delete `\results\3\onsets` I guess...
           print("about to delete:",d)
           shutil.rmtree(os.path.join(d,'onsets'),ignore_errors=True)
    except ValueError:  #apparently we got a non-integer.  Leave that directory.
        pass

As with anything when deleting files, I would definitely print the things that would be deleted on a first pass -- Just to make sure the script is actually working as expected (and to make sure you don't delete something you want to keep).

A: import shutil, os.path

root_folder = "C:\\Users\\vanstrie\\Desktop\\ntnu\\SCHEMA\\2012\\07_paper\\results"
suffix = "onsets"

for i in range(1,41):
  folder = os.path.join( root_folder, "%03d" % i, suffix )
  shutil.rmtree( folder, ignore_errors=True, onerror=None )


text:
Q: get prime numbers from numpy array I have a numpy array like,
nums = np.array([17, 18, 19, 20, 21, 22, 23])

How do I filter out the prime numbers from this array in a pythonic manner?
I know to do a simple filtering like,
nums[nums > 20]   #array([21, 22, 23])

Is there a way to pass a lambda function for filtering?
Expected output: array([17, 19, 23])

A: If you care of speed and efficiency I would recommend you to use one of the fastest prime sieves and numpy.intersect1d() function:
import numpy as np

def primesfrom2to(n):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    sieve = np.ones(n//3 + (n%6==2), dtype=np.bool)
    sieve[0] = False
    for i in range(int(n**0.5)//3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[      ((k*k)//3)      ::2*k] = False
            sieve[(k*k+4*k-2*k*(i&1))//3::2*k] = False
    return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]

# generate 100.000 random integers from 1 to 1.000.000.000
a1 = np.random.randint(1, 10**9, 100000)
# generate all primes that are equal or less than a1.max()
primes = primesfrom2to(a1.max())

# print result
print(np.intersect1d(primes, a1))

A: The way that I would do it is with gmpy or a 3rd party library who has developed a good primality test algorithm. The Miller-Rabin primality test is generally a very safe (and fast!) bet. If you just want the slow way, you can do:
import numpy as np
import math

def is_prime(n):
    if n % 2 == 0 and n > 2:
        return False
    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))

a = np.arange(1, 10**3)
foo = np.vectorize(is_prime)
pbools = foo(a)
primes = np.extract(pbools, a)
primes  # => Output below
array([  1,   2,   3,   5,   7,  11,  13,  17,  19,  23,  29,  31,  37,
        41,  43,  47,  53,  59,  61,  67,  71,  73,  79,  83,  89,  97,
       101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,
       167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
       239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311,
       313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389,
       397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
       467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563,
       569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
       643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727,
       733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821,
       823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,
       911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997])

If you want to filter OUT the primes, just call np.invert on the pbools variables. The same would go for any predicate. You can also pass a lambda into vectorize. For example, say we wanted only prime numbers that are also 1 away from being divisible by 5 (for whatever reason).
import numpy as np
import math

def is_prime(n):
    if n % 2 == 0 and n > 2:
        return False
    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))

a = np.arange(1, 10**3)
foo = np.vectorize(lambda x: (not (x + 1) % 5 or not (x - 1) % 5) and is_prime(x))
primes = a[foo(a)]  # => Shorthand.... Output below
array([  1,  11,  19,  29,  31,  41,  59,  61,  71,  79,  89, 101, 109,
   131, 139, 149, 151, 179, 181, 191, 199, 211, 229, 239, 241, 251,
   269, 271, 281, 311, 331, 349, 359, 379, 389, 401, 409, 419, 421,
   431, 439, 449, 461, 479, 491, 499, 509, 521, 541, 569, 571, 599,
   601, 619, 631, 641, 659, 661, 691, 701, 709, 719, 739, 751, 761,
   769, 809, 811, 821, 829, 839, 859, 881, 911, 919, 929, 941, 971, 991])

A: It appears that you question is not about primes at all, but about how to apply a function to numpy array. I used simple is_odd example. Maybe np.vectorize is what you are looking for:
In [34]: nums = np.array([17, 18, 19, 20, 21, 22, 23])

In [35]: def is_odd(n):
    if n % 2 == 1:
        return True
    return False
   ....:

In [36]: is_odd_v = np.vectorize(is_odd)

In [37]: nums[is_odd_v(nums)]
Out[37]: array([17, 19, 21, 23]

If I recall correctly np.vectorize is used primarily for convenience, and does not have great performance.

A: Having a setup like this:
import numpy as np
import math
nums = np.array([17, 18, 19, 20, 21, 22, 23])

So now we create an array that contains all possible integer candidates:
divisors = np.arange(2,int(math.sqrt(np.max(nums)))+1) # Numbers from 2 to sqrt(max(nums))
print(divisors)
# [2 3 4]

Now apply the modulo operation on the array but with a different dimension so we check each number with each divisor:
print(nums[:,None] % divisors[None,:]) # Modulo operation on each element (0 means divisible)

[[1 2 1]
 [0 0 2]
 [1 1 3]
 [0 2 0]
 [1 0 1]
 [0 1 2]
 [1 2 3]]

Now how do we get the primes ... we check if there is no result in the line that is zero:
print(np.min(nums[:,None] % divisors[None,:], axis=1)) # Minimum of the modulo for that element
# [1 0 1 0 0 0 1]

and then create a mask to index them:
print(nums[np.min(nums[:,None] % divisors[None,:], axis=1) > 0]) # So index them
# [17 19 23]

So all you need in the end is:
nums = np.array([17, 18, 19, 20, 21, 22, 23])
divisors = np.arange(2,int(math.sqrt(np.max(nums)))+1)
nums[np.min(nums[:,None] % divisors[None,:], axis=1) > 0]

all the other stuff is just for illustrating what each step is doing.
This is not trivial since it uses broadcasting of 1D arrays into a 2D array but the method should be clear. Let me know if you have any questions.

If you want to optimize this, there is another possibility: The divisors are currently every number between 2 and the sqrt(max(array)) but you don't need to test for all these numbers. If you had a function that returned all primes in that range that would be enough. For example using primesfrom2to of @MaxU's answer a faster possibility is:
nums = np.array([17, 18, 19, 20, 21, 22, 23])
# All prime numbers in the range from 2 to sqrt(max(nums))
divisors = primesfrom2to(int(math.sqrt(np.max(nums)))+1)
nums[np.min(nums[:,None] % divisors[None,:], axis=1) > 0]

but it uses the same mechanism as before but is a bit faster. :-)

A: If you really want to use a Filter, you can use this:
nums[[i for i in range(len(nums)) if sum([nums[i]%val==0 for val in range(2,nums[i]-1)])==0]]

What does this do?
We search all indexes with prime number by using
[i for i in range(len(nums)) if sum([nums[i]%val==0 for val in range(2,nums[i]-1)])==0]

This basically goes through every value and checks if it is not divisible by any value smaller than itself (ignoring 1)
[i for i in range(len(nums)) #for every index

if sum(#calculate sum of booleans

[nums[i]%val==0 for val in range(2,nums[i]-1)] # check if it is divisble by any value smaller than itself

)==0 #check if the number of divisors is zero


text:
Q: alignment of divs inside one another

<asp:Image ID="Image1" runat="server" ImageUrl="~deliveryvan.jpg" Height="75px" Width="100px" />

<asp:HyperLink ID="HyperLink7" NavigateUrl="~/List.aspx" runat="server" Text="Deliveries"></asp:HyperLink>
    <% if (NumerofDeliveries > 0) %>
     <% { %>

<%:NumerofDeliveries%>

      <% } %>

I would like to place the div containing the numbers in the top right of the box.
I can do this by removing margin-top:12px; from the original div. however I need to keep margin-top:12px;  as I want the images to have padding.
Any help?

A: use - margin value for the numbers.
margin-top:-12px;


text:
Q: "Form region" for calendar views in outlook add-in Overview: I would like to show a "form region" when calendar is selected in Outlook. I also would like to show some custom HTML content in the reading pane (or any pane like task pane adjacent to main calendar pane).
Questions:

*

*Are API add-ins allowed for Calendar views in Outlook?

*Are & custom form regions allowed for Calendar views in Outlook?

*Would it be possible to show Custom form region here in Calendar's reading pane when no specific time is selected in the calendar?

*Would it be possible to show Custom form region here in Calendar's reading pane when specific appointment type is selected in the calendar?

A: Create a task pane instead - see https://msdn.microsoft.com/en-us/library/aa942864.aspx and https://msdn.microsoft.com/en-us/library/bb296010.aspx.
Takes panes can be displayed both in explorers (that is what you need) and inspectors (similar to form regions).

A: Unfortunately it's currently not possible to open an Outlook Add-In in 'Calendar/meeting view' using the 'new' office add-in model. It's only possible to open it in Mail Read or Compose mode and Appointment/meeting Read or Compose mode where a single item is opened. Maybe you could create a UserVoice for this?
OfficeDev UserVoice


text:
Q: Calculate unique items seen by users via sql I need help to resolve the next case.
The data which users want to see is accessible by pagination requests and later these requests are stored in the database in the next form:
+----+---------+-------+--------+
| id | user id | first | amount |
+----+---------+-------+--------+
|  1 |    1    |   0   |    5   |
|  2 |    1    |   10  |   10   |
|  3 |    1    |   10  |    5   |
|  4 |    1    |   15  |   10   |
|  5 |    2    |   0   |   10   |
|  6 |    2    |   0   |    5   |
|  7 |    2    |   10  |    5   |
+----+---------+-------+--------+

The table is ordered by user id asc, first asc, amount desc.
The task is to write the SQL statement which calculate what total unique amount of data the user has seen.
For the first user total amount must be 20, since the request with id=1 returned first 5 items, with id=2 returned another 10 items. Request with id=3 returns data already 'seen' by request with id=2. Request with id=4 intersects with id=2, but still returns 5 'unseen' pieces of data.
For the second user total amount must be 15.
As a result of SQL statement, I should get the next output:
+---------+-------+
| user id | total |
+---------+-------+
|    1    |   20  |
+---------+-------+
|    2    |   15  |
+---------+-------+

I am using MySQL 5.7, so window functions are not available for me. I stuck with this task for a day already and still cannot get the desired output. If it is not possible with this setup, I will end up calculating the results in the application code. I would appreciate any suggestions or help with resolving this task, thank you!

A: This is a type of gaps and islands problem.  In this case, use a cumulative max to determine if one request intersects with a previous request.  If not, that is the beginning of an "island" of adjacent requests.  A cumulative sum of the beginnings assigns an "island", then an aggregation counts each island.
So, the islands look like this:
select userid, min(first), max(first + amount) as last
from (select t.*,
             sum(case when prev_last >= first then 0 else 1 end) over
                 (partition by userid order by first) as grp
      from (select t.*,
                   max(first + amount) over (partition by userid order by first range between unbounded preceding and 1 preceding) as prev_last
            from t
           ) t
     ) t
group by userid, grp;

You then want this summed by userid, so that is one more level of aggregation:
with islands as (
      select userid, min(first) as first, max(first + amount) as last
      from (select t.*,
                   sum(case when prev_last >= first then 0 else 1 end) over
                       (partition by userid order by first) as grp
            from (select t.*,
                         max(first + amount) over (partition by userid order by first range between unbounded preceding and 1 preceding) as prev_last
                  from t
                 ) t
           ) t
      group by userid, grp
     )
select userid, sum(last - first) as total
from islands
group by userid;

Here is a db<>fiddle.

A: This logic is similar to Gordon's, but runs on older releases of MySQL, too.
select userid
  -- overall length minus gaps
  ,max(maxlast)-min(minfirst) + sum(gaplen) as total
from
 (
   select userid
     ,prevlast
     ,min(first) as minfirst -- first of group
     ,max(last) as maxlast   -- last of group
      -- if there was a gap, calculate length of gap
     ,min(case when prevlast < first then prevlast - first else 0 end) as gaplen
   from
    (
      select t.*
        ,first + amount as last -- last value in range
        ,( -- maximum end of all previous rows
           select max(first + amount)
           from t as t2
           where t2.userid = t.userid
             and t2.first < t.first
         ) as prevlast
      from t
    ) as dt
   group by userid, prevlast
 ) as dt
group by userid
order by userid

See fiddle


text:
Q: Does C have enumeration-controlled loops? What I'm asking:
Does C have enumeration-controlled loops?
Why do so many languages require the step size of an enumeration-controlled loop to be a compile-time constant?

A: As for 1.:
Yes, it does. 2 Examples:
for loops can be "enumeration controlled".
for (i = 0; i <= 10; i++){
   //your code
}

while and do-while conditions can also be "enumeration controlled".
i = 0;
while (i < 10){
   //your code
   i++;
}

On this website you can find an article about the problems with enumeration controlled loops in C.
Talking about "enumeration controlled loops" is however a little dated, as they are usually referenced at as "iterative conditional loops".
About 2.:
I'm dismissing your second question as [too broad] for this context.


text:
Q: Is it legal to cast a struct to an array? Consider the following:
// Just a sequence of adjacent fields of same the type
#[repr(C)]
#[derive(Debug)]
struct S<T> {
    a : T,
    b : T,
    c : T,
    d : T,
}

impl<T : Sized> S<T> {
    fn new(a : T, b : T, c : T, d : T) -> Self {
        Self {
            a,
            b,
            c,
            d,
        }
    }
    // reinterpret it as an array
    fn as_slice(&self) -> &[T] {
        unsafe { std::slice::from_raw_parts(self as *const Self as *const T, 4) }
    }
}

fn main() {
    let s = S::new(1, 2, 3, 4);

    let a = s.as_slice();

    println!("s :: {:?}\n\
              a :: {:?}", s, a);
}

*

*Is this code portable?

*Is it always safe to assume a repr(C) struct with fields of same type can be reinterpreted like an array? Why?

A: Yes, it is safe and portable, except for very large T (fix below). None of the points listed in the safety section of the documentation for std::slice::from_raw_parts are a concern here:

*

*The data pointer is valid for mem::size_of::<T>() * 4, which is the size of S<T>, and is properly aligned.

*

*All of the items are in the same allocation object, because they are in the same struct.

*The pointer is not null, because it is a cast from the safe &self parameter, and it is properly aligned, because S<T> has (at least) the alignment of T.

*The data parameter definitely points to 4 consecutive initialized Ts, because S is marked #[repr(C)] which is defined such that in your struct, no padding would be introduced. (repr(Rust) makes no such guarantee).

*The memory referenced is not mutated during the lifetime of the reference, which is guaranteed by the borrow checker.

*The total size of the slice must not be greater than isize::MAX. The code does not check this, so it is technically a safety hole. To be sure, add a check to as_slice, before the unsafe:
assert!(std::mem::size_of::<S<T>>() <= isize::MAX as _);

The check will normally be optimized out.


text:
Q: The input dimension of the LSTM layer in Keras I'm trying keras.layers.LSTM.
The following code works.
#!/usr/bin/python3
import tensorflow as tf
import numpy as np
from tensorflow import keras

data = np.array([1, 2, 3]).reshape((1, 3, 1))
x = keras.layers.Input(shape=(3, 1))
y = keras.layers.LSTM(10)(x)
model = keras.Model(inputs=x, outputs=y)

print (model.predict(data))

As shown above, the input data shape is (1, 3, 1), and the actual input shape in the Input layer is (3, 1). I'm a little bit confused about this inconsistency of the dimension.
If I use the following shape in the Input layer, it doesn't work:
x = keras.layers.Input(shape=(1, 3, 1))

The error message is as follows:
ValueError: Input 0 of layer lstm is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: [None, 1, 3, 1]

It seems that the rank of the input must be 3, but why should we use a rank-2 shape in the Input layer?

A: Check out the documentation for tf.keras.Input. The syntax is as-
tf.keras.Input(
    shape=None,
    batch_size=None,
    name=None,
    dtype=None,
    sparse=False,
    tensor=None,
    **kwargs
)

shape: defines the shape of a single sample, with variable batch size.
Notice, that it expects the first value as batch_size otherwise pass batch_size as a parameter explicitly

A: Keras works with "batches" of "samples". Since most models use variable batch sizes that you define only when fitting, for convenience you don't need to care about the batch dimension, but only with the sample dimension.
That said, when you use shape = (3,1), this is the same as defining batch_shape = (None, 3, 1) or batch_input_shape = (None, 3, 1).
The three options mean:

*

*A variable batch size: None

*With samples of shape (3, 1).

It's important to know this distinction especially when you are going to create custom layers, losses or metrics. The actual tensors all have the batch dimension and you should take that into account when making operations with tensors.


text:
Q: ARIMA trend = 'nc' or 'c' in python I am trying to work with ARIMA forecasting for a TS that has trends and seasonality. Hence I decompose the data into residual+trend+seasonality.
As I need to predict values out of sample, I am using exog=trend as input for the model and run prediction on residual (which is ~stationary).
This works really poorly. It seems that the trend is not taken into consideration by the model at all - when I add artificially the trend to the predicted values, i.e., plot prediction + trend, the prediction looks very close to the original series... But since I do not know the trend, I cannot do this trick. When not using additive trend, there is a seemingly constant difference between parts of the prediction and the real data.
My question is the following - can ARIMA deal with trend in Python (I know that it can in R)? How can it be imported into the model if not via exog? I tried to run ARIMA on residual+trend and it still performs badly.
Also, what is the meaning of trend = 'c' Vs trend = 'nc'? The manual says "Whether to include a constant or not. 'c' includes constant, 'nc' no constant." Constant as constant trend 0-order estimate? Constant as expected constant trend, i.e., 'nc' means varying trend? Or 'nc' as no trend included in the model? The prediction does not work well neither with this nor with that option, but if I know that there is a trend, should I always use "c"?
Help please?
Thanks.