text:
Q: How to define instances of Applicative and Monad when working with a constructor defined using record syntax I am trying to define instances for Applicative and Monad of RWS, but there must be something that I am missing. For pure, I am getting an occurs check error. It must have something to do with the fact that I give RWS f as the result of pure, despite f having the type a. I don't understand how to access the other arguments of RWS (r, w and s). I would appreciate it if someone explained some of the notions in detail, such as the newtype definition. As I understand it, we define a new type RWS which has 4 arguments (r, w, s and a). This type is defined using a constructor (fromRWS), that does something with the arguments. Correct me if I am wrong. If this is correct, is RWS defined by the 4 arguments or by fromRWS?
Moving further, the implementation for <*> produces a type error. It says that fromRWS2 is applied to too few arguments. I don't see the issue, though, since I have used the same where clause approach to solve a similar problem for a variable environment. What alternatives do can I use?
When defining Monad, I just got a parse error on input RWS
Please help me define the instances.
Here is my code:
module RWS where

newtype RWS r w s a = RWS { fromRWS :: r -> s -> (a, s, w) }

instance Functor (RWS r w s) where
  fmap f (RWS rws) = RWS $ \r s -> let (a,s',w) = rws r s in (f a, s', w)

instance Monoid w => Applicative (RWS r w s) where
    -- pure a -> RWS r w s a
    pure f = RWS f
    -- (<*>) :: RWS r w s (a -> b) -> RWS r w s a -> RWS r w s b
    RWS f <*> RWS a = RWS fromRWS2
                            where fromRWS2 r1 s1 = f a

instance Monoid w => Monad (RWS r w s) where
   --return :: a -> RWS r w s a
   return x = RWS x
   --(>>=)  :: (RWS r w s a) -> (a -> (RWS r w s b)) -> (RWS r w s b)
  RWS fr >>= f = f fr

A: Maybe it is clearer if we write RWS as
newtype RWS r w s a = MakeRWS { fromRWS :: (r -> s -> (a, s, w)) }

This definition gets you three things:

*

*A type constructor RWS taking the four r w s a arguments.

*A data constructor MakeRWS of type (r -> s -> (a, s, w)) -> RWS r w s a

*A field accessor fromRWS of type RWS r w s a -> (r -> s -> (a, s, w))
As we can see the data constructor MakeRWS should be applied to a function to construct the value of type RWS r w s a.
In your pure implementation you apply MakeRWS to a value of type a not a function. This is what goes wrong with you pure implementation.
As you note in the comment the type of pure should be
a -> RWS r w s a

but your implementation would have had this type if it worked:
(r -> s -> (a, s, w)) -> RWS r w s a

The correct implementation is
pure a = MakeRWS (\_r s -> (a, s, mempty)

Your monad implementation fails parsing because you don't have the same indentation on the return line as the line starting RWS.

A: Just follow the type(s). We can only do so much with any given thing:
-- newtype RWS r w s a  =  RWS { fromRWS :: r -> s -> (a, s, w) }

-- .....

    RWS tf <*> RWS ta  =  RWS tfa
        where
        tfa r1 s1  =  (f a, s?, w2 ?? w3)  -- what is ?
           where                           -- what is ??
           (f, s2, w2) = tf r1 s1
           (a, s3, w3) = ta r1 s2

Similarly for the monad. First of all return = pure and the other answer shows you how to define that:
    pure a  =  RWS ta
        where
        ta _r s  =  (a, s, mempty)

Then the bind is
   --(>>=)  :: (RWS r w s a) -> (a -> (RWS r w s b)) -> (RWS r w s b)
  (RWS f) >>= k  =  RWS g
       where
       -- RWS f :: RWS r w s a
       --     f :: r -> s -> (a, s, w)
       -- RWS g :: RWS r w s b
       --     g :: r -> s -> (b, s, w)
       g r1 s1  =  ???                     -- what is ???
            where
            (a, s2, w2) = f r1 s1
            (RWS h)     = k a
            -- RWS h :: RWS r w s b
            --     h :: r -> s -> (b, s, w)
            (b, s3, w3) = h r1 s????       -- what is ????


text:
Q: Concerning broken headphone wires I am planning to fix my broken headphones. They don´t really work in my laptop unless I twist the plug-in wire to a certain position and hold them there. I think it´s just a broken wire somewhere close to the plug-in? I was thinking of cutting the wire close to the plug-in and solder the wires to a new plug-in. Do you think my assumptions are correct? What are the best tools to use for this task?

A: Its unfortunate that these headphone jacks are all too often designed to fail. If you take the time, you can learn to repair them and even make them stronger than before.
Materials
You will need wire strippers/cutters, a replacement jack with wire slots, electrical tape, a soldering iron and some solder. The replacement connector should be able to unscrew, revealing the wire slots and solder points. They can be purchased very cheap and are much better to use than an old connector that is not made for replacing.
Preparation
Cut the cable near to the faulty jack. Strip the outer sheath about 1/2". There will likely be three colored wires covered in enamel. First, separate the colors and then you will need to remove the enamel. This can be done using a bead of hot solder which will melt the enamel and tin the wire. Or if you have acetone/nail polish remover and mineral spirits those work well too. If none of those works for you, you will have to carefully scrape off the enamel with steel wool or a knife. This is the most tricky part, but if you don't remove the enamel, the headphones won't work perfectly.
Soldering
Next you have to match each color with the tip, ring or sleeve of the headphone jack. For this type of connector, the tip is left channel, ring is right channel and sleeve is common. Generally the red wire is right channel, the blue wire is left channel, and the bare copper one is common. If the stereo orientation is wrong, reverse the red and blue connections.
Reinforcement
After testing the audio and L/R orientation, you may need to reinforce the wire with electrical tape and epoxy. Epoxy can be put over the solder joints so that when the cable is pulled, the tension is put on the epoxy instead of on the soldering joints which could make them weaken and break over time. With electrical tape, the idea is to put it thicker near the connector and taper it off. This way, if you pull the wire sideways, the wire will bend like a fishing rod, distributing the load over a few inches instead of just one point.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to run an FxCop Code Analysis from the MSBuild command line with VS NOT installed? Our final build server does not have Visual Studio 2010 installed.  It uses the MSBuild.exe from the .NET 4 SDK.  As part of our code delivery process to our customer we need to allow him to build the projects from the command line on a Visual Studio 'agnostic' server and also to run Code Analysis rules on that machine.
On the visual studio side we started out with AllRules.rules and created exceptions going foreward so naturally we'd like the exceptions to carry over to the code analysis on the build server.
Is this possible ?
Thanks in advance.

A: Using standalone FxCop you can customize your CI process as you wish. Open this link and go to "Setting up continuous FxCop code analysis" chapter.
Link above seems to be dead now. You can try to look here on this SO question


text:
Q: How Can I Query Polymorphic Relationship in Laravel 8 I am able to create and even delete a polymorphic row from my app, but I can not for the life of me able to figure out how to query the relationship so I can update the row. My models and controller methods are below--all work except for public function updateManifest($id).  I didn't include all the update code I've been trying over the past day and a half because it would be too much and not really relevant, but I can tell you that I can only get as deep as the Workorder model, I can't seem to query anything related through the poly relationship so I can query all the manifest objects.  Thank you.
Workorder.php
class Workorder extends Model
{
...
    public function manifest(){
        return $this->morphMany(Manifest::class, 'manifestable');
    }
}

Manifest.php
class Manifest extends Model
{
    use SoftDeletes;
    protected $fillable = [
        'stream_id', 'manifest_number', 'manifest_quantity', 'manifest_rate',
        'manifest_total', 'manifestable_id', 'manifestable_type', 'stream_description_plus'
    ];

    public function manifestable(){
        return $this->morphTo();
    }

}

edit.php (Workorder controller)
   class Edit extends Component {

public function mount(Workorder $workorder, Manifest $manifest)
    {
        $this->workorder = $workorder;
        $this->manifest = $manifest->manifestable;
        $this->workorder_number = $workorder->workorder_number;
        $this->workorder_po_number = $workorder->workorder_po_number;
        $this->workorder_status = $workorder->workorder_status;
        $this->workorder_job_notes = $workorder->workorder_job_notes;
        $this->project_id = $workorder->project_id;
        $this->customer_id = $workorder->customer_id;
        $this->generator_id = $workorder->generator_id;
        $this->prevailing_wage = $workorder->prevailing_wage;
        $this->touched = false;
    }

        public function addManifest($id)
            {
                Manifest::create([
                    'workorder_id' => $this->workorder->id,
                    'stream_description_plus' => $this->stream_description_plus,
                    'manifest_number' => $this->manifest_number,
                    'manifest_quantity' => $this->manifest_quantity,
                    'manifest_rate' => $this->manifest_rate,
                    'manifestable_id' => $this->workorder->id,
                    'manifestable_type' => get_class($this->workorder)
                ]);

                return redirect()->route('admin.workorder.edit', $this->workorder->id);
            }

        public function updateManifest($id)
            {
                $record = Workorder::find($id);
               /* dd($record);*/
                $record->update([
                    'stream_description_plus' => $this->stream_description_plus,
                    'manifest_number' => $this->manifest_number,
                    'manifest_quantity' => $this->manifest_quantity,
                    'manifest_rate' => $this->manifest_rate,
                ]);

                return redirect()->route('admin.workorder.edit', $this->workorder->id);
            }

        public function deleteManifest($id)
            {
                $record = Manifest::findOrFail($id);
                $record->delete();

                return redirect()->route('admin.workorder.edit', $this->workorder->id);
            }

           public function render()
            {
                $items = Item::all();
                $users = User::all();
                $projects = Project::all();
                $generators = Generator::all();
                $customers = Customer::all();
                $personnel = Personnel::all();
                $streams = Stream::all();

                return view('livewire.admin.workorders.edit',
                    compact('items', 'projects', 'generators',
                        'customers', 'personnel', 'users', 'streams'));
            }
        }

update form
...
<form wire:submit.prevent="updateManifest({{$man->id}})" method="PUT">

            <select wire:model="stream_id"
                    class="mt-1 form-select block w-full pl-3 pr-10 py-2 text-base leading-6 border-gray-300 focus:outline-none focus:shadow-outline-blue focus:border-blue-300 sm:text-sm sm:leading-5">
                <option value="">
                    Select Waste Stream
                </option>
                @foreach($streams as $stream)
                    <option value="{{$stream->id}}">{{$stream->stream_description}}</option>
                @endforeach
            </select>
            @error('stream_description')
                {{ $message }}
            @enderror

</form>
...


text:
Q: How do I turn a tag list into a component? Could you please tell me how to turn a page with a list of all tags into a component that would be displayed on all pages? In this case, when you click on each tag, the page redraws and displays a list of posts with a specific tag.
In the current version of the site, the page with all tags, the tag page and the page with all posts are 3 different pages.
The clearest example of how I want to end up doing this is the https://colorlibhub.com/sparkling/ site (a free theme for Wordpress). There's a block with categories on the side, click on the one you want - the page displays the posts of that category.
gatsby-node.js
const path = require('path');
const _ = require('lodash');

exports.createPages = async ({ actions, graphql, reporter }) => {
  const { createPage } = actions;

  const blogPostTemplate = path.resolve('./src/templates/post.js');
  const tagTemplate = path.resolve('./src/templates/tags.js');

  const result = await graphql(`
    {
      postsRemark: allMdx(sort: { order: DESC, fields: [frontmatter___date] }, limit: 2000) {
        edges {
          node {
            slug
            frontmatter {
              tags
              url
            }
          }
        }
      }
      tagsGroup: allMdx(limit: 2000) {
        group(field: frontmatter___tags) {
          fieldValue
        }
      }
    }
  `);

  // handle errors
  if (result.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`);
    return;
  }

  const posts = result.data.postsRemark.edges;

  // Create post detail pages
  posts.forEach(({ node }) => {
    createPage({
      path: node.frontmatter.url,
      component: blogPostTemplate,
      context: { url: node.frontmatter.url },
    });
  });

  // Extract tag data from query
  const tags = result.data.tagsGroup.group;

  // Make tag pages
  tags.forEach((tag) => {
    createPage({
      path: `/tags/${_.kebabCase(tag.fieldValue)}/`,
      component: tagTemplate,
      context: {
        tag: tag.fieldValue,
      },
    });
  });
};

single tag page
import React from 'react';
import PropTypes from 'prop-types';
import { Link, graphql } from 'gatsby';

import Header from '../components/header';
import Footer from '../components/footer';

import * as styles from './tags.module.scss';

const Tags = ({ pageContext, data }) => {
  const { tag } = pageContext;
  const { edges, totalCount } = data.allMdx;
  const tagHeader = `${totalCount} ${totalCount === 1 ? 'запись' : 'записи'} tagged with "${tag}"`;

  return (
    <>

      <main className={`${styles.container} ${styles.page}`}>

{tagHeader}

          {edges.map(({ node }) => {
            const { slug } = node;
            const { title, url } = node.frontmatter;
            return (

                <Link to={`/${url}`}>{title}</Link>

            );
          })}

        <Link to="/tags" className={styles.button}>
          All tags
        </Link>

    </>
  );
};

Tags.propTypes = {
  pageContext: PropTypes.shape({
    tag: PropTypes.string.isRequired,
  }),
  data: PropTypes.shape({
    allMdx: PropTypes.shape({
      totalCount: PropTypes.number.isRequired,
      edges: PropTypes.arrayOf(
        PropTypes.shape({
          node: PropTypes.shape({
            frontmatter: PropTypes.shape({
              title: PropTypes.string.isRequired,
            }),
            fields: PropTypes.shape({
              slug: PropTypes.string.isRequired,
            }),
          }),
        }).isRequired,
      ),
    }),
  }),
};

export default Tags;

export const pageQuery = graphql`
  query ($tag: String) {
    allMdx(
      limit: 2000
      sort: { fields: [frontmatter___date], order: DESC }
      filter: { frontmatter: { tags: { in: [$tag] } } }
    ) {
      totalCount
      edges {
        node {
          slug
          frontmatter {
            title
            url
          }
        }
      }
      nodes {
        frontmatter {
          title
          url
        }
      }
    }
  }
`;

all tags page
import React from 'react';
import PropTypes from 'prop-types';
import kebabCase from 'lodash/kebabCase';
import { Helmet } from 'react-helmet';
import { Link, graphql } from 'gatsby';

import Header from '../../components/header';
import Footer from '../../components/footer';

import * as styles from './tags.module.scss';

const TagsPage = ({
  data: {
    allMdx: { group },
    site: {
      siteMetadata: { title },
    },
  },
}) => (
  <>
    <Helmet title={title} />

    <main className={`${styles.container} ${styles.page}`}>

Tags

        {group.map((tag) => (

            <Link to={`/tags/${kebabCase(tag.fieldValue)}/`}>
              {tag.fieldValue} ({tag.totalCount})
            </Link>

        ))}

  </>
);

TagsPage.propTypes = {
  data: PropTypes.shape({
    allMdx: PropTypes.shape({
      group: PropTypes.arrayOf(
        PropTypes.shape({
          fieldValue: PropTypes.string.isRequired,
          totalCount: PropTypes.number.isRequired,
        }).isRequired,
      ),
    }),
    site: PropTypes.shape({
      siteMetadata: PropTypes.shape({
        title: PropTypes.string.isRequired,
      }),
    }),
  }),
};

export default TagsPage;

export const pageQuery = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
    allMdx(limit: 2000) {
      group(field: frontmatter___tags) {
        fieldValue
        totalCount
      }
    }
  }
`;

blog page (list of all posts)
import * as React from 'react';
import { Link, graphql } from 'gatsby';

import Layout from '../../components/layout';
import Seo from '../../components/seo';
import Card from '../../components/Card';

import * as blog from '../../components/blog.module.scss';

function BlogPage({ data }) {
  return (
    <Layout>
      <Seo title="Статьи" />
      <main className={`${blog.container} ${blog.blog}`}>
        {data.allMdx.nodes.map((post) => (
          <Card
            key={post.id}
            category={post.frontmatter.tags.map((tag) => {
              return (
                <Link key={post.id} to={`/tags/${tag}`} className={blog.categoryLink}>
                  {tag}
                </Link>
              );
            })}
            title={post.frontmatter.title}
            description={post.frontmatter.description}
            link={`/${post.frontmatter.url}`}
          />
        ))}

    </Layout>
  );
}

export const PostsQuery = graphql`
  query {
    allMdx(sort: { fields: frontmatter___date, order: DESC }) {
      nodes {
        frontmatter {
          title
          description
          date(formatString: "DD.MM.YYYY")
          tags
          url
        }
        id
        body
        slug
      }
    }
  }
`;

export default BlogPage;

A: Since page queries (like the one in TagsPage) only works in pages (or in top-level components) you can't just copy and paste your query into a component because it won't be a page anymore.
Your only chance given the scenario is to use a static query to get all tags and display them into your component. There's a limitation using static queries: they don't accept dynamic parameters, since the TagsPage query is not using any filters (as $tag in Tags is) it won't be a problem.
Something like this should work:
import React from "react";
import { useStaticQuery, graphql } from "gatsby";

export default function YourComponent() {
  const data = useStaticQuery(graphql`
    query {
      allMdx(sort: { fields: frontmatter___date, order: DESC }) {
        nodes {
          frontmatter {
            title
            description
            date(formatString: "DD.MM.YYYY")
            tags
            url
          }
          id
          body
          slug
        }
      }
    }
  `);

  console.log("your tags are:", data);
  return
 your loop here
;
}


text:
Q: VBA Excel, copied sheets come in wrong order I am struggling with the problem. I have two sheets with a different name and I want them copied throughout the document on the same basis as explained in the queries below:
VBA Excel add new sheet with number based on the previous sheet created
VBA Excel duplicate the existing sheet with number based on the previous sheet duplicated
Whereas the 1 sheet name works fine, the error occurs when launching 2 of them simultaneously.
My code looks as follows:
 Sub Sheetaadding()

 'first sheet

 Dim wsr As Worksheet, wso As Worksheet

 Application.ScreenUpdating = False

 Set wsr = ThisWorkbook.Sheets("Vet Area Map 1")
 Set wso = ThisWorkbook.Sheets("Area Map 1 Open")
 Dim I As Long, J As Long, K As Long
 Dim xCount As Integer, yCount As Integer

 For I = 1 To ActiveWorkbook.Sheets.Count
    If InStr(1, Sheets(I).Name, "Vet") > 0 Then xCount = xCount + 1
 Next

 For I = 1 To Sheets.Count - (Sheets.Count - 1)

 With Sheets("Vet Area Map 1")
 .Copy After:=ActiveWorkbook.Sheets(wsr.Index + xCount + I)
 ActiveSheet.Name = "Vet Area Map " & xCount + 1
.Select
End With
Next I

'second sheet

For J = 1 To ActiveWorkbook.Sheets.Count
    If InStr(1, Sheets(J).Name, "Open") > 0 Then yCount = yCount + 1
Next

For J = 1 To Sheets.Count - (Sheets.Count - 1)

 With Sheets("Area Map 1 Open")
 .Copy After:=ActiveWorkbook.Sheets(wso.Index + (yCount + (J - 1)))
 ActiveSheet.Name = "Area Map " & yCount + 1 & " Open"
.Select
End With
Next J

Application.ScreenUpdating = True
End Sub

And the result is quite opposite. Since the Vet Area Map comes fine, the Area Map 1 Open comes in opposite order.

How can I make these sheets appearing interchangeably as shown in the image ("Desired order"). I want to appear Vet Area Map3, Area Map 3 Open, Vet Area Map 4, Area Map 4 Open and so on.

A: Maybe I missed something, but I think the convoluted .Copy After:= is the source of the problem.
I'm also not sure what the loops are for, but For I = 1 To Sheets.Count - (Sheets.Count - 1) is the same as I = 1 to x - (x-1) Which is the same as I = 1 to 1, so not much of a loop.
Technically, unless you are going to delete pages, there seems to be little use to count twice, neither is selecting the original sheet after each action. And some other cleaning:
Sub Sheetaadding()

Dim wsr As Worksheet, wso As Worksheet
Dim I As Long, xCount As Long
Set wsr = ThisWorkbook.Sheets("Vet Area Map 1")
Set wso = ThisWorkbook.Sheets("Area Map 1 Open")

For I = 1 To ActiveWorkbook.Sheets.Count
    If InStr(1, Sheets(I).Name, "Vet") > 0 Then xCount = xCount + 1
Next

 'first sheet
wsr.Copy After:=ActiveWorkbook.Sheets(wsr.Index - 1 + xCount * 2)
ActiveSheet.Name = "Vet Area Map " & xCount + 1

'second sheet
wso.Copy After:=ActiveSheet
ActiveSheet.Name = "Area Map " & xCount + 1 & " Open"

End Sub


text:
Q: Google analytics api - get page views by URL I was able to run de "hello" app from google analytics api:
function getFirstProfileId($analytics) {
    // Get the user's first view (profile) ID.

    // Get the list of accounts for the authorized user.
    $accounts = $analytics->management_accounts->listManagementAccounts();

    if (count($accounts->getItems()) > 0) {
        $items = $accounts->getItems();
        $firstAccountId = $items[0]->getId();

        // Get the list of properties for the authorized user.
        $properties = $analytics->management_webproperties
                ->listManagementWebproperties($firstAccountId);

        if (count($properties->getItems()) > 0) {
            $items = $properties->getItems();
            $firstPropertyId = $items[0]->getId();

            // Get the list of views (profiles) for the authorized user.
            $profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstPropertyId);

            if (count($profiles->getItems()) > 0) {
                $items = $profiles->getItems();

                // Return the first view (profile) ID.
                return $items[0]->getId();

            } else {
                throw new Exception('No views (profiles) found for this user.');
            }
        } else {
            throw new Exception('No properties found for this user.');
        }
    } else {
        throw new Exception('No accounts found for this user.');
    }
}

function getResults($analytics, $profileId) {
    // Calls the Core Reporting API and queries for the number of sessions
    // for the last seven days.
    return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:sessions'
    );
}

That returns the page views for the (whole) account. But I would like to get the page views ( for the whole range ) for a specific url,
I'm trying to find how to do so, but the most similar page that I found, seems to be written in a different syntax. So I don't know how to enter those params in the current app.
Any thoughts?
--EDIT--
For more information, the previous code, prints:
But this code ( with the "syntax" of the link I provided before )
function getReport($analytics) {

  // Replace with your view ID, for example XXXX.
  $VIEW_ID = "40xxxyyy9"; // I got it from The Google Account Explorer

  // Create the DateRange object.
  $dateRange = new Google_Service_AnalyticsReporting_DateRange();
  $dateRange->setStartDate("7daysAgo");
  $dateRange->setEndDate("today");

  // Create the Metrics object.
  $sessions = new Google_Service_AnalyticsReporting_Metric();
  $sessions->setExpression("ga:sessions");
  $sessions->setAlias("sessions");

  // Create the ReportRequest object.
  $request = new Google_Service_AnalyticsReporting_ReportRequest();
  $request->setViewId($VIEW_ID);
  $request->setDateRanges($dateRange);
  $request->setMetrics(array($sessions));

  $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
  $body->setReportRequests( array( $request) );
  return $analytics->reports->batchGet( $body );
}

function printResults($reports) {
  for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
    $report = $reports[ $reportIndex ];
    $header = $report->getColumnHeader();
    $dimensionHeaders = $header->getDimensions();
    $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
    $rows = $report->getData()->getRows();

    for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
      $row = $rows[ $rowIndex ];
      $dimensions = $row->getDimensions();
      $metrics = $row->getMetrics();
      for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
        print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
      }

      for ($j = 0; $j < count( $metricHeaders ) && $j < count( $metrics ); $j++) {
        $entry = $metricHeaders[$j];
        $values = $metrics[$j];
        print("Metric type: " . $entry->getType() . "\n" );
        for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
          $value = $values->getValues()[ $valueIndex ];
          print($entry->getName() . ": " . $value . "\n");
        }
      }
    }
  }
}

Prints out:
 Uncaught exception 'Google_Service_Exception' with message '{ "error": { "code": 403, "message": "Google Analytics Reporting API has not been used in project api-project-395xxxxxxx2105 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analyticsreporting.googleapis.com/overview?project=api-project-395xxxxxxx2105 then retry.

And if I follow the console link to my project. It let me know that is already enabled ( otherwise the first code in the question shouldn't work )

A: Your example actually return the number of sessions, not pageviews. So to get the number of pageviews for an Url you would need to a) change ga:sessions to ga:pageViews and b) apply a filter that limits the data to the expected Url.
Filters can by applied by passing them as part of an array of optional parameters, so you'd need to change your function a bit (this basically taken from the documentation):
function getResults($analytics, $profileId) {

    $optParams = array(
          'filters' => 'ga:pagePath=@/my/url'
    );

    return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:pageViews',
        $optParams
    );
}

IIRC =@ should be a partial match in a filter (else consult the documentation) and of course you need to change "/my/url" to your actual url.
Also note my comment about different API versions.


text:
Q: Troubleshooting CPU, PSU, MOBO, HW Have a well aged PC that has started acting up. In short terms:

*

*It has worked fine for about 13 years.

*BIOS, Windows 10

*Started out with trouble booting.

*When pressing the ON button it sometimes start, other times not.

*Have to keep "trying" to start it over and over.

*

*It sometimes is completely dead

*Other times it start the fans for a fraction of a second, then goes dead.

*Other times it goes into a loop; start for half a second, shut down, start for half a second, shut down etch until I unplug the power.

*Take out fans, HDDS, RAM, etc. and sometimes it starts other times not. Sometimes after powered off for a while, other times not etc.

There are some Red LED indicators on the motherboard; for CPU and RAM. Taking out the RAM usually put the PC in a state where it starts. Then put RAM back and boot. Sometimes the CPU led lights up, other times the RAM, but there is no pattern to it.

*

*Have run the extensive version of Microsoft memory test (9-12 hours) but it did not report anything.

*The voltages reported from the PSU internally using software are fine, but this could perhaps not tell all?

*The computer never crashes when running

*Only stage where there are troubles is at boot time.

*Have also run some CPU stress tests.

Any idea what could be going on here? The RAM test is fair enough, but are there other tests that can be run for e.g. the CPU, PSU, chips on the MB etc?
Not quite sure where to go from here. Thought of getting a new CPU (used) but no idea if it actually is the CPU ...

ASUS P7P55D: https://www.asus.com/supportonly/P7P55D/HelpDesk_Manual/


text:
Q: Issues with np.unwrap() in python. Phaseshifting I have to plot a set of data which is in a 2-pi periodic box and there are discontinuities because of the periodicity of the values, so I used the numpy function unwrap() for discontinuities in pi or 2*pi, but it doesn't solve my problem.
Below is the plot. It is noticeable that between ~3 and ~5, there is a discontinuity, but unwrap() doesn't notice (or solve) it.
Any suggestion is appreciated


text:
Q: SEDE [Post Link] magic column not compatible with chat one-boxing for answers I am filing this as a bug report but I am not sure if the "bug" is on the SEDE side or the chat side (or if this should be a chat feature request).
Issue: SEDE links to answers (or anything that isn't a question for that matter) in the [Post Link] column are not compatible with chat one-boxing.
Reason: SEDE always uses http://site/questions/id, no matter what the PostTypeId is (i.e. instead of http://site/a/id for answers).
SE's web servers seem to handle this properly and forward to the correct URL, but chat does not, and copying a generated answer link from SEDE into chat does not create a onebox as I would expect.
This is one way to frame the reason. It could also be said that chat does not handle 301's properly. Like I said, not sure where to consider the issue to be.
Also, rene's comment below leads me to point another finger at chat: It turns out chat does properly one-box links to answers in the form /q/id, it just doesn't handle /questions/id.
Steps:

*

*In an SEDE query with a [Post Link] column linking to an answer, copy the link and paste it in chat.

Expected: One-box. Actual: No one-box (a ... zero-box?)
Possible Solutions:

*

*Make SEDE generate [Post Link] URLs based on PostTypeId, or

*Make chat be able to one-box /questions links to answers, or

*Make chat follow the 301 status replies the server sends back before one-boxing, or

*Make SEDE generate links of the form /q/id instead of /questions/id.

The first solution probably comes at too high a cost: While the links are formatted client-side, the query needs to return the title column in the response when the magic column is present. Letting it be based on PostTypeId means adding extra overhead to the response when the magic column is used.
I believe that the third solution (follow 301 replies) is philosophically the best except that in practice it isn't really necessary since chat doesn't seem to one-box wiki or moderator nomination posts anyways (PostTypeId 3 thru 8), so unless support for those were added in general it wouldn't change anything vs. the other two options.
The fourth solution is from rene's observation in the comment below. This might be the quickest fix, since it doesn't really require changes to anything other than SEDE's client-side link formatting code.
Also I'm not entirely sure about my claim that the web servers handle /questions properly for all post types, I'd need to do some more thorough testing, and I don't want to stray too far from the topic here (answer links). I can only say for certain that it works for questions and answers.
Example:
Query:
SELECT TOP 2 Id [Post Link], Id, PostTypeId
  FROM Posts
  WHERE PostTypeId = 1 AND DeletionDate IS NULL
UNION SELECT TOP 2 Id [Post Link], Id, PostTypeId
  FROM Posts
  WHERE PostTypeId = 2 AND DeletionDate IS NULL

Chat results:

*

*For a question: https://chat.stackexchange.com/transcript/message/36373572#36373572

*For an answer: https://chat.stackexchange.com/transcript/message/36373576#36373576

A: The magic column Post Link is expanded client-side. The PostTypeId isn't send in the payload to the client so you can't decide there if it needs to be a /q/ or on /a/. A quick experiment in chat reveals that using https:\\site\q\{id} does one-box correctly for both answers and questions.
So for now that will be the fix as that can be prepared by a simple Pull Request on the SEDE repository.
The change is on these lines in query.resultset.js:
case 'post':
     return linkFormatter('/questions/', siteColumnName);

will become:
case 'post':
     return linkFormatter('/q/', siteColumnName);

I have tested this locally and renders the correct result. I have gone ahead and submitted this Pull Request that only needs to be merged on the main branch by Nick in 6 to 8 weeks. The PR already received a thumbs up from Tim Stone so we're good to go.


text:
Q: KMLTree for Using with the Google Earth Plugin I need a solution for loading all the layers and elements of a KML file into a webpage tree element for use with the Google Earth Plugin.
Is the jquery KMLTree the only option for a tree to view KML layers and elements with the GE Plugin?
https://code.google.com/p/kmltree/

A: Author of kmltree here. I'd caution against trying to roll your own with any old treeview control. Parsing kml and dealing with networklinks is a major pain, especially considering that the API gives limited access to the loaded networklinks.
Kmltree had some serious effort and real-world testing put into it for a couple years so it would be a shame not to leverage it. I'm not aware of any other projects that have gone to similar lengths to support networklinks, html (even youtube) infoWindows, and all the particularities of tree styling in the spec. I'm not actively maintaining it anymore since my work has taken my attention elsewhere, but it's still in good shape and patches are always welcome.

A: No - but to date it is by far the best.
There is this demo is the api samples gallery that Uses dojo for example.
http://earth-api-samples.googlecode.com/svn/trunk/demos/dom-tree/index.html
Essentially you could use any treeview control from any framework and adapt it to show Kml features - there are plenty out there.
Also, Kml is just Xml - so it would be fairly easy to build your control that has the functionality you require by using native JavaScript and the Google Earth api.


text:
Q: Custom Record with Custom Sublist - access data? Is there a way to access a custom sublist on a custom record via suitescript? I have a record that users will enter criteria into that will then populate a bom in the sublists section via a saved search. Is there a way to access this data? When I try to run currentRecord.getSublists(), it says that it is not a function.
Any help is appreciated. Thanks!

A: Just in case people still run into this issue, it's a matter of dynamic vs static records.
currentRecord in a User Event is both a static record and cannot be "saved" (i.e. if you want to make changes in an afterSubmit method).
You'll want to record.load in dynamic mode to get what you are looking for.

A: var linect = rec.getLineItemCount('recmachcustrecord');


text:
Q: How to group elements of array I have an array:
var arr = ['User1','123456','User2','456789','User3','546544'];

How can I get array of object like this:
var arr2 = [{name: 'User1', id: 123456},{name: 'User2', id: 456789}, {name: 'User3', id: 546544}];

I tried this:
arr.forEach(function (item, i, arr) {
            arr2.push(
                {
                    name: arr[i],
                    id: arr[i + 2]
                }
            );
        });

A: In a simple way, you need to do two things:

*

*Check if the length is even.

*Push it as how you require, by incrementing the loop twice.

var arr = ['User1', '123456', 'User2', '456789', 'User3', '546544'];
var arrObj = [];
if (arr.length % 2 === 0)
  for (var i = 0; i < arr.length; i += 2)
    arrObj.push({
      "name": arr[i],
      "id": parseInt(arr[i + 1], 10),
    });
console.log(arrObj);

A: Look at the comments inside the code.

const arr = ['User1', '123456', 'User2', '456789', 'User3', '546544'];

// Ok, so what you to do is to group the infos and create a new object
// There is many function you can use, in the following example, I will use
// Array.reduce

// We gonna call couple, two values that goes together, like :
// User1 and 123456
// User2 and 456789

// ...
const ret = arr.reduce((tmp, x, xi) => {
  // Add nothing for the first value of the couple
  // We gonna ignore, User1, User2 and User3
  if (xi % 2 === 0) return tmp;

  return [
    ...tmp,

    // Add a new value in the array
    {
      // The name is the first value of the couple
      name: arr[xi - 1],

      // The id is the second value of the couple
      id: x,
    },
  ];
}, []);

console.log(ret);

A: The for loop works on all versions of all computers and has the added advantage of being able to skip the index directly, something forEach can only do with a lot of extra code. Also forEach is slower than the for loop.

var arr1 = ['User1', '123456', 'User2', '456789', 'User3', '546544'], arr2 = [];
for (var i = 0; i < arr1.length - 1; i += 2) { // here is the i+=2
  arr2.push({
    "name": arr1[i],
    "user": arr1[i + 1] // here is the i+1
  });
}
console.log(arr2)

Or terser array

var arr1 = ['User1', '123456', 'User2', '456789', 'User3', '546544'], arr2 = [];
for (var i = 0; i < arr1.length - 1; i += 2) {
  arr2.push({
    [arr1[i]]: arr1[i + 1]
  });
}
console.log(arr2)

A: A solution to your problem would be as follow :
var arr2 = [];

for (var i = 0; i < arr.length; i = i + 2) {
   arr2.push({name : arr[i], id: arr[i + 1]})
}

Next time time try to show your trial code, you'll progress much more this way.


text:
Q: Maven - execute comand in seperate thread before and after test I have a module in my project that is depentent on a server running for the unit tests to work. The server can be run with the command mvn jetty:run -f moduleName/pom.xml. Is there a way to automatically start the server in a new thread, before the test phase starts, and terminate it afterwards? In other words, i want the server to start after running mvn test and stop the server again once it moves on to the next module.
I've already tried using JerseyTest, but I am not satisfied with the result because of the complexity of the module and all the different classes that depend on the server.


text:
Q: radio button clicking for payment process hi guys presently am working with my own website.. my web site works fine i want to add something in my website. in payment process i have created 3 buttons, customers after fill that forms they need to choose the payment button three button will has a different values ie pounds £ 3 £ 5.5 and £ 9
.. once customer click the cart the payment amount will be automatically display on left side after that when customer clicking that radio button that payment amount should be added with that amount by clicking any one of radio button ..
kindly check my website amd plz click unlock page
http://spsmobile.co.uk
plz can any one  say the correct code which will be suitable with it..plz

A: If I'm getting you right, you want to show radio buttons that will, once clicked, show a defined value on the box at the right at your website (unlock page).
If that's so, you'll have to define radio buttons:
<input type="radio" name="" id="" value="1" onclick="showText(this)" />Text

Change name and id, add checked if you want it to be pre-checked; and modify the text that you want to add, before or after itself. Then, add an onclick event to load something like this:
        function showText(isList){
            txtIndex = isList.selectedIndex;
            document.getElementById('textDiv').innerHTML = nText[txtIndex];
        }

And add an array for that possible values;
        var nText = new Array()
        nText[1] = "";
        nText[2] = "";

Add as many arrays you need, and inside that inverted commas from each nText[] write what you want to show once each radio is selected. Once done that, you should print the textDiv (or whatever you want to), directly to the html page with

 or so.
That should make it, even thought you might have to change it slightly as I'm using this for <select> instead of direct inputs and onchange events instead of onclick, and I've changed it on-the-fly. Good luck.


text:
Q: angular webpack works with real backend I am using webpack + angular to develop the project. one problem is that when I start my localhost, angular cannot get data from real backend.
angular is running at localhost:8080, and the real API is at http://192.168.xxx.xxx:8080/getTable.html
if I write the url directly in angular, I would have below error:
XMLHttpRequest cannot load http://192.168.xxx.xxx:8080/getTable.html. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
anybody has solution to this? thanks


text:
Q: Can we enable/disable Call Audio Routing setting in ios programmatically I'm starting a call in ios programmatically like this:
NSString *telString = [NSString stringWithFormat:@"tel:%@", @"9898989898",];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:telString]];

Along with this, I want to enable speaker automatically for this phone call from my app as per client request. I know user can do it mannualy like following:

Can we access this Call Audio Routing setting from our app? or is there other possibility?
Referring to this question its not possible, but have things changed in these 5 years?


text:
Q: User rights to read/write win.ini in windows 8.1 I use a program in Windows 8.1 Pro that needs full read/write rights to win.ini.
- Logged in as administrator
- UAC is disabled
- Applications and administrators have full rights to modify win.ini. Nevertheless I cannot modify the file unless I run the program (or notepad) as administrator. This is however not an option for this application.
Anybody an idea which security setting I can change to accomplish this?
Art.

A: Have you tried running the program as administrator?
Right click on the icon and select "run as administrator" from the context menu.
I'm curious.  What program needs to write to win.ini in this day and age and why?


text:
Q: How can I present a small page sheet with SwiftUI? I'm developing an app for iPad with SwiftUI.
I want to present a page sheet but with a smaller size.
I'm using but I can't change the width of the page sheet.
.sheet(
    isPresented: self.$isEditing,
) {
    Text("My page sheet view")
}

The result is :

How can I have the Apple shortcut app modal size ?

Maybe it's a proprietary custom view from Apple not available with UIKit...
Thank you very much

A: At the moment, you can use an actionSheet (iOS 14 or earlier) / confirmationDialog (iOS 15 or later) which is much smaller or you can create your own custom-made sheet maybe with usage of SheeKit.
For the case that an actionSheet / confirmationDialog is enough:
Screenshot of the actionSheet
@State private var showingConfirm: Bool = false
@State private var actionSelection = ""
..

Group {
    Button(action: {
            showingConfirm.toggle()
        }, label: {
            Label("Demo")
        })
 }
// iOS 14
.actionSheet(isPresented: $showingConfirm, content: {

        let action1 = ActionSheet.Button.default(Text("First action")) {
            actionSelection = "First"
        }

        let action2 = ActionSheet.Button.default(Text("Second action")) {
            actionSelection = "Second"
        }

        return ActionSheet(title: Text("Action Sheet"), message: Text("Message"), buttons: [action1, action2])
 })

 // or for iOS 15
 .confirmationDialog("Action Sheet", isPresented: $showingConfirm, titleVisibility: .visible) {
        Button("First action") {
            actionSelection = "First"
        }

        Button("Second action") {
            actionSelection = "Second"
        }

    }


text:
Q: java configuration of mongodb with latest spring/spring boot release version I want to create a MongoTemplate bean using spring boot 2.3.4.RELEASE. Earlier I configured it using 2.0.5.RELEASE as below.
    public MongoDbFactory mongoDbFactory() {

        return new SimpleMongoDbFactory(new MongoClientURI("mongodb://localhost:27017/test"));
    }

    @Bean
    public MongoTemplate mongoTemplate() {
        System.out.println("check");
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
        return mongoTemplate;
    }

I upgraded the spring boot version to 2.3.4.RELEASE. Since, SimpleMongoDbFactory has been deprecated since 2.0.0, I am unable us this configuration. I tried to implement in following way for newer version,
public MongoDatabaseFactory mongoDbFactory() {

        //return new SimpleMongoClientDatabaseFactory("mongodb://localhost:27017/test");
        return new SimpleMongoClientDatabaseFactory(new MongoClientURI("mongodb://localhost:27017/MGXPI413"));
    }

    @Bean
    public MongoTemplate mongoTemplate() {
        MongoTemplate template = new MongoTemplate(mongoDbFactory());
        return template;
    }

I do not want to downgrade the version. I searched a lot about it, but could not get correct configuration. Please let me know how to do it.


text:
Q: Thread handling in c# I have the following code.. When i am executing this code, all the 5 thread windows are displaying at the same time. But I want to execute a single thread with some value in each iteration. More than two threads should not be executed at a time..
The second thread(key=1) should start only after the completion of the first thread(key=0), and third thread(key=2) only after the completion of the second thread, and so on. Please help..
How can deal with this problem.
for (long key = 0; key < 5; key++)
{
                    var processingThread = new Thread(() => DoDataSetup(key));
                    _progress = new ProgressReport(processingThread);
                    _progress.Show();
                    _progress.FormClosed += delegate(object delSender, FormClosedEventArgs args)
                    {
                        this.Enabled = true;
                    };

                    this.Enable    d = false;

                    processingThread.Start();
                }

A: First of all it is better to use ThreadPool for Task creation, but I suggest you to create threads with use of Task.Run(...). For allowing to enter only a limited number of threads you could use the Semaphore class, or you use the BatchBlock of the TPL-API
//with semaphore
var semaphore = new Semaphore(0,2);
for(long key = 0; key < 5; key++)
{
    semaphore.WaitOne();

    ProcessWorking(key);

    semaphore.Release();
}

public void ProcessWorking(long key)
{
    var processingThread = new Thread(() => DoDataSetup(key));
    _progress = new ProgressReport(processingThread);
    _progress.Show();
    _progress.FormClosed += delegate(object delSender, FormClosedEventArgs args)
    {
        this.Enabled = true;
    };

    this.Enabled = false;
    processingThread.Start();
}


text:
Q: Process started with systemctl throws no errors, but does not appear in process list? Unix newbie here. I am trying to start gunicorn with systemctl. No error message appears, but it's also not showing up in the processes list:
$ sudo systemctl start gunicorn
$ ps aux | grep gunicorn
test+ 29902  0.0  0.0  14224   924 pts/0    S+   11:13   0:00 grep --color=auto gunicorn

Is it possible that it's running, but invisible?
Or if not, how can I debug why it isn't running?
UPDATE: Just tried systemctl status gunicorn and got this:
● gunicorn.service - Gunicorn Application Server handling myapp
   Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled)
   Active: inactive (dead) (Result: exit-code) since Mon 2016-10-31 11:24:04 EDT; 1min 25s ago
  Process: 30135 ExecStart=/.venv/bin/gunicorn --workers 3 --bind unix:/home/myapp/myapp/myapp.sock myapp.wsgi:application (code=exited, status=200/CHDIR)
 Main PID: 30135 (code=exited, status=200/CHDIR)

So it's dead, but how can I find out why?

A:
(code=exited, status=200/CHDIR)

The working directory that you've configured in the service unit is wrong or inaccessible.

A: I faced something similar, I had all folders correctly present but got the same error.  I got it to work by changing the "User" parameter. I set it as root and worked. Fyi.


text:
Q: Get Room object in other node in socket.io in multiple socket.io server environment I have two socket io servers, and two clients are connected on different servers say, client 1 is connected to server 1 and client 2 is connected to server 2.
Now client 1 creates a room in its socket.io server i.e in server 1 and when client 2 tries to join that room it actually cannot find that room because that room is in server 1 and client 2 is trying to find the room in server 2 which is not created there.
Currently, I'm using a PostgreSQL adapter to route events to different clients connected on different servers. The events are passing successfully but client 2 is not able to join the room.
So how can I get the room information which is created on server 1 in the second socket.io server?
If there is any other way to do it. Please tell me.


text:
Q: Using vba to login I want to use vba to login to a site. This makes it easy for everyone and not everyone has to know the password this way.
However, the site was recently updated and now the code that I used (that was duct taped together from bits and pieces)
`Sub apiweb()
Dim oHTML_Element As IHTMLElement
Dim sURL As String
On Error GoTo Err_Clear
sURL = "https://apiweb.biomerieux.com/login"
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.timeout = 60
oBrowser.navigate sURL
oBrowser.Visible = True
Do
 ' Wait till the Browser is loaded
Loop Until oBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = oBrowser.document
HTMLDoc.all.login.Value = "xxxx"
HTMLDoc.all.Password.Value = "yyyy"
' oBrowser.Refresh ' Refresh If Needed
Err_Clear:
If Err <> 0 Then
Err.Clear
Resume Next
End If
End Sub`

So it used to work that you press a button in excel, the site would open and after a second or 2 the login and password would show up and you'd just press login. Now it only opens the site.
I tried a few things including inspecting the elements, but i'm a novice so I don't really know what to look for or what to do. So any help (and explanation) would be appreciated!

A: Option Explicit

Sub WbClkMe()

Dim IE As New SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
Dim HTMLInput As MSHTML.IHTMLElement
Dim HTMLButton As MSHTML.IHTMLElement

IE.Visible = True

IE.navigate "https://apiweb.biomerieux.com/login"

Do While IE.readyState <> READYSTATE_COMPLETE

Loop

Set HTMLDoc = IE.document

Set HTMLInput = HTMLDoc.getElementById("signupEmail") ' This is based on on your website

HTMLInput.Value = "" 'Put the value of Usernamae

Set HTMLInput = HTMLDoc.getElementById("signupPassword") 'This is based on on your website

HTMLInput.Value = "" 'Put the value of Password

Set HTMLButton = HTMLDoc.getElementById("signupSubmit") 'This is based on on your website

HTMLButton.Click

End Sub

A: How about this method?
Dim HTMLDoc As HTMLDocument
Dim oBrowser As InternetExplorer
Sub Login_2_Website()

Dim oHTML_Element As IHTMLElement
Dim sURL As String

On Error GoTo Err_Clear
sURL = "https://apiweb.biomerieux.com/login"
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.timeout = 60
oBrowser.navigate sURL
oBrowser.Visible = True

Do
' Wait till the Browser is loaded
Loop Until oBrowser.readyState = READYSTATE_COMPLETE

Set HTMLDoc = oBrowser.Document

HTMLDoc.all.signupEmail.Value = "signupEmail"
HTMLDoc.all.signupPassword.Value = "*****"

For Each oHTML_Element In HTMLDoc.getElementsByTagName("signupSubmit")
If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For
Next

' oBrowser.Refresh ' Refresh If Needed
Err_Clear:
If Err <> 0 Then
Debug.Assert Err = 0
Err.Clear
Resume Next
End If
End Sub

As an aside, hit F12 to see the HTML behind your browser.


text:
Q: Why does the restoration of the metadata and the saved model fail? I have defined a deep learning model using the Lenet5 architecture.
I saved the result and the metadata.
I tried to reuse them to predict on the new images.
But even though the model yielded a validation accuracy of 97.7%, a test accuracy of 95.8%, the prediction on new images gives an accuracy of 0%.
It seems that the problem occurs due to incorrect restoration of the model.
It seems that the tensors are not found properly.
Then I named the tensors to solve the problem.
Finally, I am stuck with a naming problem.
Here is the code: < click me >
And the data are available here: < click me >
The traces:
Training... model: model1, rate: 0.00085, epochs: 2, batch size: 100, keep_prob: 0.67

Epoch:   0 | cost : 0.631 | Val.accu : 0.816
Epoch:   1 | cost : 0.419 | Val.accu : 0.900
INFO:tensorflow:Restoring parameters from ./logs/nn_logs/171113x1008/model1.ckpt
Validation Accuracy = 0.900
INFO:tensorflow:Restoring parameters from ./logs/nn_logs/171113x1008/model1.ckpt
Test Accuracy = 0.880
< myLabel > = [0, 1, 2, 32, 35]
< repo name of the model > : 171113x1008

And I get the following erro message:
Traceback (most recent call last):
  File "<ipython-input-1-e08ed0fc9454>", line 1, in <module>
    runfile('C:/Users/mo/_171109_1434_TSC-Debugging.py', wdir='C:/Users/mo/_Coding_')

  File "C:\Users\mo\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "C:\Users\mo\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/mo/_171109_1434_TSC-Debugging.py", line 910, in <module>
    myPredictionGRAY, ch = fctPrediction(myImg2, pathCkp)

  File "C:/Users/mo/_171109_1434_TSC-Debugging.py", line 889, in fctPrediction
    metaModel = tf.train.import_meta_graph(Ckp+ckptMeta)

  File "C:\Users\mo\Anaconda3\envs\tfgpu\Lib\site-packages\tensorflow\python\training\saver.py", line 1595, in import_meta_graph
    **kwargs)

  File "C:\Users\mo\Anaconda3\envs\tfgpu\Lib\site-packages\tensorflow\python\framework\meta_graph.py", line 499, in import_scoped_meta_graph
    producer_op_list=producer_op_list)

  File "C:\Users\mo\Anaconda3\envs\tfgpu\Lib\site-packages\tensorflow\python\framework\importer.py", line 308, in import_graph_def
    op_def=op_def)

  File "C:\Users\mo\Anaconda3\envs\tfgpu\Lib\site-packages\tensorflow\python\framework\ops.py", line 2339, in create_op
    self._add_op(ret)

  File "C:\Users\mo\Anaconda3\envs\tfgpu\Lib\site-packages\tensorflow\python\framework\ops.py", line 2033, in _add_op
    "is already used" % op.name)

The error message:
ValueError: cannot add op with name layer1/layer1W/optAdam as that name is already used
Thank for your support,
mo


text:
Q: How can i render two jsx files using ReactDOM.render As i said t want to render two jsx files using ReactDOM.render, but i don't know how can i do it.
import Header from './header';
import HelloWorld from './hello-world';
import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
<Header />,
<HelloWorld />,
document.querySelector('.root')
);

Many thanks in advance !!

A: render can only render one component (which can have children). So like this:
ReactDOM.render(
  <div>
    <Header />
    <HelloWorld />
  </div>,
  document.querySelector('.root')
);


text:
Q: Rolling two dices n-times. Probabillity of getting doubles I started learning the basics of probabillity theory by myself and did some practicing and I was doing the following exercise which i found on the internet.
Two dices are rolled n-times, determine the probabillity of getting each double (1,1),(2,2),.....,(6,6)
atleast one time.
I used the binominal distribution, since all four conditions i) finte number of trials ii)trials are independent iii)each trial has two outcomes and at each trial probability doesn't change.
Consider getting a double is a sucess
P(getting a double on a roll)=$\frac { 1 }{ 6 } $
P( not getting a double)=$\frac { 5 }{ 6 } $
since we are looking for 6-succes we get from the binominal distribution formula that (n,6)
$P(x=6)=(n,6){ p }^{ 6 }{ (1-p) }^{ n-6 }$
$P(x=6)=(n,6){ \frac { 1 }{ 6 }  }^{ 6 }{ (1-\frac { 5 }{ 6 } ) }^{ n-6 }$
((n,6) denotes the binominal coeff.)
I'm a little concerned if this is right,since i did not consider the atleast one time thing furhter my modell does not consider that if a pair comes twice it still counts as success even tho its none.
Could you help me to finish this correctly

A: The chance you don't get double $1$ in $n$ rolls is $\left(\frac {35}{36}\right)^n$ so the chance you do get double $1$ is $1-\left(\frac {35}{36}\right)^n$.  The naive thing is to say the chance you get all six doubles is then $\left(1-\left(\frac {35}{36}\right)^n\right)^6$  This ignores the correlation introduced because the fact that you got a double $1$ means you have fewer chances to get double $2$.  As $n$ gets large this will not be a problem, but clearly for $n=5$ the chance of getting all the doubles is zero.
This is a job for inclusion-exclusion.  There are $36^n$ total sets of rolls.  Of that $35^n$ do not have double $1$s so subtract $6\cdot 35^n$ for the sets missing each double.  You have subtracted the ones missing two pairs of doubles twice, so add them back in.  This is ${6 \choose 2}34^n$.  Now we have subtracted the ones missing three doubles three times and added them back three times, so subtract them once, which is ${6 \choose 3}33^n$.  Now the ones missing four doubles...

A: Supposing we roll two dice that have $q$ sides, $n$ times and ask about
each double appearing at least once. We have from first principles
that this is given by
$$\frac{1}{q^{2n}} n! [z^n] (\exp(z)-1)^{q} \exp(z)^{q^2-q}.$$
Here we have used the labeled combinatorial class
$$\def\textsc#1{\dosc#1\csod}
\def\dosc#1#2\csod{{\rm #1{\small #2}}}
\textsc{SEQ}_{=q}(\textsc{SET}_{\ge 1}(\mathcal{Z}))
\textsc{SEQ}_{=q^2-q}(\textsc{SET}(\mathcal{Z})).$$
This may be evaluated in two ways, the first is
$$\frac{1}{q^{2n}} n! [z^n] \exp(z)^{q^2-q}
\sum_{p=0}^q {q\choose p} (-1)^{q-p} \exp(pz)
\\ = \frac{1}{q^{2n}} n! [z^n]
\sum_{p=0}^q {q\choose p} (-1)^{q-p} \exp((p+q^2-q)z).$$
This is
$$\bbox[5px,border:2px solid #00A000]{
\frac{1}{q^{2n}}
\sum_{p=0}^q {q\choose p} (-1)^{q-p} (p+q^2-q)^n.}$$
The second is
$$\frac{q!}{q^{2n}} n! [z^n]
\frac{(\exp(z)-1)^{q}}{q!} \exp(z)^{q^2-q}
\\ = \frac{q!}{q^{2n}} n!
\sum_{p=q}^n [z^p] \frac{(\exp(z)-1)^{q}}{q!}
[z^{n-p}] \exp(z)^{q^2-q}
\\ = \frac{q!}{q^{2n}} n!
\sum_{p=q}^n {p\brace q} \frac{1}{p!}
\frac{(q^2-q)^{n-p}}{(n-p)!}.$$
We get
$$\bbox[5px,border:2px solid #00A000]{
\frac{q!}{q^{2n}}
\sum_{p=q}^n {n\choose p} {p\brace q}
(q^2-q)^{n-p}.}$$
Observe that the first of these is inclusion-exclusion where the nodes
of the  underlying poset  represent configurations  where a  given set
$P\subseteq D$ of doubles $D$ with $|P|=p$ is missing or possibly more
doubles. To see this re-index as follows:
$$\bbox[5px,border:2px solid #00A000]{
\frac{1}{q^{2n}}
\sum_{p=0}^q {q\choose p} (-1)^p (q^2-p)^n.}$$
The cardinality of these is  clearly $(q^2-p)^n$ where we have removed
the  $p$  doubles  in  $P$.   Now  in  this  poset  the  configuration
containing  all doubles  is only  included in  $P=\emptyset$ and  with
weight $(-1)^{|P|}$ we get weight  one for these. A configuration that
is  missing the  doubles from  a set  $R$ where  $R\subseteq D,  R\neq
\emptyset$ is  included in all  nodes representing subsets $P$  of $R$
which gives a weight
$$\sum_{P\subseteq R} (-1)^{|P|}
= \sum_{p=0}^{|R|} {|R|\choose p} (-1)^p = 0,$$
so  these  have   weight  zero  in  the  poset   which  concludes  the
construction by PIE.

A: I've been scratching my head over this one since it seems like it should be really simple, but.. it isn't...
I tried solving this using the multinomial formula, and I think I've got the correct answer. I confirmed by writing an algorithm to simulate this procedure (rolling 2 die $n$ times, checking if all 6 pairs show up), and the long-run frequencies I'm getting in my simulation match my answer quite closely, so I'm pretty sure I've gotten this correct, or at least very close to correct.
I see someone has already provided an answer, but that solution is way above my head and I don't understand it. I have a feeling the asker here will not understand that explanation without a good deal of further study, so I'm offering my solution as well, which I think is a bit easier to understand, albeit, a bit impractical.
Basically, my solution is a brute-force attack using the multinomial formula. I have basically just summed all possible multinomial probabilities where there are at least $1$ of each pair, using nested summations.
A single multinomial probability is given by:
$$ P(N_1=n_1, N_2=n_2,...,N_m=n_m)={n! \over {n_1! \cdot n_2! \cdot ...\cdot n_m!}}p_1^{n_1}p_2^{n_2}...p_m^{n_m} $$
And this is useful, by thinking of $N_1, N_2,$ etc.. as the number  of times $(1,1), (2,2)$ appears in $n$ rolls, and $N_{7 \rightarrow 36}$ as the number of times all other outcomes appear.
By taking the sum of all possible  multinomial probabilities where each pair shows up at least once, you should get the probability you're looking for.
So... you want the following sum:
$$P\Bigl(N_1 \ge 1, N_2 \ge 1, N_3 \ge 1, N_4 \ge 1, N_5 \ge 1, N_6 \ge 1, \bigl[0 \le N_{7 \rightarrow 36} \le (n-6) \bigr] \Bigr)$$
$$
= \sum_{n_1=1}^{(n-5)} \sum_{n_2=1}^{(n-S_1-4)} \sum_{n_3=1}^{(n-S_2-3)} \sum_{n_4=1}^{(n-S_3-2)} \sum_{n_5=1}^{(n-S_4-1)} \sum_{n_6=1}^{(n-S_5)}  {
{n! \over {n^*
(n-S_6)!
}
}{\left( {1\over36} \right)^{S_6}
}{\left(30\over36 \right)^{n-S_6}}
}     $$
where $S_i=\sum_{k=1}^{i} n_k,$ $n^*= \prod_{k=1}^{6} n_k!,$ and $N_1+N_2+...+N_6+N_{7 \rightarrow 36}=n$
In case this isn't obvious, I've represented the number of times $(x,x)$ shows up by $N_x$, and the number of times all non-doubles show up as $N_{7\rightarrow 36}$. Therefore, $p_x={1\over 36},$ and $p_{7\rightarrow 36}={{36-6}\over 36}={30\over36}$.
Now you might be wondering how you would go about simplifying this to derive a simpler, general formula, and I haven't the foggiest idea. However, if you want to find out an actual probability for a given value of $n$, you can use the desmos graphing calculator (which is an amazing tool if you are not aware of this already) to do this for values of $n< (\sim70)$. The calculator starts getting a bit choppy with higher values.
Here is a link to the summation above, with a slider for the $n$ value:
https://www.desmos.com/calculator/on90xvxmzx
and here is the algorithm I wrote to test my answer:
http://jonsprojects.biz/apr18tests/stackexchange.php?n=50&N=1000
You can change the $n$ parameter  (# of rolls) by changing $n=XX$, and the $N$ parameter (# of sets of rolls to generate) by changing $N=XX$ in the url. Don't set it too high or it won't work. My algorithm isn't very efficient.
If someone more knowledgeable than me wants to confirm if I've done this right, that would be great! Or perhaps if someone can simplify my answer a bit more, or has a simpler approach, that would also be great to see.

A: The method needs to be changed from a probability of getting any six doubles to a probability of getting six specific doubles. The probability of getting the first double is 6/36, the next double will be 5/36, the next 4/36 etc.
So the answer is  $6!/36^6$
Using the binomial formula doesn't work because the probability changes depending on a success.


text:
Q: Labeling specific countries using Natural Earth and QGIS I am new to QGIS 3 and want to make a simple map of research area. I'm using Natural Earth and I've identified the "10m_admin_0_map_units" is the file with the country names.
I just want a few country names to appear on the map of the Caribbean e.g. Barbados, Curacao, Cuba, Venezuela, Mexico. But I can't work out how to set up the rule based layer for this and I can't find a tutorial using this Version.
Could someone explain how I set-up the filter to only get a few country names?

A: You should to use in Properties --> Label --> Rendering --> Show Label

Click on "Edit..." and add the next expresion:
"name" in
 ( 'Venezuela' , 'Cuba' , 'Mexico' )
This is the result


text:
Q: Populate a new column in dataframe, based on values in differently indexed dataframe I have two dataframes, each with a different index, and I'd like to merge the 'hop' column from df2 into df1 based on the 'src' column in df1 and the index in df2.
df1
     src    dest    val
  0    1       2      X
  1    1       2      Y
  2    1       3      Z
  3    1       4      X
  4    2       2      X
  5    3       2      Y
  6    4       3      Z
  7    4       1      X

df1
 id  hop
  1    3
  2    5
  3    2
  4    3

i.e. the resulting dataframe needs to be merged as such:
df3
     src    dest    val    hop
  0    1       2      X      3
  1    1       2      Y      3
  2    1       3      Z      3
  3    1       4      X      3
  4    2       2      X      5
  5    3       2      Y      2
  6    4       3      Z      3
  7    4       1      X      3

I think it's probably a pd.merge() or pd.join() operation but I'm having a spot of bother with it :(


text:
Q: Check box Label click in iPad I have used some check boxes with Lable tag a reason behind it is if user click on text that appropriate check box select, but when I test this in iPad its work fine if user click on direct check box but when click on text its dose not response like its does in desktop
Please check this link

A: I had this issue, there's a simple CSS fix which I've wrote about on my blog here: http://www.tjcafferkey.me/problems-clicking-input-label-select-ios-safari/
The CSS is simple:

label > * {
  pointer-events:none;
}

A: Have you tried simply using an ID/FOR combination?
<input type="checkbox" id="mycheckbox" />

Click here

A: Learning from these two questions (3035954, 7358781), there seems to be a hack that will produce the behaviour you want:
Adding an empty onclick handler to each label should work, e.g.:
<input type="checkbox"> Checkbox

Or, alternatively, you could do this via some less intrusive javascript, e.g.:
$('label').click(function(){});


text:
Q: Filtering byte stream efficiently before converting to numpy array / pandas dataframe I'm looking for guidance on how to efficiently filter out unneeded parts of my data before converting to a numpy array and/or pandas dataframe. Data is delivered to my program as string buffers (each record separately), and I'm currently using np.frombuffer to construct an array once all records are retrieved.
The problem I'm having is that individual records can be quite long, thousands of fields, and sometimes I only want a small subset of them. Filtering out these unneeded fields adds steps and significantly slows down the data import though.
Without any filtering, my current process is:
# assume some function here that retrieves one record at a time and appends it to 'data'

data = [b'\x00\x00\x00\x00\x00\x00\xf0?one     \x00\x00\x00\x00\x00\x00Y@',
        b'\x00\x00\x00\x00\x00\x00\x00@two     \x00\x00\x00\x00\x00\x00i@',
        b'\x00\x00\x00\x00\x00\x00\x08@three   \x00\x00\x00\x00\x00\xc0r@',
        b'\x00\x00\x00\x00\x00\x00\x10@four    \x00\x00\x00\x00\x00\x00y@']

final_data = b''.join(data)

arr = np.frombuffer(final_data, dtype=struct_dtypes)
df = pd.DataFrame(arr)

# dataframe
    n1     ch     n2
0  1.0    one  100.0
1  2.0    two  200.0
2  3.0  three  300.0
3  4.0   four  400.0

My current solution for filtering is essentially:
final_data = b''.join(b''.join(buffer[offset: offset + 8] for offset in [0, 16]) for buffer in data)

struct_dtypes = np.dtype([('n1', 'd'), ('n2', 'd')])
arr = np.frombuffer(final_data, dtype=struct_dtypes)
df = pd.DataFrame(arr)

    n1     n2
0  1.0  100.0
1  2.0  200.0
2  3.0  300.0
3  4.0  400.0

That middle step to slice and rejoin each record makes filtering slower than just reading everything. If I construct the full array first and then return only the specified columns, isn't that just a waste of memory? What's an appropriate way to read only the portions of the string buffers I want?
Update using accepted answer
struct_dtypes = np.dtype({'names': ['n1', 'ch'],
                          'formats': ['d', '8V'],
                          'offsets': [0, 8],
                          'itemsize': 24})

final_data = b''.join(data)

arr = np.frombuffer(final_data, dtype=struct_dtypes)

A: You can specify an offset for each field during dtype construction:
struct_dtypes = np.dtype({'names': ['n1', 'n2'], 'formats': ['d', 'd'], 'offsets': [0, 16]})

or
struct_dtypes = np.dtype({'n1': ('d', 0), 'n2': ('d', 16)})

Update (see comments below):
If you don't read the last element in the record, you need to specify the itemsize:
struct_dtypes = np.dtype({'names': ['n1', 'ch'],
                          'formats': ['d', '8V'],
                          'offsets': [0, 8],
                          'itemsize': 24})


text:
Q: my login/index zul page is loading twice, where as i am only calling it once I am using zk ce version 6.5 and i have a problem. My login/index pages is being loaded twice.

*

*when i on logout button call this:
Executions.createComponents("login", center, null);
above page has two fields and i am using MVVM approach.
Now it loads fine, but as soon as i enter the username in the textbox or enter the password in textbox, page is automatically refreshed. I have checked in my code, i am not calling the above method anywhere else in a process here.
Please tell me why on textbox/password textbox i am getting this behaviour for the loginpage. once it's reloaded twice, it gets the username and takes me to home page. now i logout and same scenario.
for two times, i am getting call to this method, once is obvious, bacause on logout i called it, but on entering any text in textbox and removing the focus from it. then this method is again called.
@AfterCompose
public void afterCompose(@ContextParam(ContextType.VIEW) Component view){
    Selectors.wireComponents(view, this, false);
 }

I have inspected my code too, there is no event on any of the textfield.
login.zul
<zk>
    <window id="loginWin" border="none" width="100%" height="100%"
        apply="org.zkoss.bind.BindComposer"
        viewModel="@id('vmc') @init('com.example.LoginViewModel')"
        validationMessages="@id('vmsgs')">

        <borderlayout>
            <west border="normal" size="70%" title="What Intelliops Do?">

                    asdasd as asd a d asdasd a sd asd asasd asd d asdasd as
                    d a d asdasd a sd asd asasd asd a d asdasd a sd asd
                    asasd asd a d asdasd a sd asd asasd asd

            </west>
            <east border="normal" size="30%" title="Login">

                    <grid sizedByContent="true"
                        form="@id('lv') @load(vmc.userDto)
                       @save(vmc.userDto, before='loginButtonInvoke')
                       @validator('com.example.LoginValidator')">
                        <columns>
                            <column width="50%"></column>
                            <column width="50%"></column>
                        </columns>
                        <rows>
                            <row align="left" width="100%"
                                style="background:white;.row:hover{background-color: #fff};border:none">
                                <cell style="text-align:right">
                                    User Name
                                </cell>
                                <cell>
                                    <textbox id="userNameTextBox" type="text"
                                        value="@bind(lv.user.username)" maxlength="50" />
                                    <image src="@load(vmsgs['userNameTextBoxError'])" width="12px"
                                        height="12px" tooltiptext="@load(vmsgs['userNameTextBox'])"></image>
                                </cell>
                            </row>
                            <row width="100%"
                                style="background:white;.row:hover{background-color: #fff};border:none">
                                <cell style="text-align:right">
                                    Password
                                </cell>
                                <cell>
                                    <textbox id="passwordTextBox" type="password"
                                        value="@bind(lv.user.password)" maxlength="20" />
                                    <image src="@load(vmsgs['passwordTextBoxError'])" width="12px"
                                        height="12px" tooltiptext="@load(vmsgs['passwordTextBox'])" />
                                </cell>
                            </row>
                            <row width="100%"
                                style="background:white;.row:hover{background-color: #fff};border:none">
                                <cell style="text-align:right">
                                    <button id="loginButton" label="Login"
                                        onClick="@command('loginButtonInvoke')" />
                                </cell>
                                <cell>

                                </cell>
                            </row>
                            <row spans="2" width="100%"
                                style="background:white;.row:hover{background-color: #fff};border:none">
                                <cell colspan="2" style="text-align:right">

                                        Forgot Password?

                                </cell>
                            </row>
                        </rows>
                    </grid>

            </east>
        </borderlayout>
    </window>
</zk>

loginviewmode class
package com.example;

import org.apache.log4j.Logger;
import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Label;
import org.zkoss.zul.Textbox;

import com.example.UserDTO;
import com.example.IUserService;
import example.Pages;
import example.TemplateUtil;
import example.UserUtil;

public class LoginViewModel{

    private Logger logger = Logger.getLogger(this.getClass().getName());

    IUserService userService = (IUserService)SpringUtil.getBean("userService");

    UserDTO userDto = new UserDTO();

    private static final String USER_ROLES = "userRoles";
    private static final String MASTER = "master";

    @Wire("#userNameTextBox")
    Textbox userNameTextBox;

    @Wire("#passwordTextBox")
    Textbox passwordTextBox;

    @Wire("#loginErrorLabel")
    Label loginErrorLabel;

    @AfterCompose
    public void afterCompose(@ContextParam(ContextType.VIEW) Component view){
        Selectors.wireComponents(view, this, false);
     }

    @Command("loginButtonInvoke")
    public void loginButtonInvoke(){
        logger.info("LoginViewModel:afterCompose >>>>>>>>>>>>>>>");
        logger.info("loginButtonInvoke: " + userDto.getUserIntelliOps().getUsername() + " " + userDto.getUserIntelliOps().getPassword());
        userDto = userService.getUserAuthentication(userDto);

        if(userDto!=null){
            UserUtil.setSession(userDto);
            logger.info("loginButtonInvoke:userDto!=null ");
            /*List<ViewObjectOperation> list = userService.getAllOtherOperationsService().userAuthorizationMatrix(userDto.getUserIntelliOps().getRoles().get(0).toString());*/
            //List<ViewObjectOperation> list = userService.getAllOtherOperationsService().userAuthorizationMatrix(3+"");
            //logger.info("asdasdas   " + list.size());
            /*getUserAuthorizedMenu*/
            //TODO what is the following line doing here????
            userService.getUserAuthorizedMenu();

            TemplateUtil.loadContent(Pages.HOME_FILE,true);
        }else{
            if(userDto==null){
                userDto = new UserDTO();
            }
        loginErrorLabel.setValue("Invalid username or password.");
        }

    }

    public UserDTO getUserDto() {
        return userDto;
    }

    public void setUserDto(UserDTO userDto) {
        this.userDto = userDto;
    }

}

TemplateUtil class to draw the pages
package com.example;

import org.apache.log4j.Logger;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Path;
import org.zkoss.zul.A;
import org.zkoss.zul.Borderlayout;
import org.zkoss.zul.Button;
import org.zkoss.zul.Center;
import org.zkoss.zul.Include;
import org.zkoss.zul.North;

public class TemplateUtil {

    static Logger logger = Logger.getLogger(TemplateUtil.class.getName());

    public static void loadContent(String contentPage, boolean isMenu) {

        logger.info("TemplateUtil: loadContent().......... ");

        Borderlayout mainlayout = (Borderlayout) Path.getComponent("/main/mainLayout");
        North topHeader = mainlayout.getNorth();

        topHeader.getFellow("menuDiv").setVisible(isMenu);

        //TODO remove the following logger

        if(isMenu==true ){
            anchorUsername.setLabel(UserUtil.getUserName());
            logger.info("isMenu==true....");
            Executions.createComponents(Pages.MENU_FILE, topHeader.getFellow("menuDiv"), null);
            UserUtil.setSession(true);
        }

        topHeader.invalidate();

        Center center = mainlayout.getCenter();
        center.getChildren().clear();
        logger.info("contentPage: " + contentPage);
        Executions.createComponents(contentPage, center, null);

    }

}

please help me on this
Let me update you. 1. first time no refresh 2. after login, when i click on logout and go to login page, as soon as i add the value in any of the textbox, pages refreshes. no action is written on any of those fields.

A: I am not able to understand why you are doing ...
Executions.createComponents("login", center, null);

When you going for logout
From my understanding you can do this thing like this...
//Executions.getCurrent().getDesktop().invalidate();//Condition base if you needed use it otherwise dont use it
Executions.getCurrent().getSession().invalidate();
Executions.sendRedirect("/login.zul");


text:
Q: Evaluating typehints for numpy.radians and float/array input elements I have a function that looks as following:
import numpy as np

def test() -> None:
    a = map(np.radians, (1.,2.,np.array([1,2,3])))

Evaluating this with mypy returns the error message
error: Argument 1 to "map" has incompatible type "ufunc"; expected "Callable[[object], Any]"

Using only floats or only arrays as the input list for map poses no problem here, the issue arises when the input list/tuple contains objects of both types. At runtime this poses no problem either.
How can I modify this function to satisfy mypy's requirements and make it typesafe?

A: The problem here is that mypy infers the type of the elements of (1., 2., np.array([1,2,3])) as object (not as Union[float, np.ndarray] as you'd hope here), which then is incompatible with np.radians.
What you can do as a workaround is giving your tuple/list an explicit type that is compatible with both the tuple/list and the argument of np.radians. E.g.:
from typing import Sequence, Union
import numpy as np

def test() -> None:
    x: Sequence[Union[float, np.ndarray]] = (1., 2., np.array([1,2,3]))
    a = map(np.radians, x)

There is an open mypy github issue that seems similar, though maybe
not exactly the same: python/mypy#6697.

A: With all due respect, the right solution is to tell MyPy to ignore this line.
import numpy as np

def test() -> None:
    a = map(np.radians, (1.,2.,np.array([1.,2.,3.]))) # type: ignore

PS: You always have the very inadvisable option to edit the numpy library and fix the call signature of _UFunc_Nin1_Nout1 to accept the object type (in addition to ArrayLike). The edit below makes your mypy error message go away.
--- a/typing/_ufunc.pyi
+++ b/typing/_ufunc.pyi
@@ -86,21 +86,21 @@ class _UFunc_Nin1_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
         casting: _Casting = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
         signature: Union[str, _2Tuple[Optional[str]]] = ...,
         extobj: List[Any] = ...,
     ) -> Any: ...
     @overload
     def __call__(
         self,
-        __x1: ArrayLike,
+        __x1: ArrayLike | object,
         out: Union[None, NDArray[Any], Tuple[NDArray[Any]]] = ...,
         *,
         where: Optional[_ArrayLikeBool_co] = ...,
         casting: _Casting = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
         signature: Union[str, _2Tuple[Optional[str]]] = ...,
         extobj: List[Any] = ...,
     ) -> NDArray[Any] | Any: ...

References

*

*MyPy Documentation at Readthedocs, MyPy Common Issues and Solutions, Spurious errors and locally silencing the checker.

*type: ignore is a part of PEP484 for a reason.

*Numpy _ufunc.py declares the offending type specification _UFunc_Nin1_Nout, https://github.com/numpy/numpy/blob/main/numpy/typing/_ufunc.pyi

A: I don't know if it was intentional, but you didn't use dots in the array.
import numpy as np

def test() -> None:
    a = map(np.radians, (1.,2.,np.array([1.,2.,3.])))


text:
Q: Entity framework: add info to relational tables but keep EF object format If I have 3 tables:

Customer CustID Name Email
List ListID Title
CustomersLists CustID ListID

Entity Framework makes it very easy to grab lists of a customer.
db.Customers.FirstOrDefault(c => c.Name == "Bob").Lists

I need save a timestamp of the creation of the relational table so I can see when the customer was added to a list.
I don't want to add a column 'timestamp' to the relational table because it will mess with the intuitive LINQ functionality, as the table CustomersLists appears instead of Customer.Lists.
I have about 12 tables that need to have this timestamp, most of which don't have many to many relationships. Just fishing to see if anyone has a really good solution I'm overlooking.

A: Do not map the timestamp in EF mapping. And set the default value for that timestamp column on database layer to: getDate(). It will set it to current "datetime" on insert.


text:
Q: Best practices to decide base resolutions for images and drawables I understand that for performance, we should provide different resolutions for our drawables based on this scale:
•  xhdpi: 2.0
•  hdpi: 1.5
•  mdpi: 1.0 (baseline)
•  ldpi: 0.75
Now, if I want to create an image that for example will show in the center of the screen or as a background for a button, how to decide the starting resolution?
My practice is, for example, if I want an image to take 100 dp width and 50 dp hight on the screen, I would design a 200*100 px image, which is double the dp amount, so it shows up crisp. Should I consider this particular image to be the hdpi, xhdpi, xxhdpi, or mdpi? so I scale it accordingly.
Thanks for any insights.

A: If you want your image to be 100dp x 50dp, and your actual bitmap is 200px x 100px, then you would put that bitmap in res/drawable-xhdpi/. 200/100 is 2.0. 100/50 is 2.0. -xhdpi has a ratio of 2.0 over -mdpi, and in -mdpi, 1dp is 1px.


text:
Q: Show that $3+\omega^2\not=\omega^2+3$ where $\omega$ denotes the least infinite ordinal I understand this shouldn't work due to ordinals not being associative, commutative or distributive but the question says to include all the details in my argument. I'm not sure how I'm supposed to expand upon this further outside of stating basic laws of ordinals. I know that
$3+\omega \not= \omega +3$
So is the proof very similar? I'm really not sure how to even begin approaching this.


text:
Q: Tumblr photoset's iframe loading 404 Not Found I haven't found anyone with this problem either in stackoverflow or anywhere else and Tumblr support is being obtuse.
A few photosets on my tumblr are mysteriously loading a 404 not found page within the photoset iframe. When I view the source and click on the content link for that photoset, I can load it. Right now it is happening to the second post down on http://margodunlap.com/tagged/parsonssproutlogo, but earlier that post was fine and a different photoset on a different page was 404-ing. That photoset cleared up.
If it's useful, here is the code from the problem component/post:

My instinct is that this is tumblr's servers messing up but is it possible it is a problem with my photoset script? It is below - I believe it is a common one.
$(document).ready(function(){
$(".photoset").each(function() {
$(this).width('800px');
var newSrc = $(this).attr("src").replace('500','800');
$(this).attr("src", newSrc);
});

$(function(){
var iFrames = $('.photoset');

function iResize() {
for (var i = 0, j = iFrames.length; i < j; i++) {
    iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';}
}

if ($.browser.safari || $.browser.opera) {
    iFrames.load(function(){
        setTimeout(iResize, 0);
    });

    for (var i = 0, j = iFrames.length; i < j; i++) {
        var iSource = iFrames[i].src;
        iFrames[i].src = '';
        iFrames[i].src = iSource;
    }
} else {
    iFrames.load(function() {
        this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
    });
}
});
});

Also I don't know if this is relevant but Chrome's java console is telling me that a few other scripts on the page (tumblr's marketing trackers and my google analytics) are failing to load. Please know I'm a designer, not a programmer, and I'm trying my best for this to not be a dumb question. Basically I've spent six months tweaking this website, my portfolio, to be perfect and 12 hours before I was set to submit it as my grad school application, it does this. Huge lesson learned about hosting important things in reliable places but in the meantime please help if you can, I'm desperate and sad.
I've taken the problem post down because of the whole submitting to grad school thing, but if anyone knows what the problem with this might be I'd really appreciate a permanent fix.


text:
Q: Vue.js setup() and mounted() I am fairly new to Vue.js and am currently working on a project. I currently have some constants declared in setup(), lets call one of the constant "c", and I want to get them from within mounted(). I realized that I can still console.log(this.c) within mounted() to get the constant printed out but when I try to console.log(this.c) within a function in mounted() I can no longer get it and I get an error Uncaught (in promise) TypeError: Cannot read properties of undefined.
Why is this so? And what work arounds are there?
Example:
    setup() {
       const c = ref(1)
    },

    mounted() {
       console.log(this.c) // prints 1 on console

       function doesSomething() {
          console.log(this.c) // TypeError: Cannot read properties of undefined
          ...
       }
    }

A: The function doSomething in the mounted hook should be declared with an arrow function instead, since function declaration has its own this binding:
mounted() {
  console.log(this.c)

  const doesSomething = () => {
    console.log(this.c) // Ok
  }
}

A: mounted is an option in the options api which is different than the composition api using the setup hook, you could use onMounted hook in setup to replace mounted option:
import {onMounted} from 'vue';

setup(){
 let c='some content'

 onMounted(()=>{
    console.log(c)// don't use this keyword
  })

}


text:
Q: Highchart Stock gui does not work in Angular 8 I'm trying to  make a graph with Highchart stock in Angular 8.
I want to add "FullScreen" button  so I did the following :
In  my component I imported  required modules :
import * as Highcharts from "highcharts/highstock";
import * as HStockTools from "highcharts/modules/stock-tools";
import * as HFulScreen from "highcharts/modules/full-screen";

HFulScreen(Highcharts)
HStockTools(Highcharts)

In my CSS file I added :
@import "https://code.highcharts.com/css/stocktools/gui.css";
@import "https://code.highcharts.com/css/annotations/popup.css";

Graph options :
stockTools: {
    gui: {
      buttons: [ 'fullScreen', 'separator', 'saveChart' ]
    }
  },
  chart: {
      height : "600px"
  },
  tooltip: {
    shared: true ,
    split :false
  },
  credits: {
    enabled: false
  },
  yAxis: [{
    labels: {
      align: 'left'
    },
    height: '60%',
    resize: {
      enabled: true
    }
  }, {
    labels: {
      align: 'left'
    },
    top: '60%',
    height: '20%',
    offset: 0
  }, {
    top: '80%',
    height: '20%'
  }],

  series: [{
    type: 'line',
    id: 'activa-ohlc',
    name: 'AAPL Stock Price',
    data: "ohlc"
  }, {
    type: 'column',
    id: 'aapl-volume',
    name: 'AAPL Volume',
    data: "volume"
  }],

Package.json with Highchart's version :
"highcharts": "^8.0.3",
"highcharts-angular": "^2.4.0",

But I'm  getting this error :
ERROR in ../node_modules/highcharts/modules/full-screen.d.ts:17:21 - error TS2304: Cannot find name
'Fullscreen'.

17         fullscreen: Fullscreen;

I don't know if I'm doing something wrong.
Thanks for your help

A: I found a similar issue reported on the highcharts-angular repository.
https://github.com/highcharts/highcharts-angular/issues/259#issuecomment-762787358
It looks like the Fullscreen module requires the Exporting module so to fix the problem you could try importing & initializing the Exporting module.
import HC_exporting from 'highcharts/modules/exporting';
import HC_FullScreen from 'highcharts/modules/full-screen';

HC_exporting(Highcharts);
HC_FullScreen(Highcharts);

Hope that solves your problem. If the following solution won't help please recreate the issue in an online editor, so I can check what is not working or what could be done.


text:
Q: How can I clear and recreate the flyway-play generated database during testing I am using Play 2.4 with the Flyway-Play module.
Is there are way to clean and recreate the database between tests using this plugin? Some of my unit test have database effects which are not trivial to reverse, and it would be nice to be able to start afresh after these tests.
The documentation for the flyway-play module states:

In Test mode, migration is done automatically.

However, this seems be only once before running all tests. It would be nice to have programmatic control when preparing and cleaning up tests.

A: Not sure how flyway is integrated in the play framework (no experience with that), but it looks like what you are looking for is the flyway cleancommand.

Drops all objects in the configured schemas.

Flyway documentation: clean


text:
Q: SQL query does not return the data in the columns I am trying to run a query to get all columns contained in the table if the table exist.
IF (EXISTS (SELECT *  FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'2000064'))

The query gets executed but does not return anything! It just say "Query executed".
I have tried in several ways: TABLE_NAME = 2000064, TABLE_NAME = '2000064' but nothing is returned.
The table exists, and there are data in it.
What am I doing wrong?
EDIT:
I need to return the data contained in the table if the table exists.

A: To get information about the column, uou can just run:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'2000064';

(Note:  you should include TABLE_SCHEMA as well to find a specific table.)
If the table does not exist, then you will get no rows back.  Putting it in an if exists statement, runs the query and would then run whatever is in the then clause.  Your question doesn't have the then part of the statement.


text:
Q: I try to install something using poetry I have connection error I try to install numpy using poetry but I have this error when i use the home network:
[ConnectionError]
HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/c5/63/a48648ebc57711348420670bb074998f79828291f68aebfff1642be212ec/numpy-1.19.4.zip (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f041865a250>: Failed to establish a new connection: [Errno 111] Connection refused'))