text:
Q: Controlling how items are placed in a row via flexbox/fluent ui I am using flexbox and Microsoft's fluent ui "stack" abstraction of it to display video-cards on a page in my React app. I am using flex-wrap and space-between to keep equal space between each of the items, as the name implies. And this looks perfect when numerous items exist on the page.
However, when you're just starting to add items, and you go to add a second item, instead of placing the item just to the right of the first video-card - which is aligned to the left of the page - the second item gets put on the far right of the row. And then the 3rd item is half the distance of 1 and 2 -- so it's placed in the exact middle of the row.
My question is, how can get that 2nd item -- and then the 3rd, etc. -- to drop in just to the right of the previous item, until the row is full, at which point it wraps to a new row and the same happens again?
This is my code:
<Stack
  horizontal
  styles={{
   root: {
    'flex-wrap': 'wrap',
    'justify-content': 'space-between'
   }
  }}>
  {this.showNewVideoCard()}
  {this.state.videos.map((video, index) => (
    <div key={index}>
      <VideoCardForm key={video.id}
       ... more code
      />
    </div>
  ))}
</Stack>

In other words, when I add the second item, what I'm getting is something like this:

... when what I want is something like this:

And I'm guessing the way it would need to work, behind the scenes, is that the space between each item will need to be calculated based on the maximum number of items you can fit in one row?
Is this a scenario flexbox is designed to handle? Or is this more complicated than I'm realizing? Note: in case it's not already obvious, each video-card will be exactly the same dimensions. So, in my use case, I know I can fit 7 video-cards in a row before it wraps to the next row. I'd just rather the items in a row drop in next to each other, rather than on opposite ends of the row initially.

A: I believe your issue is that you're using justify-content: space-between, when you should be using justify-content: flex-start and giving each item a margin. Since flex-start is the default value for justify-content you can just remove that line all together.


text:
Q: User session expires after every deploy. Using asp.net core, identity and azure I have an asp.net core web application deployed on Azure App Service, the problem is that every time I publish changes to the server, (no matter if it's via vs publish or via vs team services ci) the users sessions expires and every user has to login again.
How can I avoid this?
Thanks for your help.

A: Everytime you publish build your AppDomain recycled, so session state will be changed and expired.
You can read in details in this question
Losing Session State

*

*If you want to keep your user logged-in after build, maybe use another technique. Like Access Tokens for example.

Read more from here
https://samueleresca.net/2016/12/developing-token-authentication-using-asp-net-core/
https://dotnetthoughts.net/token-based-authentication-in-aspnet-core/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intersection of $X \cap Y$ where X and Y are x and y axis in $\mathbb{R^n}$ I was asked two questions in class. One was what would be the intersection of X and Y ($X \cap Y)$ when X and Y are x and y axis in $\mathbb{R^2}$ and the other question was the same but in $\mathbb{R^3}$.
I thought in $\mathbb{R^2}$ it would be a point (namely the origin) which is apparently wrong. In the case of $\mathbb{R^3}$ i dont know what the answer is. Does having a z axis affect the answer since the question only asks us to worry about $X \cap Y$ in $\mathbb{R^3}$ so i thought it doesnt matter if z axis exist and the answer in the case would be again a point (namely the origin).
What is incorrect about both of these cases?
EDIT: Picture of the question Question
. We are given four options from which to choose our answer. The options are A. no elements, B. one element, C. Two elements and D. Infinitely many elements


text:
Q: symfony2 CSRF invalid Okay, so today I updated my database with new information from our 'live' database...  And since then I've been having issues on one of my forms.  If you need any code let me know and i'll edit this and post the code needed...
I have a report form which has a date range field and a drop down for an agent department.  When I first visit the page I see this at the beginning of the form:
The CSRF token is invalid. Please try to resubmit the form
So I go over to one of my other forms that has the same type of information, and check the _token out and this is what comes out:
<input type="hidden" id="ecs_crmbundle_TimeClockReportType__token" name="ecs_crmbundle_TimeClockReportType[_token]" value="87e358fbc4d6d3e83601216b907a02170f7bcd92" />
<input type="hidden" id="ecs_crmbundle_SimpleSalesReportType__token" name="ecs_crmbundle_SimpleSalesReportType[_token]" value="87e358fbc4d6d3e83601216b907a02170f7bcd92" />

The first one is the one that shows the error, and the SimpleSalesReport does not...  Any idea why this is doing this or how I can fix it?
Thanks..

A: Are you by chance using $form->bindRequest() in the action which produces the CSRF error? I had this issue. You should not be binding the request for a new form. If you are posting the form to the same action, wrap the bindRequest in a conditional which checks if method is POST:
if ($this->getRequest()->getMethod() == 'POST') {
  $form->bindRequest($this->getRequest());
  if ($form->isValid()) {
    ...
  }
}

A: There is no problem using {{ form_widget(form) }} to build your custom form.
All you have to do is add the _token like this:
{{ form_widget(form._token) }}

A: This error had me crazy for days!
Thanks krishna!
If in your form template you choose to not use the default form behavior {{ form_widget(form) }} you SHOULD put {{ form_rest(form) }}
Hope this could help anyone else!


text:
Q: Send email with list of active plugins upon activation/deactivation I'm using Airtable to keep a real-time list of plugins for multiple WP sites, and have an almost-working setup with Zapier emailing new plugin data when a plugin is activated or deleted.
The email is correct upon plugin activation, however upon deactivation the recently-deactivated plugin is still included in the list. Is the plugin list somehow being cached?
Almost-working code:
////////////////////////////////////////////////////////////
// send an email on plugin activate / deactivate
////////////////////////////////////////////////////////////

function urlToDomain($url) {
   return implode(array_slice(explode('/', preg_replace('/https?:\/\/(www\.)?/', '', $url)), 0, 1));
}

function detect_plugin_change( $plugin, $network_activation ) {

    $url = urlToDomain(site_url());

    $the_plugs = get_option('active_plugins');
    sort ( $the_plugs );
    foreach($the_plugs as $key => $value) {
        $string = explode('/',$value);
        $plugins .= $string[0] .", ";
    }

    $to = [email address removed];
    $subject = $url;
    $body = $plugins;
    $headers = array('Content-Type: text/html; charset=UTF-8');

    wp_mail( $to, $subject, $body, $headers );

}
add_action( 'activated_plugin', 'detect_plugin_change', 10, 2 );
add_action( 'deactivated_plugin', 'detect_plugin_change', 10, 2 );

This sends an email like this:
To: [email address removed]
Subject: sitename.com
Body: admin-menu-editor, display-posts-shortcode, gravityforms, list-pages-shortcode, plugin-central, simple-history, taxonomy-list-shortcode, user-switching, wordpress-seo, wp-scss
Any ideas what needs to be edited so that it works properly upon plugin deactivation? Thank you!

A: If you look here in /wp-admin/includes/plugin.php
        do_action( 'deactivated_plugin', $plugin, $network_deactivating );
    }
}

if ( $do_blog )
    update_option('active_plugins', $current);
if ( $do_network )
    update_site_option( 'active_sitewide_plugins', $network_current );

The options aren't updated until after the hook fires.
You can get around this by using the first parameter to deactivated_plugin:
function detect_plugin_change( $plugin, $network_activation ) {

    $url = urlToDomain(site_url());

    $the_plugs = get_option('active_plugins');
    sort ( $the_plugs );
    foreach($the_plugs as $value) {
        // Skip the deactivated plugin.
        if ( $plugin === $value ) {
            continue;
        }

        $string = explode('/',$value);
        $plugins .= $string[0] .", ";
    }

    $to = [email address removed];
    $subject = $url;
    $body = $plugins;
    $headers = array('Content-Type: text/html; charset=UTF-8');

    wp_mail( $to, $subject, $body, $headers );

}

Edit: You can also get "fancy" and provide more details about the plugins, if needed, using get_plugin_data.


text:
Q: How to fill a vector of struct I have the following code, where i defined a vector of vector of struct
#include <vector>
#include <iostream>

using namespace std;

struct node
{
    int index;
    double value;
};

int main()
{

    vector  < vector <node> >vett1;

    node p;
    p.index=5;
    p.value=2;

    for (int i=0; i<10; i++)
        vett1[i].push_back(p);

    return 0;
}

i don't know the right way to fill it. In this way when i run it, compilers gives me segmentation fault error.

A: When you access vett1[i], but the vett1 has not been filled with size zero. That's why the segmentation fault error occur.
Three ways to fix it:

*

*Add
vett1.resize(10);

before the for loop.

*Or define vett1 and set its size as follows:
vector <vector <node>> vett1(10);

*Or you can do this if you don't know the exact size pre-hand:
for (int i=0; i<10; i++)
{
    vector<node> temp;
    temp.push_back(p);
    vett1.push_back(temp);
}


text:
Q: Add 'Stack Exchange Community FAQ' pages to 'help' search results As sort of an 'inverse' to this request, "Add help link to FAQ," I propose tying in the "FAQ for Stack Exchange sites" content into the 'help' search function on all SE network sites.  Even if just the question titles on the FAQ page were included, I think it would be beneficial. Indexing the contents of the linked questions for inclusion in a 'help' search would be even better.
For context, this request is prompted by my first encounter with review audits, on SU.  I failed my first review audit because I thought it was a bug in the site, and freaked out a bit because (a) I hadn't even known that audits existed, and (b) I couldn't find any information on what the consequences were for failing audits.  The FAQ points to a good overview of audits, but searching SU help for 'audit' at present returns zero hits, and I hadn't remembered the existence of the SE FAQ.


text:
Q: Form and input element looks different on IE11 and Firefox compared to chrome the image of my shopping cart looks different from chrome to IE/firefox. (chrome is straight but IE/FF is positioned slighly lower)
I want them all to look the same as the one in chrome. I am running normalize.css I am quite a newbie programmer so keep that in mind, please can you help me out, below is the html and css:
HTML

    <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr"     method="post" class="shopping">
        <input type="hidden" name="cmd" value="_cart">
        <input type="hidden" name="business" value="HUUDRV4678LJG">
        <input type="hidden" name="display" value="1">
        <input class="input1"type="image" src="http://asknaturalhealth.com/img/shopping1.png" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

    </form>

CSS:
.shopping {
    position: relative;
    display: inline;
    top: 40px;
    left: 1080px;
    margin-left: -1000px;
}

    .shopping .input1 {
    -moz-box-sizing: border-box;
   box-sizing: border-box;
}

A: Try this:
    .shopping {
        position: relative;
        display: inline;
        top: 40px;
        left: 1080px;
        margin-left: -1000px;
    }

        .shopping .input1 {
        -webkit-box-sizing:border-box;
        -moz-box-sizing: border-box;
         box-sizing: border-box;
}


text:
Q: Using subject and observable as I/O service parameters to avoid dependence on http request/reponse structure and the service providing http calls I am building a service, which needs to open a modal, and trigger a chain of http calls on certain user interactions. The APIs i need to call depend on the actual context where the service is being used, as well as the API parameters.
I wanted to avoid having to define callbacks to use my service, or using the httpService (or its wrapped version) as parameter as then it would have to implement certain methods my service expects - to keep usage as simple as possible. Also avoiding callbacks was an external expectation.
I'm still learning rxjs, and not sure if this is an acceptable solution using a subject like this, or are there better ways?
Is it safe from memory leaks to use Subject this way?
I assumed using takeUntil and calling next on destroy$ will cancel any subscription on my end, and everything will be garbage collected when the modal opened by the service and the parent component is both destroyed.
Ideally only one modal component will be active at a time, but i don't know if there won't be several instances existing in browser memory at any given time so i'm not sure if exposing a single/global Subject property in the service would be a good idea.
export class myService {
  doStuff(
    subject: Subject<InputType>,
    mappedSubject: Observable<ResponseType1>,
    otherAPICall: Observable<ResponseType2>,
  ) {
    return this.dialog.open({data: { subject, mappedSubject, otherAPICall });
  }
}

in the modal:
private destroy$ = new Subject();

ngAfterViewInit() {
  this.data.mappedSubject.pipe(
    takeUntil(this.destroy$),
    flatMap(result => {
      if (result.allGood) return this.data.otherAPICall;
       Observable.throw("not good");
    }),
  ).subscribe(result => displayResult(result));
}

doOnButtonClick() {
  this.data.subject.next(this.form.get("myInput").value);
}

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}

usage in another component:
const subject = new Subject()<InputType>;
this.myService.doStuff(
  subject,
  subject.pipe(
    flatMap(inputValue => this.httpService1.call(this.transform(inputValue))),
    map(x => (x as ResponseType1)),
  ),
  this.httpService2.call(params).pipe(map(x => (x as ResponseType2)),
);

A: Only concern is, why are we passing Subject as data property inside open(). Using DI you can inject service anywhere in Component/Service constructor and access it there right?.
Avoid passing subject, this may lead to memory consumption and performance issues.
Instead of using 'flatMap', you can try switchMap. This will cancel previous the source observable Http call if active.


text:
Q: Transform the equation into a system of first order equation. Transform the equation
$$\dfrac{d^3x}{dt^3}+t\dfrac{d^2x}{dt^2}+2t^3\dfrac{dx}{dt}-5t^4=0$$
into a system of first order equation.
I can't understand how to proceed.

A: We are given:
$$\dfrac{d^3x}{dt^3}+t\dfrac{d^2x}{dt^2}+2t^3\dfrac{dx}{dt}-5t^4=0$$
As hinted at by @ShuhaoCao, we can proceed as follows:

*

*$x_1 = x \implies x_1' = x' = x_2$

*$x_2 = x' \implies x_2' = x'' = x_3$

*$x_3 = x'' \implies x_3' = x''' = -t x'' -2t^3 x' +5t^4 = -t x_3 -2t^3x_2+5t^4$

So, our new system is:
$$\begin{align}
x_1' & = x_2 \\
x_2' & = x_3 \\
x_3' & = -t x_3 -2t^3x_2+5t^4
\end{align}$$
Note, if we had been given initial conditions, they would similarly follow as:

*

*$x(0) = a \implies x_1(0) = a$

*$x'(0) = b \implies x_2(0) = b$

*$x''(0) = c \implies x_3(0) = c$


text:
Q: How to simulate a key event with modifier key pressed in an Ember.js integration test? I'm trying to test an event handler that reacts to the shift + delete key combo, but the Ember docs for the Test.keyEvent method don't seem to mention any way to activate modifier keys.
I tried issuing a keydown on shift (keyCode 16), then keydown on delete (keyCode 46):
keyEvent('.my input', 'keydown', 16);  // Shift
keyEvent('.my input', 'keydown', 46);  // Delete
keyEvent('.my input', 'keyup', 46);  // Delete
keyEvent('.my input', 'keyup', 16);  // Shift

but the delete event's shiftKey property is still undefined

A: It seems the answer is to use triggerEvent instead of keyEvent:
triggerEvent('.my input', 'keydown', {
  keyCode: 46,  // Delete
  shiftKey: true
});


text:
Q: How do I come up with an equation that will describe the results of other integrals with changes to a constant? I have one equation: 10*(1-x)(x^n)+(x)(1-x^n), to which I must find the integral of from [0,1], with n ranging from 1 to 100. I want to then plot the results with the x value as the value of n and the y value as the result of the integrals for each corresponding n value. What would the final equation that graphs the results be?

A: f[n_] = Integrate[10*(1 - x) (x^n) + (x) (1 - x^n), {x, 0, 1}, Assumptions -> n > 0]
Plot[f[n], {n, 1, 100}]

gives back $$f(n)=\frac{n^2+n+20}{2 n^2+6 n+4}$$
and

A: I think that the graphs are aligned. I used PlotRange to match your graph and they look similar. I added to the solution given by bRost03.
Plot[f[n], {n, 1, 130}, PlotRange -> {{0, 160}, {0, 2}},
 Ticks -> {Range[0, 160, 20], Range[0, 2, .20]},
 GridLines -> {Range[0, 160, 20], Range[0, 2, .20]}]


text:
Q: gl_FragCoord precision I have this fragment shader code that displays differently between iOS simulator (non-retina) and iPad2 (non-retina) :
     highp vec2 textCoord;
     textCoord.x = gl_FragCoord.x / uViewPortWidth;
     textCoord.y = gl_FragCoord.y / uViewPortHeight;

     highp vec4 resultColor = texture2D(uTexture, textCoord);

     gl_FragColor = resultColor;

Somehow in real device, the result is jagged. But in simulator, it's smooth as hell.
Real device :

Is it because of precision problem of the gl_FragCoord? Weird how it only works on simulator...
Any tips how to deal with gl_FragCoord? Thanks!

A: gl_FragCoord is defined as mediump. So compliant implementations of ES 2 can give it as little as 10 bits of storage. However ES doesn't place an upper limit, so another equally compliant implementation may discard the precision modifiers and treat everything as a 16-bit (or greater) type.
It also stipulates that:

The precision used to internally evaluate an operation, and the
  precision qualification subsequently associated with any resulting
  intermediate values, must be at least as high as the highest precision
  qualification of the operands consumed by the operation.

So the precision used to perform your calculations will be at least mediump — or highp if that's how uViewPortWidth/Height are declared.
However exactly what precision that gives you is still implementation dependant. Anecdotally, the simulator does generally use a higher precision.
So, as a first attempt, make sure that divide is highp by any means. If that doesn't get the precision you want then the GPU likely doesn't provide it in a single unit so you'll have to consider a more complicated solution.


text:
Q: Shuffling of MySQL record on page refresh I am working on a website where i have two types of offer (best offer and hot offer) fetching from database. I have limited the record to 1.  So that one only one record of hot offer and one record of best offer should view to user. Now I have to shuffle the each offer in page refresh. That is, when any one refresh the page, the next hot offer (from database) should replace the previous hot offer and should be same in best offer.

A: Make it Random, otherwise you have to maintain state of offer displayed on page to get next offer.
Below Query will help.
SELECT * from tbl_offers ORDER BY RAND() LIMIT 0,1;

A: Add ORDER BY RAND() LIMIT 1 to the end of your MySQL query IFF your table is small.
If it is large then this is a very inefficient way of doing it (since it still evaluates every row) so you'd be better off counting the number of rows:
SELECT MAX(id), COUNT(*) FROM table

and then picking a random id ($id = rand(1,$count);) and then selecting that row
SELECT * FROM table WHERE id = $id

If there are deleted rows (and this last command returns nothing) then pick a random ID again and run the previous command again. The COUNT(*) in the first query is so you can ensure that there is at least 1 row.
This does not work well for tables where there are a lot of deleted rows, plus it assumes that you have an auto_increment field.


text:
Q: Salesforce trigger - passing values from trigger record Objective here – to extract the account__r.id from the record in the trigger and add the value to a list with each for-loop…
CODE SAMPLE ONE
if (trigger.isinsert) {
for (loan__c oloan : trigger.new){
system.debug(oloan);
    Loan__c loanintrigger = new loan__c();
    loanintrigger = [ SELECT loan__c.name,account__r.id from loan__c WHERE loan__c.id =      : oloan.id];
    Account a = new account ();
    a.id = loanintrigger.account__r.id;
    //   debug to test insertion of value directly from trigger object.....
    system.debug(a.id);

CODE SAMPLE TWO
if (trigger.isinsert) {
for (loan__c oloan : trigger.new){
system.debug(oloan);
    Account a = new account ();
    a.id = oloan.account__r.id;
//   debug to test insertion of value directly from trigger object.....
    system.debug(a.id);

So… trigger one runs and completes its assignment. Trigger two fails due to "missing argument."  I.e. – system.debug(a.id) shows that the id in the account object is null.
1, of course, requires a query for every record in the trigger.  No style points.
This foreshadows another important and vexing question….
In the context of an after delete trigger, not even #1 works because you cannot query DB for data that has been deleted!
Can anybody suggest alternate approach?  What am I missing?


text:
Q: How to ignore CMake Compiler Definitions in sub projects I have a main project that has several 3rd party libraries. I just added a new 3rd party project. The problem I'm facing is the new project breaks when the main project compiler definitions are passed to it.
How can I avoid passing these definitions to the 3rd party project?
Also, if the 3rd party project is compiled stand-alone, it only requires two include directories. But when compiled with the main project there are many extra directories passed to it.
I've tried looking for a set_definition() but I'm not seeing anything helpful.
Any links to examples or write ups will be nice. It might also be that I'm not looking for the right solution.
thanks

A: Using global 'add_definition' is old-approach. In present may be much better define compiler flags, defines etc. per target, folder, source files etc. (in your case COMPILE_DEFINITIONS?)
Just google for 'modern CMake' and you will find slides and videos from conferences how to use modern CMake.


text:
Q: Removing blank space from bottom of HTML page I'm recreating the look of the google homepage, and I'm noticing that there is large blank area below the bottom of the body. Additionally, the page "height" is longer than I expected, as you need to scroll down to view the space.
This is surprising to me, because the body mainly consists of two divs set at 95% and 5% height, so I thought that would simply fill the window frame perfectly. Inspecting it with chrome tools doesn't show that any element's space taking up this extra room. I've attached a screenshot and here is the code.
body {
    background-color: white;
    margin:0;
}
body, html{
    height: 100%;
}

.imageTag{
    display: inline-block;
    vertical-align: bottom;
}

.topItem{
    font-family: arial,sans-serif;
    font-size: 13px;

    margin-right: 25;
    margin-top: 13;

    opacity: .75;
}

.topItem:hover {
    text-decoration: underline;
    cursor:pointer;
}

.signIn{
    border:7px solid #419bf4;
    border-right: 12px solid #419bf4;
    border-left: 12px solid #419bf4;
    border-radius: 3px;

    background-color: #419bf4;

    color: white;
    font-size: 12px;
    font-weight: 600;

    margin-top: 8;

    opacity: 1;
}

.signIn:hover{
    cursor:pointer;

    text-decoration: none;

    background-color: #4486f7;
    border-color: #4486f7;
}

.squaresImg{
    margin-top: 8;
    margin-left: 1;
}

.squaresImg:hover{
    cursor:pointer;
}

.googleImg{
    margin-top:5;
    margin-bottom:30;
}

.searchBar{
    width:550px;
    height:45px;

    font-family: arial,sans-serif;
    font-size:18px;

    background-image:url(googleMic.png);
    background-repeat: no-repeat;
    background-position: 515px 10px;
    background-size: 3%;

    border: 1px solid;
    border-color: #dfdada;

    box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.19);

    outline: none;

}

.searchBar:hover{
    box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.2), 0 7px 7px 0 rgba(0, 0, 0, 0.19);

}

.barItem{
    margin-right: 2;
    margin-left: 2;

    border:1px solid #eeeeee;
    padding: 9px;
    border-radius: 3px;

    background-color: #eeeeee;

    font-family: arial,sans-serif;
    font-size: 13px;
    color: #646464;
    font-weight: 600;

    opacity: .75;
}

.barItem:hover{

    border-color: #646464;
    color: #000000;
}

.bottomDiv{
    width: 100%;
    /*height: 5%;*/

    background-color: #eeeeee;

    border: 1px solid;
    border-color: #e4e4e4;

}

.bottomItemL{
    float: left;

    margin: 10px 15px 0;

    font-family: arial,sans-serif;
    font-size: 13px;
    color: #666;
}
.bottomItemR{
    float: right;

    margin: 10px 15px 0;

    font-family: arial,sans-serif;
    font-size: 13px;
    color: #666;
}

.bottomItemL:hover {
    text-decoration: underline;
    cursor:pointer;
}

.bottomItemR:hover {
    text-decoration: underline;
    cursor:pointer;
}

  <meta charset="UTF-8">
  <title>Google Page</title>
  <link rel="stylesheet" type="text/css" href="style.css">

                Sign In

                Images

                Gmail

                <input class="searchBar" type="text" name="searchBar" autofocus="autofocus">

                Google Search
                I'm Feeling Lucky

        Advertising
        Business
        About
        Settings
        Terms
        Privacy

A: You need to define height of the parent element first, which is body tag.
Write this in your


text:
Q: Kotlin is it possible to start an activity from a class? I am new to kotlin, i am creating a framework to handle all my api call, the problem is that it doesn't have context. I would like to start an activity when i receive a certaine call of the api but i have no activity so i can't Intent.
What i have tried :
val intent = Intent(this, testActivity::class.java)
startActivity(intent)

But it's that that i need context.
I also tried to create a global Class Application with a companion object context but i get an error Required Context found Intent.
val intent = Intent(App.context, testActivity::class.java)
startActivity(intent)

Is there a way to start an activity in a class ? or what should i do ?

A: Create Application class and create instance.
@Synchronized
        fun getInstance(): MyApplication ? {
            return mInstance
    }

Initialize in Application's onCreate() method
override fun onCreate() {
        super.onCreate()
        mInstance = this
    }

Now use instance as your context in your whole app
MyApplication.getInstance()

A: From your activity, pass applicationContext as a parameter to your API class when creating an instance of the API class. You can do this via constructor injection. You can then use the received applicationContext to start activities and services


text:
Q: AngularJS directives - directives on transcluded content http://plnkr.co/edit/XbgMa9681GkKPeodplJx?p=preview
Please see the above plunker.  Is there a way to bind directives in template dom to the parent directive's scope?  I've seen this behavior with ng-transclude as well, the above is just about as simple as I can make it.  I have read that transcluded content is in a scope which is a sibling of the directive scope but $$nextSibling doesn't seem to be the trick either.

A: use directive:
app.directive('accordion', function($compile) {
  return {
      restrict: 'C',
      scope: {

      },
      link: function(scope, elem, attrs){
        scope.showSection = false;
        elem.find('p').attr('ng-show', 'false');
        $compile(elem.find('p'))(scope)
        elem.find('h1, h2').bind('click', function () {
          scope.$apply(function(){
            scope.showSection = !scope.showSection;
            elem.find('p').attr('ng-show', 'showSection');
            $compile(elem.find('p'))(scope);
          });
        });
      }
  };
});

plunkr


text:
Q: Characterization of Tychonoff spaces in terms of open sets Metrizability and complete regularity are topological properties that are, in a sense, different from the Hausdorff condition because they are not defined purely in the terms of the open sets, but rather using some external object, namely $\mathbb R$. Now a space is metrizable if it has the weak topology induced by a function $d : X \times X \rightarrow \mathbb R$ satisfying the properties of a metric, but metrization theorems tell us that an equivalent condition is that $X$ is regular and has a sigma-discrete basis (and this is purely topological). Is there a similiar characterization of Tychonoff spaces that makes no reference to $\mathbb R$ whatsoever?

A: A $T_1$ space $X$ is completely regular if and only if it has a basis $\mathcal{B}$ such that

*

*For every $x \in X$ and every $U \in \mathcal{B}$ that contains $x$, there exists $V \in \mathcal{B}$ such that $x \notin V$ and $U \cup V = X$.

*For any $U, V \in \mathcal{B}$ satisfying $U \cup V = X$, there exist $U', V' \in \mathcal{B}$ such that $X \setminus V \subset U'$, $X \setminus U \subset V'$ and $U' \cap V' = \varnothing$.

The proof can be found in
Frink, Orrin Compactifications and semi-normal spaces. Amer. J. Math. 86 1964 602–607.
The statement I've given above is actually dual to the statement of this paper. I took it directly from Engelking's General topology, which is the book I strongly recommend for finding references to this kind of questions.

A: Another answer was given by Aarts and De Groot in Complete regularity as a separation axiom Canadian Journal of Mathematics 21 1969 96–105. Frink's condition sets things up for a proof a la Urysohn's Lemma; Aarts and De Groot's condition is in terms of subbases and the proof proceeds by constructing a Hausdorff compactification.

A: Suppose that $(X,\mathcal{T})$ is a topological space. Then define a relation $\prec$ on $\mathcal{T}$ by letting $U\prec V$ if and only if $\overline{U}\subseteq V$. Define a relation $\ll$ on $\mathcal{T}$ by letting $U\ll V$ if and only if there is some $(U_{r})_{r\in[0,1]\cap\mathbb{Q}}$ such that $U_{0}=U,U_{1}=V$ and $\overline{U_{r}}\subseteq U_{s}$ whenever $r<s$. Then

*

*the space $(X,\mathcal{T})$ is regular if and only if for each $U\in\mathcal{T}$, we have $U=\bigcup\{V\in\mathcal{T}|V\prec U\}$, and

*the space $(X,\mathcal{T})$ is completely regular if and only if for each $U\in\mathcal{T}$, we have $U=\bigcup\{V\in\mathcal{T}|V\ll U\}$.
This characterization of regular and completely regular spaces is the way that one typically defines regularity and complete regularity in point-free topology. In fact, in point-free topology it is much more convenient to use this characterization of complete regularity than it is to use the characterization of complete regularity in terms of frame homomorphisms from the real numbers to your frame.
Perhaps the most illuminating characterizations of complete regularity are the following characterizations.
Let $X$ be a topological space. Then the following are equivalent:

*

*$X$ is completely regular.

*$X$ has a compatible proximity.

*$X$ has a compatible uniformity.
Of course, proximities and uniformities impose additional external structure on topological spaces.


text:
Q: How to get interface names from kernel using pyroute2 IPDB function? I would like to fetch the interface names (like eth0..etc) which exist in kernel using pyroute2 and IPDB functions.
import pyroute2

ipdb=pyroute2.IPDB()
   print ipdb.interfaces

The above code is displaying full information. But I would need only the  interfaces names.
Desired Output as:
eth0
eth1
...
I don't want to use IPRoute() function to fetch. I want to use IPDB to fetch the information.

A: There is another way to fetch the interface names using below snippet.
with pyroute2.IPDB() as ipdb:
        print(" ".join(ipdb.by_name.keys()))

A: This seems to do the trick:
import pyroute2
ipdb = pyroute2.IPDB()
print [ ipdb.interfaces[x].ifname for x in range(1, len(ipdb.interfaces)/2 + 1) ]

I don't like the way pyroute2 implements most of the things but, unfortunately, I'm too new on Python to change that module in way I would like.

A: just have a look here :
you'll be able to introspect your local network resources .. that's what I'm using on a large systems
https://pypi.python.org/pypi/netifaces

A: import pyroute2

ipr = pyroute2.IPRoute()
for link in ipr.get_links():
    print(link.get_attr('IFLA_IFNAME'))


text:
Q: How does auto deduce type? I have some cases of use of auto:
auto s = expr;          //s is always lvalue
auto & s = expr;        //s is always lvalue reference? What if expr is rvalue?
auto && s = expr;       //s is perfectly forwarded

Are they true? If not, why?

A: dyp is correct and I would like to elaborate.
First of all, the conclusion is the from dyp:

The type deduced for auto in the declaration of a variable is defined
  via the rules of template argument deduction, see [dcl.spec.auto]/6;
  with one exception: if the initializer is a braced-init-list, the
  deduced type is a std::initializer_list.

I'll explain.
First,
auto s = expr;

This is same as deducing the T from expr,
template<class T>
void f(T s);

f(expr);

The rule for template argument deduction is quite complicated, since you are only concerning with the lvalue and rvalue stuff, let's focus on this.
Template argument deduction is by comparing the template parameter type (call it P, in this case P is T), and the corresponding argument (call it A, in this case, the type of expr).
From 14.8.2.1,

If P is not a reference type:
— If A is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is
  used in place of A for type deduction; otherwise,
— If A is a function type, the pointer type produced by the function-to-pointer standard conversion (4.3)
  is used in place of A for type deduction; otherwise,
— If A is a cv-qualified type, the top level cv-qualifiers of A's type are ignored for type deduction.

So, if expr is array or function, it will be treated as pointers, if expr has cv-qualification (const etc), they will be ignored.

If P is a cv-qualified type, the top level cv-qualifiers of P's type are ignored for type deduction.

This actually says:
const auto s = expr;

s is a const variable, but for type deduction for auto purposes, the const will be removed.
Thus, from the above rules, auto will be deduced to the type of expr (after some type conversion stated above).
Note that, when an expression is a reference to T, it will be adjusted to T before prior analysis.
So whatever expr is – rvalue, lvalue, or lvalue/rvalue ref type – the type of auto will always be the type of expr without reference.
auto s1 = 1; //int
int &x = s1;
auto s2 = x; //int
int &&y = 2;
auto s3 = y; //int

Second, let's look at
auto &s = expr;

This will be same as
template<class T>
void f(T &s);

f(expr);

The extra rule from standard is as follows:

If P is a reference type, the type referred to by P is used for type deduction.

So the deduction of auto will be exactly same as without &, but after the auto type is deducted, the & is added to the end of auto.
//auto &s1 = 1; //auto is deducted to int, int &s1 = 1, error!
const auto &s1 = 1; //auto is deducted to int, const int &s1 = 1; ok!
const int &x = s1;
auto &s2 = x; //auto is int, int &s2 = x; ok!
int &&y = 2;
auto &s3 = y; //auto is int, int &s3 = y; ok!

Note that the last y is an lvalue. The rule of C++ is: named rvalue reference is an lvalue.
Lastly:
auto &&s = expr;

This is no doubt same as
template<class T>
void f(T &&s);

f(expr);

One additional rule from standard:

If P is an rvalue reference to a cv-unqualified template parameter and
  the argument is an lvalue, the type "lvalue reference to A" is used in
  place of A for type deduction.

This actually says that, if expr is an rvalue, the rule will be same as the second case (lvalue case), but if expr is an lvalue, the type of A will be an lvalue reference to A.
Note from previous explained, A is never reference, because the type of an expression is never a reference. But for this special case (auto &&, and A is an lvalue), reference to A must be used, regardless expr itself is a reference type or not.
Example:
auto &&s1 = 1; //auto is deducted to int, int &&s1 = 1, ok!
int x = 1;
auto &&s2 = x; //x is lvalue, so A is int &, auto is deducted to int &, int & &&s2 = x; ok!
int &&y = 2;
auto &&s3 = y; //y is lvalue, auto is int &, int & &&s3 = y; ok!

A: Since no one gives an answer and I kinda understand now (thanks to @dyp), I would just post answer myself. Point out error if any:
auto s = expr;

If expr is lvalue, prvalue, or any reference, s is always a lvalue and a copy is made.
auto& s = expr;

If expr is lvalue, lvalue reference or rvalue reference, s is lvalue reference.
If expr is prvalue, it is an error and not legal.
auto&& s = expr;

s is perfectly forwarded (rvalue would become rvalue reference and collapse).


text:
Q: convert numpy array to list of 6 elements where each time the values should shift by one position in python I have a dataset in numpy arrays values
array([0.74, 0.77, 0.72, 0.65, 0.24,
       0.07,0.79,0.88])

I want to convert numpy array to list of 6 elements where each time the values should shift by one position in python
This is the list of list that I want to get.
[[0.74, 0.77, 0.72, 0.65, 0.24,0.07],[0.77, 0.72, 0.65, 0.24, 0.07,0.79],[0.72, 0.65, 0.24,
       0.07,0.79,0.88]]

A: So, it isn't clear how many times you want to shift your array, and why the length of the resulting sublists is what it is. But just use numpy.roll. Something to the effect of:
result = [np.roll(arr, -i)[:-2].tolist()  for i in range(3)]

Based on the comment from @hpaulj I think you want something like:
n = 6 # some paramter
result = [arr[i:i+n].tolist() for i in range(len(arr) - n + 1)]


text:
Q: Selecting a drop-down option using Selenium IDE I'm new to Selenium and having a difficult time selecting options from a drop down list (trying to select the second option).
Here is the HTML that I'm working with:

    Application Reason
    <select name="appstart_international1:applicationReasonTypeID" id="applicationReasonTypeID" class="AppStart dropdown required" title="Application reason">
<option value="0"> </option>
<option value="1">New Application</option>
<option value="2">Additional location</option>
<option value="3">Owner change</option>

I'm using XPath checker to find the XPath, and it's giving me this but it doesn't work when I try and click or select command
id('applicationReasonTypeID_listbox')/x:li[2]
What should the proper Target be for finding an option like this using XPath?
Thanks Kindly!

A: If you know the text that will be in the field this is how I do it:
new Select(driver.findElement(By.id("applicationReasonTypeID"))).selectByVisibleText("New Application");

Hope that might help.
edit to add correct id and text from code provided.

A: What's wrong with either of the following?
new SelectElement(driver.FindElement(By.Id("CustomerDropDown"))).SelectByText("Nationwide");
new SelectElement(driver.FindElement(By.Id("CustomerDropDown"))).SelectByIndex(1);

A: I actually figured out the problem - it's an issue with Kendo UI not supporting drop-downs properly.  Basically the workaround is the click the drop-down arrow, then use sendKeys and point to the same Target as the drop-down with the value being whatever item you want from the list, then clicking the drop-down again.  This worked for me, hopefully it helps somebody else!


text:
Q: setAdapter(new ArrayAdapter.... Doesn't work Hello i get The constructor ArrayAdapter(FragmentBlue, int, String[]) is undefined
in this particular code
package com.example.babycare;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.support.v4.app.Fragment;

public class FragmentBlue extends Fragment implements FragmentLifecycle {

    private String[] drawerListViewItems;
    private ListView drawerListView;

    private static final String TAG = FragmentBlue.class.getSimpleName();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_blue, container, false);
        return view;

        drawerListViewItems = getResources().getStringArray(R.array.items);

        View rootView = inflater.inflate(R.layout.fragment_blue, container, false);
        drawerListView = (ListView)rootView.findViewById(R.id.drawer);

        drawerListView.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_listview_item, drawerListViewItems));
    }

    @Override
    public void onPauseFragment() {
        Log.i(TAG, "onPauseFragment()");
    }

    @Override
    public void onResumeFragment() {
        Log.i(TAG, "onResumeFragment()");

    }
}

Any help will be greatly appreciated.

A: since you are using a fragment you have to get the activity context:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_blue, container, false);

    drawerListViewItems = getResources().getStringArray(R.array.items);

    View rootView = inflater.inflate(R.layout.fragment_blue, container, false);
    drawerListView = (ListView)rootView.findViewById(R.id.drawer);

    drawerListView.setAdapter(new ArrayAdapter<String>(getActivity(),
            R.layout.drawer_listview_item, drawerListViewItems));

    return view;
}

A: I think you need
drawerListView.setAdapter(new ArrayAdapter<String>(getActivity,
                R.layout.drawer_listview_item, drawerListViewItems));

instead of
drawerListView.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_listview_item, drawerListViewItems));

Replace this with getActivity


text:
Q: Bind ListBox (or Telerik RadListPicker) to Enum I have an enum:
public enum UnitOfMeasure
{
    Meters,
    Kilometers,
    Yards,
    Miles,
    Time
}

and I want to bind it to a ListBox (actually a Telerik RadListPicker, but it works the same):
<telerikInput:RadListPicker
    Header="Measure work in:"
    ItemsSource="{Binding WorkUnitOfMeasure}"
    HeaderStyle="{StaticResource HeaderStyle}"
    x:Name="workUnitsListPicker"
    Margin="18">
</telerikInput:RadListPicker>

My View Model:
/// <summary>
/// The <see cref="WorkUnitOfMeasure" /> property's name.
/// </summary>
public const string WorkUnitOfMeasurePropertyName = "WorkUnitOfMeasure";

private ObservableCollection<Enum<UnitOfMeasure>> _workUnitOfMeasure;
/// <summary>
/// Gets the WorkUnitOfMeasure property.
/// Changes to that property's value raise the PropertyChanged event.
/// This property's value is broadcasted by the Messenger's default instance when it changes.
/// </summary>
public ObservableCollection<Enum<UnitOfMeasure>> WorkUnitOfMeasure
{
    get
    {
        return _workUnitOfMeasure;
    }
    set
    {
        if (_workUnitOfMeasure == value)
        {
            return;
        }
        var oldValue = _workUnitOfMeasure;
        _workUnitOfMeasure = value;
         RaisePropertyChanged(WorkUnitOfMeasurePropertyName);
    }
}

And in my constructor I have tried variations of something like this:
WorkUnitOfMeasure = new ObservableCollection<Enum<UnitOfMeasure>>();

I can't seem to get the listbox to bind to Enum.  I know I'm missing something simple, but I can't figure it out.

A: I believe it should be an
ObservableCollection<UnitOfMeasure>

not
ObservableCollection<Enum<UnitOfMeasure>

If not what error are you seeing?

A: If you are binding the single enum items to listbox:
Following code may help you:
 List<string> newList = new List<string>();
        for (int i = 0; i <= (int)UnitOfMeasure.Time; i++)
            newList.Add(Enum.GetName(typeof(UnitOfMeasure), i));
        SampleList.ItemsSource = newList;


text:
Q: Add android support library v4 to intellij ide I am trying to use viewpager from android support library v4 in intelli j. Currently, I am using the Android SDK 4.1
I copied android-support-v4.jar to my intellij android project under 'libs'
in the project settings of intellij
I went to "Modules" => "MyModuleName" => dependencies tab, and add the android-support-v4.jar, by navigating the path to the libs/ folder under my own project
I checked the 'export' besides this newly added jar file
but I still can't use viewpager in my application.
I get a crash msg like:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxx/com.xxxx.MyActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class android.support.v4.view.ViewPager

A: I've inspected the project you provided and found the problem to be caused by the incorrect library configuration. When adding a library, you've specified android folder inside the jar instead of specifying the jar itself.
Incorrect configuration:

Correct configuration:


text:
Q: Giving right answer for N = 2000000 but not passing test cases Find the sum of all prime numbers not greater than N. For example if user input 5 then prime numbers are 2,3,5 and their sum is 10. It is not passing 4 test cases in which two of them are exceeding the time limit. I have tried several test cases and my code is working fine on them. Here is my code.
public static long sieve_of_eratosthenes(long n)
{
    if (n == 1)
    {
        // If the user input 1.
        return (0);
    }
    else
    {
        long sum = 0;
        bool[] array = new bool[n + 1];
        for (long i = 2; i <= n; i++)
        {
            // Setting all values to true.
            array[i] = true;
        }
        // Eliminating the composite numbers.
        for (long j = 2; j < Math.Sqrt(n); j++)
        {
            if (array[j])
            {
                long multiple = 1;
                for (long k = (j * j); k <= n; k = (j * j) + (j * (multiple++)))
                {
                    array[k] = false;
                }
            }
        }
        //Now we have the prime numbers. We just have to add them.
        for (int z = 2; z <= n; z++)
        {
            if (array[z])
            {
                sum = sum + z;
            }
        }
        return (sum);
    }
}

static void Main(string[] args)
{
    int noofcases = int.Parse(Console.ReadLine());
    for( int i = 0; i < noofcases; i ++)
    {
        long entry = long.Parse(Console.ReadLine());
        Console.WriteLine(sieve_of_eratosthenes(entry));
    }
}

A: check the below code. I wrote simple logic which you can improve
public static class Int32Extension
{
    public static bool IsPrime(this int number)
    {
        if (number <= 1) return false;
        if (number == 2) return true;
        if (number % 2 == 0) return false;

        var boundary = (int)Math.Floor(Math.Sqrt(number));

        for (int i = 3; i <= boundary; i += 2)
            if (number % i == 0)
                return false;

        return true;
    }
}

then
static void Main(string[] args)
{
    int input = 5;
    int sum = 0;

    for (int i = 0; i < input;)
    {
        if (!(++i).IsPrime())
            continue;

        sum += i;
    }

    Console.WriteLine(sum);
}

Without using Extension Method
public static bool IsPrime(int number)
{
    if (number <= 1) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;

    var boundary = (int)Math.Floor(Math.Sqrt(number));

    for (int i = 3; i <= boundary; i += 2)
        if (number % i == 0)
            return false;

    return true;
}

static void Main(string[] args)
{
    int input = 5;
    int sum = 0;

    for (int i = 0; i < input;)
    {
        if (!IsPrime(++i))
            continue;

        sum += i;
    }

    Console.WriteLine(sum);
}

.Net Fiddle Link : https://dotnetfiddle.net/rEBY9r
Edit : The IsPrime test uses Primality Test With Pseudocode


text:
Q: Is the Webkit inspector (developer tools) a suitable replacement for Firebug yet? The Safari & Chrome developer tools (webkit inspector) seem to have become quite advanced. Although I'm very used to Firebug and rely on it for development, I'm really flirting with the idea of trying to just make a complete switch to Chrome (since I browse almost exclusively with it anyway) and just learn to get use to it's web developer tools.
It functions a little differently than Firebug, and I have noticed that you can easily modify values in the markup or CSS rules on the fly. So apart from any basic differences in the interface, has the webkit web inspector become a suitable replacement for firebug yet?
NOTE I'm asking my question from the standpoint of a front end designer/developer doing primarily HTML & CSS work; I don't even really get into javascript much - yet.

A: A big YES ;-) and even for javascript debugging.
Since Chrome 6 I never needed to switch back to firebug when debugging.
And profiling tools are simply awesome.


text:
Q: Solving a set of equations with Newton-Raphson I want to solve this set of equations with Newton-Raphson.
Can anybody help me?
$$ \cos(x_1)+\cos(x_2)+\cos(x_3)= \frac{3}{5} $$
$$ \cos(3x_1)+\cos(3x_2)+\cos(3x_3)=0 $$
$$ \cos(5x_1)+\cos(5x_2)+\cos(5x_3)=0 $$
Best regards.

A: I am going to jump start you, but you need to show some work.
The regular Newton-Raphson method is initialized with a starting point $x_0$ and then you iterate $x_{n+1}=x_n-\dfrac{f(x_n)}{f'(x_n)}$.
In higher dimensions, there is an exact analog. We define:
$$F\left(\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix}\right) = \begin{bmatrix}f_1(x_1,x_2,x_3) \\  f_2(x_1,x_2,x_3)  \\ f_3(x_1,x_2,x_3)\end{bmatrix} = \begin{bmatrix}\cos x_1 + \cos x_2 + \cos x_3 -\dfrac{3}{5} \\   \cos 3x_1 + \cos 3x_2 + \cos 3x_3  \\ \cos 5x_1 + \cos 5x_2 + \cos 5x_3  \end{bmatrix}= \begin{bmatrix}0\\0\\0\end{bmatrix}$$
The derivative of this system is the $3x3$ Jacobian given by:
$$J(x_1,x_2,x_3) = \begin{bmatrix} \dfrac{\partial f_1}{\partial x_1} & \dfrac{\partial f_1}{\partial x_2} & \dfrac{\partial f_1}{\partial x_3}\\ \dfrac{\partial f_2}{\partial x_1} & \dfrac{\partial f_2}{\partial x_2} & \dfrac{\partial f_2}{\partial x_3} \\ \dfrac{\partial f_3}{\partial x_1} & \dfrac{\partial f_3}{\partial x_2} & \dfrac{\partial f_3}{\partial x_3}\end{bmatrix} = \begin{bmatrix} -\sin x_1 & -\sin x_2 & -\sin x_3 \\ -3\sin 3x_1 & -3\sin 3x_2 & -3\sin 3x_3 \\ -5\sin 5x_1 & -5\sin 5x_2 & -5\sin 5x_3 \end{bmatrix}$$
The function $G$ is defined as:
$$G(x) = x - J(x)^{-1}F(x)$$
and the functional Newton-Raphson method for nonlinear systems is given by the iteration procedure that evolves from selecting an initial $x^{(0)}$ and generating for $k \ge 1$,
$$x^{(k)} = G(x^{(k-1)}) = x^{(k-1)} - J(x^{(k-1)})^{-1}F(x^{(k-1)}).$$
We can write this as:
$$\begin{bmatrix}x_1^{(k)}\\x_2^{(k)}\\x_3^{(k)}\end{bmatrix} = \begin{bmatrix}x_1^{(k-1)}\\x_2^{(k-1)}\\x_3^{(k-1)}\end{bmatrix} + \begin{bmatrix}y_1^{(k-1)}\\y_2^{(k-1)}\\y_3^{(k-1)}\end{bmatrix}$$
where:
$$\begin{bmatrix}y_1^{(k-1)}\\y_2^{(k-1)}\\y_3^{(k-1)}\end{bmatrix}= -\left(J\left(x_1^{(k-1)},x_2^{(k-1)},x_3^{(k-1)}\right)\right)^{-1}F\left(x_1^{(k-1)},x_2^{(k-1)},x_3^{(k-1)}\right)$$
Here is a starting vector:
$$x^{(0)} = \begin{bmatrix}x_1^{(0)}\\x_2^{(0)}\\x_3^{(0)}\end{bmatrix} = \begin{bmatrix}1\\2\\3\end{bmatrix}$$
You should end up with a solution that looks something like:
$$\begin{bmatrix}x_1\\x_2\\x_3\end{bmatrix} = \begin{bmatrix} 4.094047142323228 \\ 1.2318378396357232 \\ -0.5601417633888767 \end{bmatrix}$$
Of course, for a different starting vector you are going to get a different solution and perhaps no solution at all.

A: I attempted the same iteration using Excel starting with an initial guess of $x = [1,2,3]$.  The final result was $x = [-60.64267241, 76.62997198, 43.42206157]$. However, when I started with an initial guess closer to your final result, Excel yielded similar results.


text:
Q: Is there a way to allow "undefined" hashes in params without permitting everything? I have a model that serializes a Hash called current_values as JSON in the database. The model looks like this:
class Template
  belongs_to :user
  serialize :current_values, JSON
  # has attributes title and description
  # ...
end

Now I want to create a new Template, and the controller looks like this:
class TemplateController < ApplicationController
  # ...
  def create
    template = Template.new(template_params)
    template.save
    # ...
  end

  private

  def template_params
    params.require(:template).permit(:title,
                                     :description,
                                     :current_values)
  end
  # ...
end

If I use this code with params that look like this:
"template" => {
  "title" => "title",
  "description" => "description",
  "current_values" => {
    "foo" => "foo",
    "bar" => "bar"
  }
}

I get this error message:
Unpermitted parameters: current_values

I have read the documentation for permit on http://api.rubyonrails.org/ but I cannot figure out how I can allow any value for current_values without allowing everything with permit!. I do not know which attributes will be in current_values, thus I cannot pass an array with the allowed attributes. and I do not want to allow everything because then someone could overwrite :user_id.

A: To solve this problem you have to change the method:
def template_params
  params.require(:template).permit(:title,
                                   :description,
                                   :current_values)
end

to:
def template_params
  params.require(:template).permit(:title,
                                   :description).tap do |whitelisted|
    whitelisted[:current_values] = params[:template][:current_values]
  end
end


text:
Q: WPF Mediaelement freezes while repeating position property for fastforward Requirement is to create a fast forward button which will forward the video continuously. I am using the position property by adding timespan while doing fast-forward of video. While forwarding manually(click by click), for each button click, it executes ones and media moves by timespan amt. The problem is if I click the fast forward button multiple times (around 10 times), the media freezes. There is also a seek bar that continues to progresses without issue. However the media element freezes.
XAML
<MediaElement x:Name="Mediaelement" LoadedBehavior="Manual" ScrubbingEnabled="True"  MediaOpened="MediaOpened" UnloadedBehavior="Manual" Source="{Binding MediaFile}"/>

Code in View Model
private void  FastForward()
    {
          Mediaelement.Position += TimeSpan.FromMilliseconds(100);
    }

I also tried mimicking continuous forward using the below code. But this is also resulting in frame freeze after few(~10) frame moves
Code:
private async void  FastForward()
    {
        do
        {
        Mediaelement.Position += TimeSpan.FromMilliseconds(100);
        await Task.Delay(1000);
        } while (MediaelementPosition < Mediaelement.NaturalDuration.TimeSpan);
    }

I do use a DispatcherTimer and TimerTick to synchronize seeker/progress bar with the media element. That is working fine but not sure if that has to any effect in frame freeze.
Frame is not freezing at the end or at the beginning. It's happening in the middle where the next frame supposed to show up. I have also play and pause functionalities which are working as expected.
Any suggestion/guidance will be appreciated.


text:
Q: Android compose snackbar showing again on config changes I want to display a snackbar once, on android compose, but as soon as I change the screen rotation, the snackbar shows again, i took this example from official android documentation and it is doing the same thing:
@Composable
fun LoginScreen(
    state: Boolean = true,
    scaffoldState: ScaffoldState = rememberScaffoldState()
) {
    // If the UI state contains an error, show snackbar
    if (state) {

        // `LaunchedEffect` will cancel and re-launch if
        // `scaffoldState.snackbarHostState` changes
        LaunchedEffect(scaffoldState.snackbarHostState) {
            // Show snackbar using a coroutine, when the coroutine is cancelled the
            // snackbar will automatically dismiss. This coroutine will cancel whenever
            // `state.hasError` is false, and only start when `state.hasError` is true
            // (due to the above if-check), or if `scaffoldState.snackbarHostState` changes.
            scaffoldState.snackbarHostState.showSnackbar(
                message = "Error message",
                actionLabel = "Retry message"
            )
        }
    }

    Scaffold(scaffoldState = scaffoldState) {
    }
}

My question is: How do you display a snackbar once with a side effect even if the rotation changes?

A: For example, you can save the state to a local variable using rememberSaveable and set it to false when the snackbar disappears.
var localState by rememberSaveable(state) { mutableStateOf(state) }
// If the UI state contains an error, show snackbar
if (localState) {

    // `LaunchedEffect` will cancel and re-launch if
    // `scaffoldState.snackbarHostState` changes
    LaunchedEffect(scaffoldState.snackbarHostState) {
        // Show snackbar using a coroutine, when the coroutine is cancelled the
        // snackbar will automatically dismiss. This coroutine will cancel whenever
        // `state.hasError` is false, and only start when `state.hasError` is true
        // (due to the above if-check), or if `scaffoldState.snackbarHostState` changes.
        scaffoldState.snackbarHostState.showSnackbar(
            message = "Error message",
            actionLabel = "Retry message"
        )
        localState = false
    }
}


text:
Q: Does Stack Exchange use a single database for all its sites? Or does it have a different instance for each? All in the question title.

A: If you are asking if it uses the same database server, then most likely yes. High performance servers are very expensive and most (if not all) of the stack exchange websites don't warrant or need a dedicated db server just for themselves.
If you are asking if it uses the same database ("database" as in CREATE DATABASE abc) then no. It uses different "instances". Using the same actual database makes performance worse and implementation more difficult.


text:
Q: How do you show an animated progress bar and animated command line in VimScript? I'm wondering how you could get the same moving progress bar you see
when you run :TOhtml on a big file using VimScript.
Also, when you do :vimgrep, you can see the files displayed in
succession in the command window. How does one create this kind of
progressive command window update using VimScript?

A: Take a look at this question. It might lead you in the right direction. You're likely interested in the echo command :help echo


text:
Q: EZLoadingActivity giving issue on Carthage Update in Swift I have opened project after 5 months.
Setup it in new macbook. Cloned porject.
Now when i go to set dependencies using Carthage. Cartfile is same is before and code was working 5 months ago.
now i am able to get all my dependencies. But EZLoadingActivity giving error on carthage update.
Pasting terminal console here:
*** Building scheme "EZLoadingActivity_iOS" in EZLoadingActivity.xcodeproj
Build Failed
Task failed with exit code 65:
/usr/bin/xcrun xcodebuild -project /Users/mac/Git/project-ios/Carthage/Checkouts/EZLoadingActivity/EZLoadingActivity.xcodeproj -scheme EZLoadingActivity_iOS -configuration Release -derivedDataPath /Users/mac/Library/Caches/org.carthage.CarthageKit/DerivedData/10.3_10G8/EZLoadingActivity/2.1 -sdk iphoneos ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive -archivePath /var/folders/gb/tm7hcwvs05s3zkqdp1lndwgm0000gn/T/EZLoadingActivity SKIP_INSTALL=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO CLANG_ENABLE_CODE_COVERAGE=NO STRIP_INSTALLED_PRODUCT=NO (launched in /Users/mac/Git/project-ios/Carthage/Checkouts/EZLoadingActivity)
This usually indicates that project itself failed to compile. Please check the xcodebuild log for more details: /var/folders/gb/tm7hcwvs05s3zkqdp1lndwgm0000gn/T/carthage-xcodebuild.hbqgmp.log

Also pasting logs as mentioned here /var/folders/gb/tm7hcwvs05s3zkqdp1lndwgm0000gn/T/carthage-xcodebuild.hbqgmp.log
 /usr/bin/xcrun xcodebuild -project /Users/mac/Git/arteciate-ios/Carthage/Checkouts/EZLoadingActivity/EZLoadingActivity.xcodeproj -scheme EZLoadingActivity_iOS -configuration Release -derivedDataPath /Users/mac/Library/Caches/org.carthage.CarthageKit/DerivedData/10.3_10G8/EZLoadingActivity/2.1 -sdk iphoneos ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive -archivePath /var/folders/gb/tm7hcwvs05s3zkqdp1lndwgm0000gn/T/EZLoadingActivity SKIP_INSTALL=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO CLANG_ENABLE_CODE_COVERAGE=NO STRIP_INSTALLED_PRODUCT=NO (launched in /Users/mac/Git/arteciate-ios/Carthage/Checkouts/EZLoadingActivity)User defaults from command line:
IDEArchivePathOverride = /var/folders/gb/tm7hcwvs05s3zkqdp1lndwgm0000gn/T/EZLoadingActivity
IDEDerivedDataPathOverride = /Users/mac/Library/Caches/org.carthage.CarthageKit/DerivedData/10.3_10G8/EZLoadingActivity/2.1

Build settings from command line:
CARTHAGE = YES
CLANG_ENABLE_CODE_COVERAGE = NO
CODE_SIGN_IDENTITY =
CODE_SIGNING_REQUIRED = NO
GCC_INSTRUMENT_PROGRAM_FLOW_ARCS = NO
ONLY_ACTIVE_ARCH = NO
SDKROOT = iphoneos12.4
SKIP_INSTALL = YES
STRIP_INSTALLED_PRODUCT = NO

note: Using new build system
note: Planning build
note: Constructing build description
Build system information
error: SWIFT_VERSION '3.0' is unsupported, supported versions are: 4.0, 4.2, 5.0. (in target 'EZLoadingActivity_iOS')

Build system information
error: SWIFT_VERSION '3.0' is unsupported, supported versions are: 4.0, 4.2, 5.0. (in target 'EZLoadingActivity_iOS')

Please guide me how to resolve it so i can use EZLoadingActivity libraray in my project and can able to run my project.


text:
Q: library module upgrade to Glide 4, where should the AppGlideModule be put in In library module to upgrade to Glide 4.9.0.
    api "com.github.bumptech.glide:glide:4.9.0"
    api "com.github.bumptech.glide:annotations:4.9.0"
    annotationProcessor "com.github.bumptech.glide:compiler:4.9.0"

and having a kotlin extension
fun ImageView.loadImg(imageUrl: String) {
    // 4.+ code
    var requestOptions : RequestOptions = RequestOptions()
            .placeholder(ColorDrawable(Color.LTGRAY))
            .diskCacheStrategy(DiskCacheStrategy.ALL)

    if (!TextUtils.isEmpty(imageUrl)) {
        Glide.with(context)
                .setDefaultRequestOptions(requestOptions)  // or use .apply(requestOptions) but after the .load()
                .asBitmap()
                .load(imageUrl)
                .into(this)
    }
}

but it crashes

    java.lang.AbstractMethodError: abstract method "void com.bumptech.glide.module.RegistersComponents.registerComponents(android.content.Context, com.bumptech.glide.Glide, com.bumptech.glide.Registry)"
            at com.bumptech.glide.Glide.initializeGlide(Glide.java:270)
            at com.bumptech.glide.Glide.initializeGlide(Glide.java:223)
            at com.bumptech.glide.Glide.checkAndInitializeGlide(Glide.java:184)
            at com.bumptech.glide.Glide.get(Glide.java:168)
            at com.bumptech.glide.Glide.getRetriever(Glide.java:689)
            at com.bumptech.glide.Glide.with(Glide.java:716)
            at com.common.extentions.ExtensionsKt.loadImg(Extensions.kt:44)

After adding
 @GlideModule
 class TheAppGlideModule : AppGlideModule() {
     override fun isManifestParsingEnabled(): Boolean {
         return false
     }
 }

to the library module does not help, or adding it to hosting app only does not work either,
 but after adding it to both the library module and the hosting app the crash goes away.
according to documentation https://bumptech.github.io/glide/doc/generatedapi.html,
 isnt it that it not supposed to have this class defined in the library module?
anyone has same experience?
  * For now the API is only generated when a properly annotated AppGlideModule is found.
  * There can only be one AppGlideModule per application.
  * As a result it's not possible to generate the API for a library without precluding any application
  * that uses the library from using the generated API.

A: Resolved, it has missed
api "com.github.bumptech.glide:annotations:$versions.glide"

in the application side (not sure why adding single one in the module did not work and why with both it worked, maybe didnt do clear/rebuild after change?)


text:
Q: Banding appears when reprojecting shapefiles using R? I have downloaded a shape file (Marine Ecoregions (last one on the page)) from the nature conservancy http://maps.tnc.org/gis_data.html
I am then using R and the sf package to project this shapefile. If I plot this map on NAD83, WGS84 etc., the map looks good. If I project it to Eckert4, Lambert Azithmuthal, or Mollweide I get banding across the map.
Any idea why this happens?
Here is some reproducible code:
You will need to download the shapefile from the link above and add them to same folder as the function below
# set chooseProjection to one of the following" "WGS84","Eckert4","molli","lambertaz"
project_maps <- function(chooseProjection) {

  projection <- switch(chooseProjection,
                       "WGS84" = "+init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0",
                       "NAD83" = "+init=epsg:4269 +proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs +towgs84=0,0,0",
                       "NAD27" = "+init=epsg:4267 +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs +nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",
                       "Eckert4" = "+proj=eck4",
                       "molli" = "+proj=moll",
                       "tranmerc"= "+proj=tmerc",
                       "lambertaz"="+proj=laea +x_0=0 +y_0=0 +lon_0=0 +lat_0=0")
  MEco <- sf::st_read(dsn=here::here(),layer="meow_ecos",quiet=T)
  MEco <- sf::st_transform(MEco,crs=projection)

  # plot ecoregion
  plotMEco <- ggplot2::ggplot() +
    ggplot2::geom_sf(data = MEco, ggplot2::aes(fill = ECOREGION)) +
    ggplot2::theme(legend.position = "none") +
    ggplot2::ggtitle("Marine Ecoregions")
  print(plotMEco)
}

Sample figures:

If i crop the bounding box using
MEco <- sf::st_crop(MEco,c(ymin = -89.99, ymax = 89.99, xmin=-179.99, xmax=179.99))

Then the Eckert4 projection displays just fine. However the Lambert Azithmuthal is still strange.

A: The problem with this:
plot(st_transform(MEco$geom,laea))

is that some of the vertices are quite far apart in lat-long, and even more far apart in LAEA, so you get a big straight line joining them rather than following the true projected shape. Add more vertices to your shapes with st_segmentize:
plot(st_transform(st_segmentize(MEco$geom,10000),laea))

and the problem disappears as the more finely vertexed polygon transforms correctly. The parameter value (10000 above) needs setting according to your data and projection. Too large and you don't get any effect, too small and you add zillions of vertices that don't help.


text:
Q: Standard Category of Components gone walkabout Somehow I managed to delete the Standard category of components from my RIO IDE.
How do I recover from this?

A: Depends on what you did.
Deleted the palette category? Right click in the palette area and select "Reset Palette".
Unselected the standard components package? Component menu, install packages. In the list make sure the Embarcadero Standard Components package is selected.
Deleted random files in the install directory? Reinstall Delphi.
Started a command line project? There are no standard components for this type of project.


text:
Q: WSO2 API Manager 1.4.0 Management Console I downloaded and installed the WSO2 API Manager version 1.4.0 yesterday and I cannot login to the web management console (https://localhost:9443/carbon) using the default credentials (i.e. admin/admin)
I can login to the API store and API publisher and the error comes only for the management console.
Note that I performed the default install (unzip and ran ./wso2server.sh from the bin folder)
Following is part of the error stacktrace
2013-06-03 15:42:13,095]  INFO - CarbonAuthenticationUtil 'admin@carbon.super [-1234]' logged in at [2013-06-03 15:42:13,095+1000]

[2013-06-03 15:42:13,112] ERROR - AuthenticationHandler System error : 0 active authenticators registered in the system. The system should have at least 1 active authenticator service registered.
java.lang.RuntimeException: System error : 0 active authenticators registered in the system. The system should have at least 1 active authenticator service registered.
    at org.wso2.carbon.server.admin.module.handler.AuthenticationHandler.isAuthenticated(AuthenticationHandler.java:144)
    at org.wso2.carbon.server.admin.module.handler.AuthenticationHandler.authenticate(AuthenticationHandler.java:83)

Further down the stacktrace, I also get the below

[2013-06-04 11:42:15,860] ERROR - AxisEngine Authentication failure
org.apache.axis2.AxisFault: Authentication failure
    at org.wso2.carbon.server.admin.module.handler.AuthenticationHandler.authenticate(AuthenticationHandler.java:110)
    at org.wso2.carbon.server.admin.module.handler.AuthenticationHandler.invoke(AuthenticationHandler.java:55)
    at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:340)
    at org.apache.axis2.engine.Phase.invoke(Phase.java:313)

I also get the following two warning messages on startup
[2013-06-04 11:14:05,489]  WARN - ValidationResultPrinter Swap Memory size (MB): 64 of the system is below the recommended minimum size :2048

[2013-06-04 11:14:15,444]  WARN - LandingPageWebappDeployer Product landing page not found.

A: @nuwandias Hi Nuwan.
I identified the issue. When I was evaluating the previous 1.3.1 version, I injected the Authorization header with the Bearer token via my Firefox browser plugin.
That was what caused the problem with the 1.4.0 version. Once I disable it it works fine.
All good now and I am looking forward to doing a deep dive evaluation of this product.
Thanks a lot for your support.

A: I have just downloaded the zip from the website and tried the same and it worked fine. Can you please provide the following information.

*

*What is the environment that you are trying this on (OS)?

*What is the md5sum value of the zip archive? Mine is fea68eaadd17daa5e6fa0aff3d973601.

*Do you see any errors/warnings on startup? If so, could you share the startup logs too?

Thanks,
Nuwan.

A: Looking at this log message...
Swap Memory size (MB): 64 of the system is below the recommended minimum size :2048
It seems like your hard drive (or partition) has filled up. I'm wondering whether this could have caused any errors when you unzipped the zip file (if the hard disk has no free space).
If this is the case, can you free up some space (>200MB) in your partition, unzip the archive again and retry?


text:
Q: Does IBM have a cloud hosting service that can be used to host worklight server/applications? In IBM developer works blog, I have read a post on using IBM PureApplication system to deploy Worklight server and applications to cloud.
Does IBM have a cloud hosting service as well?

A: Start by looking at: http://www.ibm.com/cloud-computing/us/en/
IBM provides various ways to run the IBM MobileFirst Platform (formerly Worklight) as a hosted service.
Some of them are unmanaged (you have to do your own IT). Some are managed.
The basic option is to go to Softlayer and create an unmanaged Worklight instance.
Look at http://www.ibm.com/marketplace/cloud/mobile-application-platform-pattern/us/en-us which is how IBM provides Worklight as a service, hosted on Softlayer, installed via PureApplications managed below and services by IBM Global technology unit.
Finally, IBM is in the process of providing the Worklight as a fully managed, cloud service via the IBM cloud called "Bluemix" https://console.ng.bluemix.net/  . A beta of a mobile data service, push service, mobile analytics and mobile security will appear in Bluemix by the end of this week. Note that the latest option is currently for iOS apps only


text:
Q: Create a file based on inputs provided in jenkins I am trying to execute a curl command using jenkins, but I need to provide a json file while executing that curl.
I want to build up that file dynamically using the values passed in parameters while executing the build.
Example json file:
{
"field1": "value1"
"field2": "value2"
}
These values will be dynamic i.e it will be passed as parameters when doing the build.
Please guide me through this.

A: It can be done like
pipeline {
    agent any;
    parameters {
        string(name: 'NAME', defaultValue: 'Mr X', description: 'Who should I say hello to?')
        string(name: 'LOCATION', defaultValue: 'NYC', description: 'Where should I report this to?')
    }
    stages {
        stage('curl') {
            steps {
                writeJSON file: 'data.json', json: params

                sh """
                    curl -X POST -H "Content-Type: application/json" -d @data.json http://api.xyz.net

                """
            }
        }
    }
}

Note - for DSL writeJSON need pipeline-utility-steps plugins to be installed or By using native groovy api you can parse params object to JSON.


text:
Q: PowerShell to zip WordPress plugin I have a folder containing the code for a WordPress plugin, and the following script:
$folder = Join-Path $PSScriptRoot $pluginName
$destination = Join-Path $PSScriptRoot "bundles/$pluginName.zip"
Add-Type -AssemblyName "System.IO.Compression.FileSystem"

if (Test-Path $destination) {
    Remove-Item $destination
}

[IO.Compression.ZipFile]::CreateFromDirectory(
    $folder,
    $destination,
    [IO.Compression.CompressionLevel]::Optimal,
    $true # include base directory
)

If I try to install the plugin by uploading the produced zip file to a local WordPress instance, I get the following errors:

Warning: copy(/var/www/html/wp-content/plugins/jwt-authentication-for-wp-rest-api/jwt-authentication-for-wp-rest-api\jwt-auth.php): failed to open stream: Invalid argument in /var/www/html/wp-admin/includes/class-wp-filesystem-direct.php on line 257
Warning: copy(/var/www/html/wp-content/plugins/jwt-authentication-for-wp-rest-api/jwt-authentication-for-wp-rest-api\jwt-auth.php): failed to open stream: Invalid argument in /var/www/html/wp-admin/includes/class-wp-filesystem-direct.php on line 257
Could not copy file. /var/www/html/wp-content/plugins/jwt-authentication-for-wp-rest-api/jwt-authentication-for-wp-rest-api\jwt-auth.php
Plugin install failed.

However, if I manually zip the plugin, by right-clicking the plugin folder in Windows Explorer and choosing "Send to..." -> "Compressed folder", the generated zip file installs fine.
I can't figure out why this happens, because if I unzip the folders and diff their contents, they are identical. (The zipped files are not, but I assume that's because of compression levels etc).
Do I have to set any specific flags when zipping to make this work? How do I script production of a zip file that works exactly like "Send to..." -> "Compressed folder"?


text:
Q: Since more than six months As per English grammar, 'Since' is used to show the time period in the past from which the event is happening.  So, is the sentence given below correct?

"Since more than six months, I have been directly assisting Steve as a Project Manager"

A: Technically, according to your definition, this sentence would be (sort of) correct. However, the usage of the word 'since' in this case feels out of place and really should be written as:
"For more than six months, I have been directly assisting Steve as a Project Manager."

A: Your "rule" is wrong. 'Since' is used to indicate a point in time past from which, not a period during which. 'For' is used to indicate a period.

I've only been married to Sally since July 1st.
It seems as though I've been married to her for æons.

The phrase 'as per' should be avoided. It strikes people as pompous and stilted. Say instead, "according to [the rules of] English grammar."
Don't capitalize 'project manager' unless it's an official title. (Speakers of British English may think differently about this, though).

A: It's not advisable to use 'since' like you have done, though it may still be correct.
You can use

I have been assisting Mr. XYZ for more than six months.

Or if you want to make a point that you have been assisting someone for a specific period of time, you can use

I have been assisting Mr. XYZ since January.

Assume January is six months before the current month.


text:
Q: VBA equivalent to Excel's "Search()" I have an assignment I need some help with. There are three columns: Column A(username), Column B(Category), and Column C(note). I have to create a Sub that checks each cell down Column B according to category (for example Admin). If the string, "Admin", is found in B2 for example, then the A2 is searched for either:"john.deer", "BES", or "mars". If "john.deer" is found then C2 is to say "Domain Admin Account", if "BES" is found then C2 is to say "BES Admin Account" etc.
However if "Admin" is not found in Column C then "SQL" is searched in C2. If "SQL" is found then "SQL Server", "SQL Engine", and "SQL Cluster" is searched in A2. The exact same task as the previous paragraph except different strings are searched in Column B and A. Different strings are outputted to Column C as well.
I had an equation that was perfect and just needed to create an equivalent for VBA:
=IF(NOT(ISERROR(SEARCH("admin",B3))),IF(NOT(ISERROR(SEARCH("john.deer",A3))),"Domain Admin Account",if(not(iserror(search("bes",a2))),"BES  Admin Account", if(not(iserror(search("mars",a2))),"Cisco Admin Account","no category"),IF(NOT(ISERROR(SEARCH("SQL",B3))),IF(NOT(ISERROR(SEARCH("sqlserver",A3))),"SQL Server",IF(NOT(ISERROR(SEARCH("sqlengine",B3))),"SQL Engine Account"," ")))

As you can tell its a mess, which is why I wish to create a VBA equivalent. However, there is no Search() object in VBA, only .Find.
Here is my attempt at VBA before realizing Search did not work:
    Private Sub CommandButton21_Click()

If Not IsError Then
    If Search("ADMIN", "B2") Then 'Searches Col. F for "Admin", then Col. B for type of admin before
                                'populating Notes Col. with specific Note

    If Not IsError Then
        Search("john.deer", "A2") = "Domain Admin Account"
    ElseIf Not IsError Then
        Search("BES", "A2") = "BES Admin Account"
    ElseIf Not IsError Then
        Search("mars1", "A2") = "Admin Account for Cisco Phone System"
    Else
  End If

If Search("admin", "B2") Then
    If Not IsError Then
        Search("uccxadmin", "b2") = "Admin Account for Cisco phone system"

End If
end if
end sub

A: Instr is the VBA eqivalent
dim Pos as long
Pos=Instr(Range("B2"),"ADMIN")
if pos>0 then 'code if found
else 'notfound
end if

Instr has more options than search: see documentation here.

A: You can use any function available in Excel in your VBA code. You can access this function in Application.WorksheetFunction object: Application.WorksheetFunction.Search. Use the same arguments you would use in the spreadsheet.


text:
Q: Devise, customizing the error messages? I'm using rails 3 with devise.
I have a User table with fields: email, password, fname, lname
I currently output errors in my view as follows:
<% if @user.errors.any? %>

Hold on!

            <% @user.errors.full_messages.each do |msg| %>

<%= msg %>

            <% end %>

<% end %>

Problem is this renders as:
Email The User's Email cannot be blank
Password The User's Password cannot be blank
Fname The User's Fname is too short (minimum 1 characters)
Lname The User's Lname is too short (minimum 1 characters)

How can I get the field name to not appear first with every error?
In my user model I have:
validates :fname, :length => { :minimum => 1, :maximum => 100 }
  validates :lname, :length => { :minimum => 1, :maximum => 100 }
I can customize those fields with a message attribute. What about email and password which appear to be built into devise? How do I customize those error messages?
Thanks

A: http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
validates_presence_of(*attr_names)

 Configuration options:
  message - A custom error message (default is: "can't be blank").

As for the built in names customisation, this thread can help
Rails3: Devise internationalization does not localize "Password confirmation" and others
(to extend)
activerecord:
   attributes:
       user:
        email: "your_way_of_email"
          password: "your_way_of_password"
          password_confirmation: "your_way_of_password_confirmation"

Rails will then humanize them

A: Use each_key to retrieve fields and navigate errors on each field.
<% if @user.errors.any? %>

Hold on!

            <% @user.errors.each_key do |attr| %>
                <% @user.errors[attr].each do |msg| %>
                    <% next if msg.nil? %>

<%= msg %>

                <% end %>
            <% end %>

<% end %>

View the source of full_messages:
http://ar.rubyonrails.org/classes/ActiveRecord/Errors.html#M000311


text:
Q: How to re-export a modified list of imported functions in ES6 I want to create an ES6 module which imports all functions from another module, wraps these functions and exports them again. Sounds easy, but I can't get it working.
Let's start with the module with the functions I want to wrap:
/* funcs.mjs */
export function foo() { return "foo"; };
export function bar() { return "bar"; };
// A lot of more functions following...

And this is a test script which imports and executes two of the many many hypothetical functions in the other module:
/* test.mjs */
import { foo, bar } from "./funcs.mjs";

console.log(foo());
console.log(bar());

I now want to write a wrapper module which imports all functions from funcs.mjs, wrap them into new functions and export these new functions under the original function names. So in the end I want to be able to change the imported module name in test.mjs from funcs.mjs to wrapped-funcs.mjs and then without changing anything else this script must still work and now call the wrapped functions.
The problem I struggle with is that I can't figure out how to export the wrapped functions so they can be imported the same way as importing the original functions:
/* wrapped-funcs.mjs */
import * as funcs from "./funcs.mjs";

const wrapped = Object.entries(funcs).reduce((wrapped, [ name, func ]) => {
    wrapped[name] = () => "wrapped " + func();
    return wrapped;
}, {});

// export wrapped;                     // Invalid
// export { ...wrapped };              // Invalid
// export { wrapped }                  // Not what I want (Exports object with name "wrapped")
// export default wrapped;             // Not what I want (Exports object with name "default")
export const { foo, bar } = wrapped;   // Exports correctly but I have to specify all functions manually

With export { wrapped } and export default wrapped I export all functions but the  module interface is different to what I want so that doesn't work. With export const { foo, bar } = wrapped the exports are structured correctly but this solution has the problem that I have to know all function names within the wrapper module. So that doesn't work, too.
Is there some other clever way to do this with ES6 modules? I know it can be done with CommonJS but that's out-of-scope here.


text:
Q: How to get cross-validated correlation estimate? I have a logistic regression model trained on an outcome variable $y$ and I want to get an estimate of how good the predicted raw probabilities are in terms of aligning with $y$. I realize that logistic regression probabilities should not be expected to show a linear trend with the outcome variable but I would imagine that if it was well-trained, there might be a strong rank correlation at least.
Either way, whether this is a linear or logistic model, what is the best way to assess the correlated strength in a generalizable way? I though about doing 10-fold cross validation and testing the spearman correlation in each fold and averaging those but I don't know if that makes any sense. Is there a better way to do this? Thanks.

A: Logistic regression outputs probabilistic predictions for a new case to belong to the focal class. The standard approach to assess such probabilistic predictions is to use proper scoring-rules. You can find more information and pointers to literature in the tag wiki.


text:
Q: Speed of light measurement using a star mass, just like a satellite orbits the earth This is just an idea than came to my mind last night, would it be possible to, launch a satellite, close enough to the sun (To be safe for it) to light a laser, somewhere close enough to the sun, allowing the sun's mass to curve the light trajectory and making it go all around the sun, catching it back in the satellite, just as the laser were orbiting the sun, like this:
so after all it will be a one way light, and not an refection... Just asking

A: This isn't possible near the Sun, it would require a black hole to make a beam of light go around in an orbit.
It also has the practical difficulty of determining what the distance traveled by the light is, because that close to a black hole both space and time are curved very sharply.
Seriously, the whole "one way speed of light" thing is a red herring. You can certainly measure the one way speed of light given a synchronization convention for clocks. The "problem" is that the synchronization convention is arbitrary -- if you really want to, you can choose a bizarre way of synchronizing clocks that makes the one way speed of light almost anything you want in some particular direction. But any practical and "natural" synchronization convention, such as "slow clock transport", is equivalent to Einstein's convention, in which the one way speed of light is $c$ in all directions.


text:
Q: asp.net core gzip compression dependant on response size We're using gzip compression like:
services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
  services.AddResponseCompression(options =>
  {
    options.Providers.Add<GzipCompressionProvider>();
  });

Since we'd like to avoid compression for small responses, question is if we can somehow configure gzip compression not to be used for response sizes less than XY?

A: The Compression Middleware in ASP.NET Core 2.1 does not seem to provide the ability of compressing data based on content size, so short answer to your question is "No".
However, I understand the main reason  for such setup would be to make the overall request end-to-end faster, which is what the CompressionLevel.Fastest is supposed to do for you already.
ASP.NET Core Compression Middleware considerations.
The GZipCompressionProvider ends up calling the Deflater constructor and CreateZLibStreamForDeflate method where the CompressionLevel enumeration defined in .NET is mapped into the compression level defined into the underlying zlib library used to perform the actual compression. From the zlib manual:

The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6).

According to the way the ASP.NET Core Compression Middleware maps compression levels, as defined in Deflater and ZLibNative, we can deduce the following:

*

*CompressionLevel.Fastest: zlib compression level will be 1, i.e. do it faster, compress less.

*CompressionLevel.Optimal: zlib compression level will be 6, i.e. a compromise between speed and compression.

Note, there is no option mapping into higher zlib compression levels, like 9 which is the highest compression and the most expensive, which would probably make the ASP.NET Core web app spending more time compressing than sending the whole content back to the client.
CompressionLevel usage and overall considerations.
In a web service implementation, compression is just a tool to make things faster, therefore compression should be as light as possible to avoid the case where the compression algorithm spends more time than what it would take for the network to deliver the payload not compressed.
The way I see it, CompressionLevel.Fastest works best as in most cases it guarantees the client to receive a quicker response, hence it normally is the best option for a web site or web api that needs to deal with usual file sizes.
On the other hand, if your web service needs to deliver large contents, CompressionLevel.Optimal would bring more value as it would have more impact in how much data will be sent over the network.
On top of that, the client can always specify if the response should be compressed by setting the Accept-Encoding request HTTP header appropriately, as explained in ASP.NET Core Compression Middleware documentation.


text:
Q: How to get rid of a XamlParseException? This is my xaml code. This parses an exception. I cannot find what is wrong there. Can someone point it to me?. This is a windows phone application,
XAML
<phone:PhoneApplicationPage
    x:Class="Citysearch.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="DisplayPanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="Display city" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
            <TextBlock Text="City recog" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Margin="14,151,10,10" Grid.RowSpan="2">
            <TextBox HorizontalAlignment="Left" Height="72" Margin="119,143,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="309" TextChanged="TextBox_TextChanged_1"/>
            <TextBlock HorizontalAlignment="Left" Margin="47,168,0,0" TextWrapping="Wrap" Text="city" VerticalAlignment="Top"/>

        </Grid>

    </Grid>

    <phone:PhoneApplicationPage.ApplicationBar>
            <shell:ApplicationBar>
                <shell:ApplicationBarIconButton x:Name="Reco1" IconUri="appbar.micph.rest.png" Text="mic" Click="Reco1_Click" />
            </shell:ApplicationBar>
        </phone:PhoneApplicationPage.ApplicationBar>
    </phone:PhoneApplicationPage>

The error that I get is shown below:

XamlParseException occurred : A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in System.Windows.ni.dll

It occurs on this line:
<shell:ApplicationBarIconButton x:Name="Reco1" IconUri="appbar.micph.rest.png"
    Text="mic" Click="Reco1_Click" />

A: Finally I got it.
I did this first:
Debug->Exceptions
Press Add and type in,
"System.Windows.Markup.XamlParseException"

and select Common Language Runtime Exceptions,
then it gave me the exact place of where this happens.
Then I removed
Click="Reco1_Click"

So now it works fine.

A: What we can tell you about your problem will be severely limited from the information that you have provided. The first thing to note is that that error is a very generic error and is raised for a great many different reasons... it generally has nothing to do with the XAML, but instead points to an error in a control defined in XAML.
You say that your error occurs on this line:
<shell:ApplicationBarIconButton x:Name="Reco1" IconUri="appbar.micph.rest.png"
    Text="mic" Click="Reco1_Click" />

This gives you a few possibilities:

*

*You could have a problem with your ApplicationBarIconButton control.

*You could have a problem with your IconUri property value (although you should get a compilation error if this was the case)

*You could have a problem with the code in your Reco1_Click handler

In my opinion, it is most likely that you have some code in (or started from) the constructor of your ApplicationBarIconButton control that is invalid. These types of problems can be difficult to eradicate, but if you just experiment by commenting out different (relevant) parts of the code and trying to run the application again each time, then you should eventually find the problem.


text:
Q: How to make a directory in a directory I wish to create a directory with relative path.
Here is my code:
 if os.path.isdir("Imagettes") is False :
            os.mkdir("Imagettes")

        os.makedirs("Imagettes/%Y-%m-%d_%H:%M:%S")

However it will return an error:
  File "D:\Anaconda3\envs\prunes\lib\os.py", line 223, in makedirs
    mkdir(name, mode)

OSError: [WinError 123] The file, directory, or volume name syntax is incorrect: 'Imagettes/%Y-%m-%d_%H:%M:%S'

The directory "Imagette" will be correctly created however the date directory I want to create inside won't.
I don't get what's wrong. Can somebody help me find out?

A: A filename cannot contain any of the following characters: \ / : * ? " < > |.
So you should replace : symbol, for example:
import os
from datetime import datetime
s = datetime.now().strftime("%Y-%m-%d_%H.%M.%S")
os.makedirs(f"Imagettes/{s}",exist_ok=True)

A: I found a way to have it work. I modified my code as follows :
if os.path.isdir("Imagettes") is False :
            os.mkdir("Imagettes")

today = datetime.now()
os.mkdir("Imagettes/"+ today.strftime("%Y%m%d%H%M%S"))

Hope it can be of use to somebody.


text:
Q: How to Start Cron / Crond inside the Official Postgres Container The crond is not running by default in the official postgres alpine image. How could I define my Dockerfile to make sure that the daemon runs in the background? I want that it is running by default, if possible even when the container gets restarted.
I tried to add CMD ["/usr/sbin/crond"] to my Dockerfile but I didn't succeed. Any thoughts how to run this in combination with postgres?
Update
I have added the answer of tianon:

[...]
  If you must run crond inside a container, I'd recommend instead using
  a separate container which runs nothing but crond (and thus Docker can
  both track its lifecycle, and restart it when/if it fails, the machine
  restarts, etc). You should be able to connect to the PostgreSQL
  instance from a second container, but if absolutely necessary, one
  could use things like --network container:some-postgres in order to
  join the network namespace of the database container directly.

A: pg_cron must be added to shared_preload_libraries. Per the docs:
 # add to postgresql.conf:
 shared_preload_libraries = 'pg_cron'

and you must then restart PostgreSQL.