text:
Q: Python 3 - datetime Class/module Error in VS Code (Windows) I am trying to print a simple statement that will show today's date. But no matter how I try, I keep getting the same error. Here are some examples:
    import datetime

    today = datetime.datetime.date.today()
    print(today)

I've also tried:
    from datetime import datetime

    today = datetime.date.today()
    print(today)

Either way, this is the error message I get in the terminal:
"AttributeError: partially initialized module 'datetime' has no attribute 'date' (most likely due to a circular import)"
Any advice? I'm going nuts and yet, it should be so simple! @_@

A: Your file name is the same as the package:
Change it for antoher name, like  'Time_example.py'


text:
Q: Traefik 2 middleware is working on https, but not http entry points I'm trying to setup a route do a basic 301 redirect with the added benefit of supporting both HTTP and HTTPS requests. Expected results would be that requests to http://subdom.domain.org or https://subdom.domain.org would receive a 301 and be forwarded to https://othersub.domain.org/route. Actual results is that https://subdom.domain.org 301's as expected, but http://subdom.domain.org 404's.  With the config, you can see I've tried doing both an elevate to HTTPS with the hopes that the rule might be caught there, but with the way the middleware is configured, I would expect it would work in either scenario.
Here's my current config:
http:
  routers:
    subdom.domain.org:
      entryPoints:
        - web
        - web-secure
      middlewares:
        - https-redirect # I've tried with this on and off
        - sudbdom-redirect
      service: dummy
      rule: Host(`subdom.domain.org`)
      tls:
        certResolver: letsEncryptResolver

  middlewares:
    https-redirect:
      redirectScheme:
        scheme: https
    subdom-redirect:
      redirectRegex:
        regex: ".*"
        replacement: "https://othersub.domain.org/route"
        permanent: true

  services:
    dummy:
      loadBalancer:
        servers:
        - url: localhost

I was originally having trouble matching specific regex patterns for the redirect, but in realizing I didn't really need to scope the pattern at all given that I'm applying it per route, a wildcard match seems to work quite well there.  Any thoughts or suggestions are appreciated. Thanks!

A: You should try to make 2 different router one for web entry point where you can perform redirection and 2rd one for redirectRegex where you can redirect your application to different url.

A: Following TLS section from official documentation:

When a TLS section is specified, it instructs Traefik that the current router is dedicated to HTTPS requests only (and that the router should ignore HTTP (non TLS) requests).

Solutions:
1. Define separate routers (for http and https), but it noisy for multiple services.

If you need to define the same route for both HTTP and HTTPS requests, you will need to define two different routers: one with the tls section, one without.

Example from documentation
2. Disable TLS for router
traefik.http.routers.YOUR-SERVICE.tls=false
Example:
services:
  mailhog:
    image: mailhog/mailhog
    networks:
      - traefik-public
    deploy:
      placement:
        constraints:
          - node.role != manager
      labels:
        - "traefik.enable=true"
        - "traefik.http.routers.mailhog.rule=Host(`mailhog.somehost.ru`)"
        - "traefik.http.routers.mailhog.service=mailhog"
        - "traefik.http.routers.mailhog.entrypoints=web,websecure"

        # Should be false
        - "traefik.http.routers.mailhog.tls=false"

        - "traefik.http.middlewares.redirectos.redirectscheme.scheme=https"
        - "traefik.http.routers.mailhog.middlewares=redirectos"

        - "traefik.http.services.mailhog.loadbalancer.server.port=8025"
        - "traefik.tags=traefik-public"
        - "traefik.docker.network=traefik-public"

redpajama_set_name: RedPajamaStackExchange


text:
Q: displaying multiple divs columns within a list item on mobile Im building a football app (using phonegap, backbone, require and topcoat.io) allowing users to pick their man of the match (MOTD).
In the MOTD template, I want to display the player name, position, a link to their full external profile and a radio button. The HTML looks like:

            <input type="radio" name="player_id" id="player_516" value="516">

Robin van Persie

Forward

            More

The CSS is:
.player-more{
    width:48%;
    float:left;
}

.player-details{
    vertical-align: middle;
    float:left;
    width:48%;
}

But it comes out looking like so on a mobile:
list example http://match.webintelligence.ie/img/motm.png
Maybe I'm trying to include too much information in each list item. Any suggestions as to how I could present this better? Maybe I dont need the radio buttons. Instead, if a user clicks anywhere on the list, it will highlight it and this will be their selection. Except if the click "more", in which case the external link will show...

A: This happens because your p elements are block-level elements. This means they will occupy their own line. Change the p to an inline element.
p.player-name {
  display: inline;
}

Or use a span element, which is inline by default.


text:
Q: What is facility level? My castle refuses to be upgraded until facility level 100, but I am currently at 59.  How is this calculated?  I tried adding the levels of all my buildings, (14 gold mine + 14 gold mine + 15 dragon tree + 9 fire orb + 9 wind orb + 3 castle) but that comes out to 64.  Even ignoring the castle, it's 61.  What all goes into calculating facility level?

A: According to the Dragalia Lost Wiki:

The Facility Level is the sum of the levels of all facilities, except for decorative facilities. Halidom and Smithy levels also contribute to the facility level.

You may have been calculating decorative facilities also.


text:
Q: MySQL: Create database like? In MySQL I want to clone certain databases. Is there such a thing as a
CREATE DATABASE LIKE <template database here>

command?
I know, there is
CREATE TABLE LIKE

A: If you want to clone a database, my_database for example, you'll want to run a mysql query and then run a command in the linux terminal:
mysql> CREATE DATABASE my_database_copy;
linux terminal (on the machine with the database):
mysqldump -u username -p my_database | mysql -u username -p my_database_copy
From there you'll likely get 2 "Enter password:" prompts....just input your password, press enter, and wait :)

A: There is no such command.
But you can create a backup (SQL file) of your database, and then restore all objects in the new database.
Also, you can use GUI tools in dbForge Studio for MySQL (free express edition) - Backup or restore a database. It will help you quickly recreate database and its contents.

A: *

*I will prefer taking backup and restoring

*If it's just for cloning, I will go for MySQLDump

This is just one another way of doing:
mysql> create database new_dbname;

mysql> select concat('create table
new_dbname.',TABLE_NAME,' like wings2020.',TABLE_NAME,'; insert into
new_dbname.',TABLE_NAME,' select * from ol_dbname.',TABLE_NAME,';')
from information_schema.tables where table_schema = 'old_dbname'  into
outfile '/tmp/a.txt';

mysql> source /tmp/a.txt;


text:
Q: Elliptic regularity for two dimensional domains Suppose $ \Omega$ is a smooth bounded domain in $ R^2$.  I am interested in the regularity of solutions to
$$-\Delta u(x) = f(x)  \mbox{ in } \Omega$$ with $ u=0$ on $ \partial \Omega$.
If $ f \in L^1(\Omega)$ then one just misses $ u \in C(\Omega)$.    There was a result of Wente that said something like if $ f= \nabla a \cdot \nabla^\perp b$ (where $a$ and $b$ have certain regularity assumptions,  but not really enough to see the right hand side is better than $L^1$)  then $ u \in C(\Omega)$.   I believe there is also a result that says something like if $f$ in a certain Hardy space (I am not familiar with these spaces) then one also has $ u$ continuous.

QUESTION. I recall someone mentioning  a version similar to the above.  They had   said if $ f(x) ={\rm div}(F(x))$ where  $ F \in W^{1,1}(\Omega, R^2)$  then $ u \in C(\Omega)$.  So my question is.  Is this correct or not ?

Thanks

A: It is true, but you must use the fact that $W^{1,1}$ is embedded in the Lorentz space $L^{2,1}$, see Helein's book, Harmonic maps, conservation laws and moving frames, theorem 3.3.10, you will find all the material about Hardy, Lorentz spaces in chapter 3 and more  generally this book is just awsome!!
Then using the fact the gradient of the  Green function $G$ is in $L^{2,\infty}$ because like $\frac{1}{\vert x\vert}$. Then you have $u=\nabla G * F$ is continuous.


text:
Q: C# Refresh of the event in debug mode Here I try to recover some values into variables.
I send a message to a server which returns different values. These values are read in a thread. I catch all values returned by the server with an event.
I try to store it but I have a problem: when I use my debugger I can see all refresh of my event only at the end (at display time in a WindowsForm).
Example with code:
ModuleProtocole.SendMessage("VER"); // after this command I will receive the version
ModuleProtocole.SendMessage("NA1"); // after this command I will receive the name of hardware

public void MessageRec(object source, MesACK e)
{
 ReceptionMessage = e.getinfos(); //My globale variable ReceptionMessage is refresh for every new value on port
}

if(ReceptionMessage[0] == "M") //When i debug line by line ReceptionMessage is always = "Monitor" but at the end of debug all variable like "Name" is completed by the good word
   Version = ReceptionMessage;
else Name=ReceptionMessage;

So my question is: Why my event is refresh only one time in debug? In my code, it should be trigger 2 times but only the first one is show and apply to variables in debug console.

A: I colleague found the solution: in the subscribe function to the event, add Console.Writeline(ReceptionMessage); then you can see refresh of ReceptionMessage.
Event is complicated in debug mode, this is the best way for see the refresh !
public void MessageRec(object source, MesACK e)
{
 ReceptionMessage = e.getinfos();
 Console.Writline(ReceptionMessage);
}


text:
Q: FatalErrorException: Error: Call to a member function getId() on a non-object in ...PostListener.php line 20 I'm new in Symfony2. I've a task to create blog. One of the necessary is displaying most popular posts. So I think that the best varient is create listener. It will be call, when visiter will read post. And listener will increment onе of the fild in database(MySQL). I create method in repository, which makes selection by this field. And also create Action, which renders posts by this selection. But when I try to read post, a have error:
FatalErrorException: Error: Call to a member function getId() on a non-object in /var/www/blo/src/Blog/Bundle/BlogBundle/EventListener/PostVisitedListener.php line 20.
Please, help me.
This my Entity (Post):
namespace Blog\Bundle\BlogBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Post
 *
 * @ORM\Table(name="post")
 * @ORM\Entity(repositoryClass="Blog\Bundle\BlogBundle\Entity\PostRepository")
 */
class Post
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

/**
 * @var string
 *
 * @ORM\Column(name="title", type="string", length=255)
 * @Assert\NotBlank
 * @Assert\Length(min="13", max="255")
 */
 private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="author", type="string", length=100)
     * @Assert\NotBlank
     * @Assert\Length(min="13", max="100")
     */
 private $author;

/**
 * @var string
 *
 * @ORM\Column(name="post", type="text")
 * @Assert\NotBlank
 * @Assert\Length(min="100")
 */
private $post;

/**
 * @var string
 *
 * @ORM\Column(name="image", type="string", length=100)
 */
private $image;

/**
 * @Gedmo\Timestampable(on="create")
 * @ORM\Column(name="createdAt", type="datetime")
 *
 */
private $createdAt;

/**
 *
 * @ORM\Column(name="tags", type="text")
 */
private $tags;

/**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="posts")
 */
private $category;

/**
 * @ORM\OneToMany(targetEntity="Comment", mappedBy="post")
 */
private $comments;

/**
 * @var integer
 *
 * @ORM\Column(name="visitedIncrement", type="integer")
 */

private $visitedIncrement;

public function __construct()
{
    $this->comments = new ArrayCollection();
}
/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set title
 *
 * @param string $title
 * @return Post
 */
public function setTitle($title)
{
    $this->title = $title;

    return $this;
}

/**
 * Get title
 *
 * @return string
 */
public function getTitle()
{
    return $this->title;
}

/**
 * Set author
 *
 * @param string $author
 * @return Post
 */
public function setAuthor($author)
{
    $this->author = $author;

    return $this;
}

/**
 * Get author
 *
 * @return string
 */
public function getAuthor()
{
    return $this->author;
}

/**
 * Set post
 *
 * @param string $post
 * @return Post
 */
public function setPost($post)
{
    $this->post = $post;

    return $this;
}

/**
 * Get post
 *
 * @return string
 */
public function getPost()
{
    return $this->post;
}

/**
 * Set image
 *
 * @param string $image
 * @return Post
 */
public function setImage($image)
{
    $this->image = $image;

    return $this;
}

/**
 * Get image
 *
 * @return string
 */
public function getImage()
{
    return $this->image;
}

/**
 * Set tags
 *
 * @param string $tags
 * @return Post
 */
public function setTags($tags)
{
    $this->tags = $tags;

    return $this;
}

/**
 * Get tags
 *
 * @return string
 */
public function getTags()
{
    return $this->tags;
}

/**
 * Set category
 *
 * @param $category
 * @return $this
 */
public function setCategory($category)
{
    $this->category = $category;

    return $this;
}

/**
 *  Get category
 *
 * @return integer
 */
public function getCategory()
{
    return $this->category;
}

/**
 * Set comments
 *
 * @param string $comments
 * @return Post
 */
public function setComments($comments)
{
    $this->comments = $comments;

    return $this;
}

/**
 * Get comments
 *
 * @return string
 */
public function getComments()
{
    return $this->comments;
}

/**
 * @param \DateTime $createdAt
 */
public function setCreatedAt($createdAt)
{
    $this->createdAt = $createdAt;

    return $this;
}

/**
 * @return \DateTime
 */
public function getCreatedAt()
{
    return $this->createdAt;
}

/**
 * @param int $visitedIncrement
 */
public function setVisitedIncrement($visitedIncrement)
{
    $this->visitedIncrement = $visitedIncrement;

    return $this;
}

/**
 * @return int
 */
public function getVisitedIncrement()
{
    return $this->visitedIncrement;
}

public function __toString()
{
    return $this->getTitle();
}

}

This is my PostRepository
public function visitedIncrement($id)
{
    $query = $this->getEntityManager()
        ->createQuery(
            'UPDATE BlogBlogBundle:Post p
             SET p.visitedIncrement = p.visitedIncrement + 1
             WHERE p.id = :post_id')
        ->setParameter(':post_id', $id);

    $query->execute();

This is my PostVisitedEvent

namespace Blog\Bundle\BlogBundle\Event;
use Blog\Bundle\BlogBundle\Entity\Post;
use Symfony\Component\EventDispatcher\Event;
class PostVisitedEvent extends Event
{
    protected $post;
/**
 * @param Post $post
 */
public function setPost(Post $post)
{
    return $this->post;
}

/**
 * @return Post
 */
public function getPost()
{
    return $this->post;
}

}

This is my PostVisitedListener
namespace Blog\Bundle\BlogBundle\EventListener;

use Blog\Bundle\BlogBundle\Entity\PostRepository;
use Doctrine\ORM\EntityManager;
use Blog\Bundle\BlogBundle\Event\PostVisitedEvent;

class PostVisitedListener
{
protected $repository;

public function __construct(PostRepository $repository)
{
    $this->repository = $repository;
}

public function onPostVisited(PostVisitedEvent $event)
{
    $this->repository->visitedIncrement($event->getPost()->getId());
}

This is my Action (it opens post and gives a opportunity to create comment):
    public function showPostAction($id)
    {
        $postRepository = $this->container->get('blog_blog_bundle.post.repository');
        $post = $postRepository->find($id);
    if (!$post) {
        throw $this->createNotFoundException('The post is not found!');
    }
    $commentRepository = $this->container->get('blog_blog_bundle.comment.repository');
    $comments = $commentRepository->findCommentForPost($post->getId());

    $event = new PostVisitedEvent();
    $event->setPost($post);

    $eventDispatcher = $this->get('event_dispatcher');
    $eventDispatcher->dispatch('blog_blog_bundle.post_visited', $event);

    return $this->render('BlogBlogBundle:Default:showPost.html.twig', array(
        'post' => $post,
        'comments' => $comments,
    ));
}

Yuo can see, that I also create services for repositories and listener. There are:
service id="blog_blog_bundle.post.repository"  class="Blog\Bundle\BlogBundle\Entity\PostRepository" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"
        argument>BlogBlogBundle:Post argument
    service

    service id="blog_blog_bundle.comment.repository"       class="Blog\Bundle\BlogBundle\Entity\CommentRepository" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"
        argument BlogBlogBundle:Comment argument
    service

    service id="blog_blog_bundle.post_visited_listener" class="Blog\Bundle\BlogBundle\EventListener\PostVisitedListener"
        argument type="service" id="blog_blog_bundle.post.repository"
        tag name="kernel.event_listener" event="blog_blog_bundle.post_visited" method="onPostVisited"
    service

Please, help me.

A: public function onPostVisited(PostVisitedEvent $event)
{
    if (!($event->getPost() instanceof PostInterface)) return;
    $this->repository->visitedIncrement($event->getPost()->getId());
}

PostInterface is not a symfony interface. You have to code it. Asking for interface is better than asking for a concrete instance because symfony sometimes uses proxy classes instead of concrete classes.


text:
Q: Why does a short line segment appear instead of a full line graph? My custom Canvas extends Canvas, and overrides the paint() method as below
@Override
public void paint(Graphics g) {

    Rectangle bounds = getBounds();

    g.translate(0, (bounds.y + bounds.height) / 2);

    int maxX = (int) bounds.getMaxX();

    g.drawLine(currX, currY, currX + 5, m_nextY);

    currX = currX > maxX ? maxX : currX + 5;
    currY = m_nextY;

    if (currX >= maxX) {
        currX = 0;
    }

}

int currX = 0;
int currY = 0;
int m_nextY;

public void setNextY(int pNext) {
    m_nextY = pNext;
}

The program entry-point runs a loop to retrieve random numbers which are scaled and set the location for the Y coordinate like this
java.util.Random engine = new Random();

while (Thread.currentThread().isAlive()) {
        myCanvas.setNextY((int) (engine.nextFloat() * -15f));
        myCanvas.paint(getGraphics());
        try {
            Thread.sleep(300);
        } catch (InterruptedException ex) {
         // Balderdash!
        }

    }

The expected output here should have been a line-graph. What appears instead is a single short segment with varying position and attitude.
What am I doing wrong here?

A: *

*You normally never call paint() from your code. paint() will be called from the AWT framework. So your loop should go into the paint() method.

*What is engine ?


text:
Q: Unable to cast object of type 'System.Collections.Generic.HashSet I am trying to use these classes with EF Code-First to add data to the DB. After I populate the object and try to populate the context "dbContext.Tracks.Add(t1)". I get the error "Unable to cast object of type 'System.Collections.Generic.HashSet`1[Vinyl7]' to type 'Vinyl7'" Could anyone point out what I am missing?
Public Class Vinyl7

    <Key>
    Public Overridable Property mediaId As Long
    Public Overridable Property parentMediaId As System.Nullable(Of Long)
    Public Overridable Property side As String

    <ForeignKey("mediaId"), Required>
    Public Overridable Property track As Track

End Class

Public Class Track

    <Key>
    Public Property mediaId As Long
    Public Property title As String

    Public Overridable Property Vinyl7T As ICollection(Of Vinyl7) = New HashSet(Of Vinyl7)
End Class

This is my Context
Public Class MediaRepo : Inherits DbContext

    Public Sub New()
        MyBase.New("name=MediaDB")

    End Sub

    Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)

    End Sub

    Public Property Vinyl7s As DbSet(Of Vinyl7)
    Public Property Tracks As DbSet(Of Track)

End Class

This is my Method.
        Using db = New MediaRepo
            Dim t1 = New Track
            t1.title = "Kutchie"
            Dim t2 = New Track
            t2.title = "Drug Trade"

            Dim a = New Media.Vinyl7
            a.side = "A"
            a.parentMediaId = t1.mediaId
            a.track = t1
            Dim b = New Media.Vinyl7
            b.side = "B"
            b.parentMediaId = t1.mediaId
            b.track = t2
            t1.Vinyl7T.Add(a)
            t1.Vinyl7T.Add(b)
            db.Tracks.Add(t1)

            SaveChanges(db)

        End Using

A: I think your annotation is wrong.  You're referencing mediaId as the foreign key to Track, but that's the primary key of your Vinyl7 entity. You probably mean parentMediaId right?
Update your Vinyl7 entity with this, and it will work:
   <Key>
    Public Overridable Property mediaId As Long
    Public Overridable Property side As String

    <ForeignKey("mediaId"), Required>
    Public Overridable Property track As Track

EDIT
Per your comment, I've updated to a 1..0 to 1 relationship.
Made a quick test app that's working, can you compare it to what you have?  Maybe you have something extra thats confusing EF?
 Public Class Vinyl7

    <Key>
    Public Overridable Property mediaId As Long
    Public Overridable Property side As String

    <ForeignKey("mediaId"), Required>
    Public Overridable Property track As Track

End Class

Public Class Track
    <Key>
    Public Property trackid As Long
    Public Property title As String

    Public Overridable Property Vinyl7T As Vinyl7

End Class

Module Module1

    Public Class MediaRepo : Inherits DbContext

        Public Sub New()
        End Sub

        Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
        End Sub

        Public Property Vinyl7s As DbSet(Of Vinyl7)
        Public Property Tracks As DbSet(Of Track)

    End Class

    Sub Main()
        Dim db As New MediaRepo

        Dim vin = New Vinyl7
        Dim track As New Track

        track.Vinyl7T = vin

        db.Tracks.Add(track)
        db.SaveChanges()

    End Sub

End Module


text:
Q: Component building before async function in Flutter I want to check if the client contains an id, and find out if it is logged in or not, to modify it when the widget returns, but it always stops at SharedPrefences and executes the Build, returning the address as false, even though it is logged.
class _ScheduleStateService extends State<ScheduleService> {

int clientId = 0;

//constructor

_ScheduleStateService(this.roboSelecionado) {
    _userAuthenticated();
  }

Future _userAuthenticated() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
      clientId = pref.getInt("cliente_id") ?? 0;
  }

}

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: const Text('Agendamento'),
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          children:
            (clientId != 0)
                ? Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8),
                        child: Card(
                          elevation: 4,
                          child: SizedBox(
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: TextFormField(
                                keyboardType: TextInputType.text,
                                controller: enderecoController,
                                decoration: const InputDecoration(
                                    labelText: 'Endereço',
                                    enabled: false,
                                    border: InputBorder.none,
                                    labelStyle: TextStyle(
                                        color: Color(0xFFE84505),
                                        fontSize: 18,
                                        fontWeight: FontWeight.w600)),
                              ),
                            ),
                          ),
                        ),
                      )
                    ],
                  )
                : Column(),

I know it's something related to Fure, Async and Await, but so far I couldn't find the solution!

A: You need to call setState when you want the widget to be rebuilt in response to a change in state:
Future<void> _userAuthenticated() async {
    SharedPreferences pref = await SharedPreferences.getInstance();

    // Never call setState after an asynchronous gap without
    // ensuring that the widget is still mounted. Calling setState
    // on an unmounted widget will cause an exception to be thrown!
    if (!mounted) {
        return;
    }

    setState(() {
        clientId = pref.getInt("cliente_id") ?? 0;
    });
  }
}

You should also execute this type of action from initState, rather than from the constructor:
_ScheduleStateService(this.roboSelecionado);

@override
void initState() {
  super.initState();

  _userAuthenticated();
}


text:
Q: Heroku Free Service So I am currently using Heroku's free service to run my Discord Bot.
I saw that it will sleep every 30 minutes if it isn't used. If the bot is used after 30 minutes, will the app wake up by itself or will I need to consistently wake it up.
Also, when the plan says I can verify with a credit card to get a total of 1000 free dyno hours, does that mean that I won't have to pay anything but only verify?
Thanks for all your help,
Traid

A: You will need to wake up the bot after every 30 minutes, however there are many ways that you can around this. You can create a program that will "ping" the bot every 29 minutes so it never goes to sleep.
If your Heroku is verified, you will not be charged.


text:
Q: javascript function vs jquery namespace function, the difference? How come a javascript function like this below...
function stars() {
var mOpacity = $('#area').css('opacity');
if (mOpacity = 1) {

$('#title').find('.stars').animate({"marginTop":"-170px",opacity:1}, 3000)
.animate({opacity: 0}, 400)
.animate({"marginTop":"60px",opacity:0},0, stars);
  }
}
stars();

...breaks my browser when I try to do something like this....
$.stars = function() {
var mOpacity = $('#area').css('opacity');
if (mOpacity = 1) {

$('#title').find('.stars').animate({"marginTop":"-170px",opacity:1}, 3000)
.animate({opacity: 0}, 400)
.animate({"marginTop":"60px",opacity:0},0, $.stars());
  }
}
$.stars();

What is the lesson here between the 2 styles of functions?
Thanks
Ok based on everyones feedback to see more code, here is a full gimplse of the code on my .js file...
function mIntro() {

/********PRE-GAME ANIMATION*********/
$('#area').css({'opacity':0}).delay(1000).animate({opacity:1},300);
$('#title').find('.age').css({'opacity':0}).delay(2000).animate({opacity:1}, 3000);

function stars() {
var mOpacity = $('#area').css('opacity');
if (mOpacity = 1) {

$('#title').find('.stars').animate({"marginTop":"-170px",opacity:1}, 3000)
.animate({opacity: 0}, 400)
.animate({"marginTop":"60px",opacity:0},0, stars);
  }
}
stars();
}

$(function() {
  mIntro();
});

I have jquery connected to this .js page and I just can't understand why stars has to be in-cased in a traditional javascript function and not flexibile for a jquery namespace function.  I bet it has something to do with the animate tag that re-calls stars, but I am not sure...
Thanks or any advice!!!

A: You're inadvertently calling it in the second snippet:
.animate(..., $.stars());

You should code it the same way: pass the function, not the result of calling it:
Function:             stars      $.stars
Result of calling:    stars()    $.stars()

A: The difference is that your first example is contained directly within the window object whereas the second example is contained in the jQuery ($) object (note that the $ object is then contained within the window object). As far as why it breaks when you attempt to use the jQuery namespace, I cant say without seeing all of your code, however $ is probably not defined.


text:
Q: .is(":hover") is broken as of jQuery 1.9 How to fix When doing $(...your selector here...).is(":hover"), jQuery prior to 1.9.1 gave correct answer, while jQuery 1.9.1 tells you this:

Error: Syntax error, unrecognized expression: unsupported pseudo: hover

This is not about performing an action on hover - for that, just use .hover()
This is about, at an arbitrary point in time, finding out whether or not some element is being hovered
Thank you Mooseman for the answer, which I shall demonstrate with a fiddle

A: Assuming your selector is #myid, use $('#myid:hover') instead of using .is().
If you are using $(this) or a variable, use myVar.filter(':hover').

A: However the workaround above is unsuitable when you are comparing elements using jQuery.fn.is() with a composed selector which is not known beforehand, and that could match several elements in the parent container.
eg, the same exception is thrown when selectorText in style_get() below is equal to: ".mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded .mCSB_dragger_bar, .mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_dragger .mCSB_dragger_bar"
..because hover is not defined in Sizzle.selectors.pseudos or Sizzle.selectors.setFilters (jquery-2.1.4, line 1764)..
function style_get(elem) {

  var sheets=document.styleSheets;
  var css_properties={};
  elem=$(elem);

  for (var s in sheets) {
    var rules=sheets[s].rules || sheets[s].cssRules;

    for (var r in rules) {
      if (elem.is(rules[r].selectorText)) {

        css_properties=$.extend(
          css_properties,
          css.parse(rules[r].style),
          css.parse(elem.attr('style'))
        );

      }
    }

  }

  return css_properties;

}

A: You could try to use .filter()
I think, my solution will help you:
//
// jQuery 3 pseudo ':hover' doesn't support
//

// Working on jQuery 1.7.1
$("*").on('click', $.proxy(function() {
    if ( this.$('.tooltip:hover').length > 0 ) { // jQuery 3.2.1 -> Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: hover
      console.log('Hovered!');
    } else {
      console.log('Where is my element!?');
    }
}, this));

// Updated solution for jQuery 1.7.1 - 3.2.1
$("*").on('click', $.proxy(function() {
    var isHovered = $('.tooltip').filter(function() {
        return $(this).is(":hover");
    });

    if ( isHovered.length > 0 ) {
      console.log('Hovered!');
    } else {
      console.log('Where is my element!?');
    }
}, this));

also, you can see my GitHub gist:https://gist.github.com/antydemant/74b00e27790e65f4555a29b73eea7bb2


text:
Q: Remove string literals from elements inside an array Please guys i need to parse a string to look like these in swift
"[{"question":9, "answer":25}", "question\":10, "answer":27}]"
where the index and value are dynamically gotten from a loop. I was able to get to these
["{\"question\":9, \"answer\":25}", "{\"question\":10, \"answer\":27}", "{\"question\":11, \"answer\":29}", "{\"question\":12, \"answer\":33}", "{\"question\":13, \"answer\":37}"]
so i have tried this

  for i in 0..<answersForQuestionInPage.count{

    let questions = answersForQuestionInPage[i] as Answer

    do {
    let data = try JSONEncoder().encode(questions)
    // 2
    let string = String(data: data, encoding: .utf8)!
    answers.append(string)
     print("This is the main value \(string)")

    } catch{

    }
}

this still gives me an array with this format

["{\"question\":9, \"answer\":25}", "{\"question\":10,
  \"answer\":27}", "{\"question\":11, \"answer\":29}",
  "{\"question\":12, \"answer\":33}", "{\"question\":13,
  \"answer\":37}"]

with the object

"{\"question\":9, \"answer\":25}"
  still wrapped in a string liteal " " what i want is for this return array to be in this format
[{"question":9, "answer":25}, {"question":10,
  "answer":27}, {"question":11, "answer":29},
  "{"question":12, "answer":33}, {"question":13,
  "answer":37}]

A: I didn't understand the whole thing, but you said you need to parse the String, but I think you meant JSON. So, you can do it like this and get the values. Do let me know if it is what you needed, otherwise please add clarity in your question and I will edit and update my answer accordingly.
struct Quiz: Decodable {
 let question, answer: Int
}

private func fetchQuizzes() {

  //After getting the data from API, you can do this

  guard let quiz = try? JSONDecoder().decode([Quiz].self,from: data) else { print("Unable to parse"); return }

  print(quiz)
  print(quiz.first?.answer) //First Answer

}

A: Just like Rob said before, you have a JSON here.
Using Robs code you decode the given JSON and create an array of Quiz objects (Robs struct).
You can now work with that array and transform it to your needs.


text:
Q: im getting select options from API in that one option should be selected im getting select options from API in that one option should be selected
<select>
<option value= "<?php  echo $value['brand_id'] ;?>" > <?php  echo $value['brand_name'] ;?> </option>

<?php } ?>
</select>

one option has value 5 should be selected when we load page

A: try this code:-
<option <?php echo ($value['brand_id']==5)?' selected ':''; ?> value= "<?php  echo $value['brand_id'] ;?>" > <?php  echo $value['brand_name'] ;?> </option>


text:
Q: I just posted on a closed question on the iOS app I just posted on a closed question
Is it OK to copy answers to the same question?
How?
Side point:
I do not see any indication that the post is closed on the app


text:
Q: react useCallback not updating function Isn't the hook useCallback supposed to return an updated function every time a dependency change?
I wrote this code sandbox trying to reduce the problem I'm facing in my real app to the minimum reproducible example.
import { useCallback, useState } from "react";

const fields = [
  {
    name: "first_name",
    onSubmitTransformer: (x) => "",
    defaultValue: ""
  },
  {
    name: "last_name",
    onSubmitTransformer: (x) => x.replace("0", ""),
    defaultValue: ""
  }
];

export default function App() {
  const [instance, setInstance] = useState(
    fields.reduce(
      (acc, { name, defaultValue }) => ({ ...acc, [name]: defaultValue }),
      {}
    )
  );

  const onChange = (name, e) =>
    setInstance((instance) => ({ ...instance, [name]: e.target.value }));

  const validate = useCallback(() => {
    Object.entries(instance).forEach(([k, v]) => {
      if (v === "") {
        console.log("error while validating", k, "value cannot be empty");
      }
    });
  }, [instance]);

  const onSubmit = useCallback(
    (e) => {
      e.preventDefault();
      e.stopPropagation();
      setInstance((instance) =>
        fields.reduce(
          (acc, { name, onSubmitTransformer }) => ({
            ...acc,
            [name]: onSubmitTransformer(acc[name])
          }),
          instance
        )
      );
      validate();
    },
    [validate]
  );

  return (
    <div className="App">
      <form onSubmit={onSubmit}>
        {fields.map(({ name }) => (
          <input
            key={`field_${name}`}
            placeholder={name}
            value={instance[name]}
            onChange={(e) => onChange(name, e)}
          />
        ))}

        <button type="submit">Create object</button>
      </form>
    </div>
  );
}

This is my code. Basically it renders a form based on fields. Fields is a list of objects containing characteristics of the field. Among characteristic there one called onSubmitTransformer that is applied when user submit the form. When user submit the form after tranforming values, a validation is performed. I wrapped validate inside a useCallback hook because it uses instance value that is changed right before by transform function.
To test the code sandbox example please type something is first_name input field and submit.
Expected behaviour would be to see in the console the error log statement for first_name as transformer is going to change it to ''.
Problem is validate seems to not update properly.

A: This seems like an issue with understanding how React lifecycle works. Calling setInstance will not update instance immediately, instead instance will be updated on the next render. Similarly, validate will not update until the next render. So within your onSubmit function, you trigger a rerender by calling setInstance, but then run validate using the value of instance at the beginning of this render (before the onSubmitTransformer functions have run).
A simple way to fix this is to refactor validate so that it accepts a value for instance instead of using the one from state directly. Then transform the values on instance outside of setInstance.
Here's an example:
function App() {
    // setup

    const validate = useCallback((instance) => {
        // validate as usual
    }, []);

    const onSubmit = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        const transformedInstance = fields.reduce((acc, {name, onSubmitTransformer}) => ({
            ...acc,
            [name]: onSubmitTransformer(acc[name]),
        }), instance);
        setInstance(transformedInstance);
        validate(transformedInstance);
    }, [instance, validate]);

    // rest of component
}

Now the only worry might be using a stale version of instance (which could happen if instance is updated and onSubmit is called in the same render). If you're concerned about this, you could add a ref value for instance and use that for submission and validation. This way would be a bit closer to your current code.
Here's an alternate example using that approach:
function App() {
    const [instance, setInstance] = useState(/* ... */);

    const instanceRef = useRef(instance);
    useEffect(() => {
        instanceRef.current = instance;
    }, [instance]);

    const validate = useCallback(() => {
        Object.entries(instanceRef.current).forEach(([k, v]) => {
            if (v === "") {
              console.log("error while validating", k, "value cannot be empty");
            }
          });
    }, []);

    const onSubmit = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        const transformedInstance = fields.reduce((acc, {name, onSubmitTransformer}) => ({
            ...acc,
            [name]: onSubmitTransformer(acc[name]),
        }), instanceRef.current);
        setInstance(transformedInstance);
        validate(transformedInstance);
    }, [validate]);

    // rest of component
}


text:
Q: Magento Marketplace Extensions VS Other Extensions A member of the Magento Team told me to prefer to use the Marketplace Extensions (I know about the audit process) than the other third-party extensions (e.g. from Github or aleatory module store).
Can you explain me listing the pros vs cons of each one using a technical overview?
Magento Marketplace Extensions X Other Extensions
Thanks

A: If normal extension uploading on Marketplace there are many septs which is marked Magento 2 extension better then another extension.

*

*Business Review

*Technical Review

*Marketing Review

*QA Review

Magento Marketplace Extensions

*

*Dependency Check
a) Global ($_GET, $_FILE) variable do not use.
b) Do not use Core extension code.
c) Do not use redeclaration of code (class use)

*composer.json file is proper because
it is checked by Marketplace Team.

*If use Magento market place extension Then no issue with extension because it is Check with the Magento marketplace team.

*From Magento 2 admin panel, we are directly installing or upgrade Magento marketplace extension.

Other Extensions

*

*Not check any Dependency.

*May be issue in composer.json , No one check.

*Normal developer not check dependency, If extension working in 2.0.x, It may be possible which is not working in Magento version 2.1.x.

*Which is not possible if we are use other extension.

A: Usually the extensions in the marketplace are verified by code sniffer tool and compiled by the vendor before they are released to market place, where as in other sources we don't exactly know whether the code is verified or not which might cause problems the entire project.


text:
Q: What are the performance difference between browsing in Chrome's Regular Window vs Incognito Window? Aside from not storing your web browsing history, what are the performance differences between browsing a website in Chrome's Regular Window vs Incognito Window?
Are there any power or performance differences?
Is Regular Chrome browsing better in speed and power compared to Incognito browsing?

A: Incognito will always be slower than regular chrome.  The main reason for this is that when in icognito mode, the browser doesn't store cache.
This means that each time you visit a page, the css files, javascript, images etc all have to be re-downloaded from the web server, which makes sites generally load a little slower - but is brilliant for web developers like myself who hate chasing an issue for an hour only to realise the browser is using a cached file.

A: Whilst I completely agree with Fazer I will also point out that by default all plugins/Chrome apps are disabled in incognito mode, depending on the number and type of plugins you have installed this will reduce the memory usage of the browser and reduce parsing of the webpage before rendering (e.g. AdBlock), providing a speed boost in the browser it's self.


text:
Q: Send an UDP packet through SOCKS5 proxy in windows with specified local port As we know SOCKS5 support UDP.
So, how do I send an UDP packet to the UDP Server through SOCKS5 proxy with specified local port. Therefore, server will read source port of packet is same like local port that has been specified in windows operating system.
In CLI mainly with powershell or CMD, is there commmand built-in available to do that?
Note: I have control of SOCKS5 Proxy Server and UDP Server and they are currently listening, both of them are GNU/Linux operating system. Maybe I need to setup SOCKS5 proxy server side.


text:
Q: Why do the tests of the ATestClass of Spring's TestExecutionExceptionHandlerTests not fail? Several tests in the test class of TestExecutionExceptionHandlerTest#ATestClass throw exceptions yet I assume the unit tests of Junit pass just fine. Can someone explain what is going on?

A: This answer explains it. More specifically the last comment by Sam Brannen:

Maven Surefire [...] is not executing your static nested test class because of its default exclude rule.


text:
Q: How do I capture the properties I want from a string? I hope you are well I have the following string:
"{\"code\":0,\"description\":\"Done\",\"response\":{\"id\":\"8-717-2346\",\"idType\":\"CIP\",\"suscriptionId\":\"92118213\"},....\"childProducts\":[]}}"...

To which I'm trying to capture the attributes: id, idType and subscriptionId and map them as a dataframe, but the entire body of the .cvs puts it in a single row so it is almost impossible for me to work without index
desired output:
id,  idType, suscriptionID
0.   '7-84-1811', 'CIP', 21312421412
1.   '1-232-42',  'IO' , 21421e324

My code:
import pandas as pd
import json

path = '/example.csv'
df = pd.read_csv(path)
normalize_df = json.load(df)
print(df)

A: Considering your string is in JSON format, you can do this.
drop columns, transpose, and get headers right.
toEscape = "{\"code\":0,\"description\":\"Done\",\"response\":{\"id\":\"8-717-2346\",\"idType\":\"CIP\",\"suscriptionId\":\"92118213\"}}"

json_string = toEscape.encode('utf-8').decode('unicode_escape')

df = pd.read_json(json_string)

df = df.drop(["code","description"], axis=1)

df  = df.transpose().reset_index().drop("index", axis=1)

df.to_csv("user_details.csv")

the output looks like this:
id  idType  suscriptionId
0   8-717-2346  CIP 92118213

Thank you for the question.


text:
Q: Does Windows Server Backup copy user documents too? I have a AD domain and have redirected the Documents folder for each of my users.  I have the "Grant the user exclusive rights to the Documents" checkbox ticked so I can't get in to see their documents.
I also have Windows Server Backup running a complete backup to a network share every night. I run the backup as a user that's part of the Backup Operators security group. I tried doing a Files and Folders Recovery and went in to look for a single file in one of my user's Documents folders and nothing showed up.
What I'm wondering: does Windows Server Backup backup the files that are in the Documents folders that users have exclusive rights to?  If my DC dies, and I do a full recovery, will all of their files still be there?

A: It works!
When I was looking in the restore section of Windows Server Backup, it didn't show the documents.  But, I did a little test-recovery of my own files and the folder with my documents showed up with all of the documents inside.
The user that is doing the backups has to be a part of the backup operators group.  That group can evidently backup documents that it doesn't have access too.
Hope this helps someone in the future :)

A: My guess would be No and No for both of your questions. With the option you've set on the redirected folders, only the user and local system have access to the folders.


text:
Q: How can I convert these coordinates to decimal degrees We have extracted the following coordinate set from a Microsoft SQL database, but are unable to convert it to a coordinate system that makes sense. We know that the coordinates should be in Cape Town, South Africa.
Actual_GPS_Latitude: -122146844
Actual_GPS_Longitude: 66350481

A: These latitude/longitude coordinates are expressed in milliarcseconds. Dividing them by 3,600,000 will convert them to the more standard form in degrees.
In this specific case, we obtain -33.929679°, 18.430689°, or 33° 55' 46.844" S, 18° 25' 50.481" E, near the University of Technology in Cape Town.


text:
Q: Huge amount of RU to write document of 400kb - 600kb on Azure cosmos db This is the log of my azure cosmos db for last write operations:

Is it possible that write operations of documents with size between 400kb to 600kb have this costs?
Here my document (a list of coordinate):

Basically I thought at the beginning it was a hotPartition problem, but afterwards I understood (I hope) that it is a problem in the loading of documents ranging in size from 400kb to 600kb. I wanted to understand if there was something wrong in the database setting, in the indexing policy or other as it seems to me anomalous that about 3000 ru are used to load a json of 400kb, when in the documentation it is indicated that to load a file of equal size at 100kb it takes about 50ru. Basically the document to be loaded is a road route and therefore I would not know in what other way to model it.
This is my indexing policy:

Thanks to everybody. I spent months behind this problem without having solutions...

A: It's hard to know for sure what the expected RU/s cost should be to ingest a 400KB-600KB item. The cost of this operation will depend on the size of the item, your indexing policy and the structure of the item itself. Greater hierarchy depth is more expensive to index.
You can get a good estimate for what the cost for a single write for an item will be using the Cosmos Capacity Calculator. In the calculator, click Sign-In, cut/paste your index policy, upload a sample document, reduce the writes per second to 1, then click calculate. This should give you the cost to insert a single item.
One thing to note here, is if you have frequent updates to a small number of properties I would recommend you split the documents into two. One with static properties, and another that is frequently updated. This can drastically reduce the cost for updates on large documents.
Hope this is helpful.

A: You can also pull the RU cost for a write using the SDK.

Check storage consumed
To check the storage consumption of an Azure Cosmos container, you can run a HEAD or GET request on the container, and inspect the x-ms-request-quota and the x-ms-request-usage headers. Alternatively, when working with the .NET SDK, you can use the DocumentSizeQuota, and DocumentSizeUsage properties to get the storage consumed.

Link.


text:
Q: Android - SharedPreferences not working? Here's the code where I get to have the SharedPreferences:
public class MainActivity2 extends Activity {
Button b;
EditText et;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
String rfid, getPref;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity2);

    b = (Button)findViewById(R.id.loginnext);
    et = (EditText)findViewById(R.id.rfid);
    tv = (TextView)findViewById(R.id.tv);

    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog = ProgressDialog.show(MainActivity2.this, "",
                    "Validating user...", true);
            new Thread(new Runnable() {
                public void run() {
                    login();
                }
            }).start();
        }
    });
}

void login(){
    try{

        SharedPreferences preferences = getSharedPreferences(getPref, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = preferences.edit();

        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://usamobileapp.pe.hu/webservice/check.php");

        nameValuePairs = new ArrayList<NameValuePair>(2);

        nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        response=httpclient.execute(httppost);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response = httpclient.execute(httppost, responseHandler);
        System.out.println("Response : " + response);
        runOnUiThread(new Runnable() {
            public void run() {
                tv.setText("Response from PHP : " + response);
                dialog.dismiss();
            }
        });

        if(response.equalsIgnoreCase("User Found")){
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity2.this,"Login Success", Toast.LENGTH_SHORT).show();

                    editor.putString("rfid" ,rfid);
                    editor.commit();

                }
            });

            startActivity(new Intent(MainActivity2.this, MainActivity3Activity.class));
        }else{
            showAlert();
        }

    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
}

This is where I'd like the get the Registration ID entered by the user and use it in all activities of the app.
Here is the code to check whether I get to have the SharedPreferences correctly. It displays it through I text view. I wonder why it would not show up. Did I do the SharePreferences correctly?
public class ViewGradesActivity extends ActionBarActivity {

TextView viewPref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_grades);

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    String get = settings.getString("rfid", "");

    viewPref = (TextView) findViewById(R.id.tv);
    viewPref.setText(get);

}

}
By the way, the code above is from another class.
Thanks for the help in advance.

A: You are receiving this error because you are writing to a different SharedPreferences than you are reading from. If you are using default SharedPreferences, make sure you read and write to the default preferences.
// Read the String from SharedPreferences
String awesomeString = PreferenceManager.getDefaultSharedPreferences(context).getString("key", "");

// Write the String to SharedPreferences
PreferenceManager.getDefaultSharedPreferences(context)
        .edit().putString("key", awesomeString).commit();

A: Are you sure that you put any value in rfid? Here
                public void run() {
                    Toast.makeText(MainActivity2.this,"Login Success", Toast.LENGTH_SHORT).show();

                    editor.putString("rfid" ,rfid);
                    editor.commit();

                }

I think rfid is null. I did not find any place where you are initializing it.
Put rfid in toast or log it and you will see.
And as everybody else say you have to use default shared preferences in both classes. Here you can find why Difference between getDefaultSharedPreferences and getSharedPreferences

A: That's because you don't read and write the preferences in the same preference file.
To write you use:
SharedPreferences preferences = getSharedPreferences(getPref, Context.MODE_PRIVATE);

To read you use:
PreferenceManager.getDefaultSharedPreferences(this);

So you write you preferences in a file getPref (which is null according to your code, don't you get any error?) but you read your preferences in the default file provided by the Android API.


text:
Q: In how many ways can the elements be divided into 2 groups given A set "a" having 6 elements? A set "a" has 6 elements.In how many ways can the elements be divided into 2 groups?
Options given: 1) $62$  2) $31$  3) $52$  4) $32$
My Approach:
I divided the items into 2 unequal groups of 4 and 2,5 and 1,6 and 0,3 and 3.
I get
$6!$/$2!$ . $4$!=$15$
$6!$/$3!$ . $3$!=$20$
$6!$/$1!$ . $5$!=$6$
$6!$/$0!$ . $6$!=$1$
total=$42$

Can anyone can give me hint how to solve this problem?

A: Unless there are further restrictions, you have 6 slots. Each slot takes either the value 1 or 2. Therefore, the total number of partitions is 32.


text:
Q: What is the analogue of C#/.NET InternalVisibleTo attribute in Swift? In .NET I can do internal members of the assembly visible (accessible) for another concrete assembly by adding of the attribute [InternalVisibleTo("AnotherConcreteAssembly")].
Has Swift any analog for this encapsulation ability?
If yes, How can I open access to internal members of one module for another?


text:
Q: How to handle File Associations from Application? I know Installers can setup File Associations for your Application during the installation process, so if you have your own File types that open with your Application, it will be setup to do that, and also the associated File will have its own icon in Windows what you define.
Anyway, I would like to be able to Set/Remove the File types my Application will use, directly from the preferences form in my Application.
What methods are needed to do this, I am thinking along the lines of the Registry, but then what Keys/Values etc are we to work with, if Registry is the way to go?
Appreciate some advice and tips, It is also important that it works on XP/Vista/7.
Thanks in Advance.

A: try this unit to associate a certain extension to an exe remove the entries made in registry to unregister.
unit utils;

interface
uses Registry, ShlObj, SysUtils, Windows;

procedure RegisterFileType(cMyExt, cMyFileType, cMyDescription, ExeName: string; IcoIndex: integer; DoUpdate: boolean = false);

implementation

procedure RegisterFileType(cMyExt, cMyFileType, cMyDescription, ExeName: string; IcoIndex: integer; DoUpdate: boolean = false);
var
   Reg: TRegistry;
begin
  Reg := TRegistry.Create;
  try
    Reg.RootKey := HKEY_CLASSES_ROOT;
    Reg.OpenKey(cMyExt, True);
    // Write my file type to it.
    // This adds HKEY_CLASSES_ROOT\.abc\(Default) = 'Project1.FileType'
    Reg.WriteString('', cMyFileType);
    Reg.CloseKey;
    // Now create an association for that file type
    Reg.OpenKey(cMyFileType, True);
    // This adds HKEY_CLASSES_ROOT\Project1.FileType\(Default)
    //   = 'Project1 File'
    // This is what you see in the file type description for
    // the a file's properties.
    Reg.WriteString('', cMyDescription);
    Reg.CloseKey;    // Now write the default icon for my file type
    // This adds HKEY_CLASSES_ROOT\Project1.FileType\DefaultIcon
    //  \(Default) = 'Application Dir\Project1.exe,0'
    Reg.OpenKey(cMyFileType + '\DefaultIcon', True);
    Reg.WriteString('', ExeName + ',' + IntToStr(IcoIndex));
    Reg.CloseKey;
    // Now write the open action in explorer
    Reg.OpenKey(cMyFileType + '\Shell\Open', True);
    Reg.WriteString('', '&Open');
    Reg.CloseKey;
    // Write what application to open it with
    // This adds HKEY_CLASSES_ROOT\Project1.FileType\Shell\Open\Command
    //  (Default) = '"Application Dir\Project1.exe" "%1"'
    // Your application must scan the command line parameters
    // to see what file was passed to it.
    Reg.OpenKey(cMyFileType + '\Shell\Open\Command', True);
    Reg.WriteString('', '"' + ExeName + '" "%1"');
    Reg.CloseKey;
    // Finally, we want the Windows Explorer to realize we added
    // our file type by using the SHChangeNotify API.
    if DoUpdate then SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nil, nil);
  finally
    Reg.Free;
  end;
end;

end.

Registry is defenetly the way to go with things...

A: From your app you'd be better to use the per-user store for file associations. If you use the system wide registry location then you'd need to elevate in order to apply changes.  That's not something you should do in a standard user app.
Store the registry settings under:
HKEY_CURRENT_USER\SOFTWARE\Classes

The format of entries under there is exactly the same as under
HKEY_LOCAL_MACHINE\SOFTWARE\Classes

A: You can run the following command from your shell
http://support.microsoft.com/kb/184082
or
you can make the entry in registry as shown in the following link
http://www.daycounter.com/LabBook/Changing-File-Associations-With-Registry-Editor.phtml


text:
Q: moment.js date validation from array of formats I need to test an input for proper date format. I want to accept several date formats so I created a validating function that test if at least one of the formats is OK and in that case return true.
I use moment.js to test the date.
When I simply type the condition with hard-coded string date formats, the function works properly:
var multiDateValidator = function (value)
{
    if ((moment(value, 'DD/MM/YYYY', true).isValid()) ||
        (moment(value, 'D/M/YYYY', true).isValid()) ||
        (moment(value, 'DD.MM.YYYY', true).isValid()) ||
        (moment(value, 'D.M.YYYY', true).isValid()) ||
        (moment(value, 'DD. MM. YYYY', true).isValid()) ||
        (moment(value, 'D. M. YYYY', true).isValid())) {
        return true;
    }

    return false;
};

But if I want to use the list of allowed date formats, it doesn't work, it never returns true.
var allowedDateFormats = ['DD/MM/YYYY', 'D/M/YYYY', 'DD.MM.YYYY', 'D.M.YYYY', 'DD. MM. YYYY', 'D. M. YYYY'];

var multiDateValidator = function (value)
{
    allowedDateFormats.forEach(function(dateFormat)
    {
        if (moment(value, dateFormat, true).isValid()) {
            return true;
        }
    });

    return false;
};

What's wrong with the second function? I know I'm not too good at JavaScript, but it should work, shouldn't it?

A: The is no need to use for or forEach loop. Moment provides moment(String, String[], String, Boolean); method for parsing string using multiple formats.
As the docs says:

If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.
Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:

*

*Prefer formats resulting in valid dates over invalid ones.

*Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.

*Prefer formats earlier in the array than later.

Here a working live sample:

var allowedDateFormats = ['DD/MM/YYYY', 'D/M/YYYY', 'DD.MM.YYYY', 'D.M.YYYY', 'DD. MM. YYYY', 'D. M. YYYY'];

var multiDateValidator = function (value){
  return moment(value, allowedDateFormats, true).isValid();
};

var test = ['01/01/2017', '01.01.2017', '2017-Jan-01'];
for(var i=0; i<test.length; i++){
  console.log(test[i], multiDateValidator(test[i]));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

A: As i mentioned in my comment, return true returns to the inner function, but it doesnt stop the outer function from executing, so your outer function gets executed everytime (ie every time return false is executed)
my solution would be:
var allowedDateFormats = ['DD/MM/YYYY', 'D/M/YYYY', 'DD.MM.YYYY', 'D.M.YYYY', 'DD. MM. YYYY', 'D. M. YYYY'];

var multiDateValidator = function (value)
{
  for(var dateFormat of allowedDateFormats) {
    if (moment(value, dateFormat, true).isValid()) {
      return true;
    }
  }
  return false;
};


text:
Q: зачеркнутая цена по диагонали в css Поле с ценой всегда разной длинны, угол диагонали будет постоянно меняться. Сделать на чистом css

A: решение - наложить поверх ::after псевдо-элемент с фоном в виде svg. svg можно вставлять прямо в css
пример

.old-price{
  position: relative;
  display: inline-block;
}
.old-price::after{
  content: '';
        position: absolute;
        left: 0;
        top:0;
        right: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        background-image: url('data:image/svg+xml;utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22100%25%22%20height%3D%22100%25%22%3E%0A%20%20%20%20%3Cline%20x1%3D%220%22%20y1%3D%22100%25%22%20x2%3D%22100%25%22%20y2%3D%220%22%20stroke%3D%22%23F00%22%20stroke-width%3D%222%22%2F%3E%0A%3C%2Fsvg%3E');
        background-size: cover;
}

1 000 р

100 р
</div

100 000 р
</div

чтобы вставить svg  -его нужно декодировать UrlDecoder
прикладываю вам svg, если захотите менять толщину линии и её цвет
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <line x1="0" y1="100%" x2="100%" y2="0" stroke="#F00" stroke-width="2"/>
</svg>


text:
Q: Multiple Modals with React Hooks I´m building some modals for fun but I can´t make it work for multiple modals.
useModal hook
import { useState } from 'react';

const useModal = () => {

    const [isShowing, setIsShowing] = useState(false);

    const toggle = () => {
        setIsShowing(!isShowing);
    }

    return {
        isShowing,
        toggle,
    }
};

export default useModal;

Modal component
import React, { useEffect } from 'react';

const Modal = (props) => {

    const { toggle, isShowing, children } = props;

    useEffect(() => {

        const handleEsc = (event) => {
            if (event.key === 'Escape') {
                toggle()
            }
        };

        if (isShowing) {
            window.addEventListener('keydown', handleEsc);
        }

        return () => window.removeEventListener('keydown', handleEsc);

    }, [isShowing, toggle]);

    if (!isShowing) {
        return null;
    }

    return (
        <div className="modal">
            <button onClick={ toggle } >close</button>
            { children }
        </div>
    )
}

export default Modal

in my Main component
If I do this the only modal in the page works fine
const { isShowing, toggle } = useModal();
...
<Modal isShowing={ isShowing } toggle={ toggle }>first modal</Modal>

but when I try to add another one it doesn´t work. it doesn´t open any modal
const { isShowingModal1, toggleModal1 } = useModal();
const { isShowingModal2, toggleModal2 } = useModal();
...
<Modal isShowing={ isShowingModal1 } toggle={ toggleModal1 }>first modal</Modal>
<Modal isShowing={ isShowingModal2 } toggle={ toggleModal2 }>second modal</Modal>

what I´m doing wrong? thank you
if you want to check it out please go to https://codesandbox.io/s/hopeful-cannon-guptw?fontsize=14&hidenavigation=1&theme=dark

A: Try that:
const useModal = () => {
  const [isShowing, setIsShowing] = useState(false);

  const toggle = () => {
    setIsShowing(!isShowing);
  };

  return [isShowing, toggle];
};

then:
export default function App() {
  const [isShowing, toggle] = useModal();
  const [isShowingModal1, toggleModal1] = useModal();
  const [isShowingModal2, toggleModal2] = useModal();

A: if you have multiple modal then dynamically inject <div> inside the page body and map modal to it.
to create div use,
    var divTag = document.createElement("div");
    divTag.setAttribute('id', 'modal');
    document.getElementsByTagName('body')[0].appendChild(divTag);
    document.getElementById('modal').innerHTML = modalHtML;

This should work.


text:
Q: Find out who is logged in on linux using python I have 8 servers that I would like to monitor. All servers have a tornado python server installed. One of the servers is a monitor that polls other servers and alerts me by SMS if there is a problem.
One of the alerts is when a user logs into one of the servers.
How can I use Python to detect who is logged in on my Ubuntu server?
I need to return logged in users to the main monitor.
I hope this makes things clear..

A: Use the subprocess module, and run the command who.
In [5]: import subprocess

In [6]: subprocess.check_output("who")
Out[6]: 'monty    pts/0        2013-01-14 16:21 (:0.0)\n'

You can fetch the number of current logins using : who | wc -l:
In [42]: !who
monty    pts/2        2013-01-14 19:09 (:0.0)
monty    pts/0        2013-01-14 19:07 (:0.0)

In [43]: p=Popen(["who"],stdout=PIPE)

In [44]: Popen(["wc","-l"],stdin=p.stdout).communicate()[0]
2

Names of the users:
In [54]: users=check_output("who")

In [55]: set([x.split()[0] for x in users.splitlines()])
Out[55]: set(['monty'])

A: from subprocess import Popen, PIPE, STDOUT

who = Popen(['who'],stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print who.stdout.read()

# Output
>>> sudo_O  :0           2013-01-14 11:48 (:0)
>>> sudo_O  pts/0        2013-01-14 11:48 (:0)
>>> sudo_O  pts/1        2013-01-14 12:41 (:0)
>>> sudo_O  pts/2        2013-01-14 12:42 (:0)

A: The best thing I found online is psutil.
See the psutil documentation
First install psutil :
pip install psutil

After that everything is easy as an example run python console from terminal:
import psutil

psutil.users()

Output:
[user(name='root', terminal='pts/0', host='your-local-host-from-isp.net',
started=1358152704.0)]

A: And if you dont want to install 3-rd party software. You can always run unix who utility
import os
os.popen('who').read()

A: In [1]: import subprocess
In [2]: print subprocess.check_output("who").split()[0]
Out[3]: 'rikatee'


text:
Q: Как в Android проложить маршрут в MapView Яндекс карт? Возможно ли в Android проложить маршрут на Яндекс Картах без использования Intent и вызова Яндекс приложения? И если да, то каким образом?
Должно получиться что-то вроде этого:

A: Как я понимаю жесткого условия, что должны быть именно яндекс карты не стоит.
Можно воспользоваться google maps. У них отличная документация, хорошо расписанная и с примерами.
Конкретно ваш случай есть тут.

A: В мобильных приложениях можно использовать API Яндекс.Карт через webView.
Пример использования API Карт в Android приложении
Пример построения маршрута


text:
Q: Wordpress: Plain  links in single-class.php and archive-class.php not working This seems like it should be super-easy to resolve, but it has me stumped.
All the links on my page added via get_header() and get_footer() work just fine. The links added via single-class.php and archive-class.php don't work.
Looking at the source code in Google Chrome, the links appear to be perfectly formed, but when I click on them nothing happens. Here are two examples:
Class Details

Enjoy More Photos on Our Facebook Page

The first one the href attribute is populated via get_permalink(). The second is hard-coded exactly as it appears above.
The class custom post type is added via a plugin I created. The single-class and archive-class are added via a custom theme I created.
Here are the two live pages:
archive-class.php --> http://markrummel.com/dev/enzas/classes/
single-class.php --> http://markrummel.com/dev/enzas/classes/culinary-nunnsense-sunday-brunch/
There are links a part of the body of other pages added via template-[template-name] that work just fine. It seems like it is only the main content area of the pages associated with the class custom post type that have broken links.
Any help figuring out what is going on would be most appreciated!
Thanks!

A: Javascript is preventing those links from firing. It appears to be coming from this section in scripts.js starting on line 8:
$('.class').click(function(e) {
  e.preventDefault();
});

All links that are children/grandchildren of element with class 'class' will become void, which is causing all of your links to fail.


text:
Q: toLocaleString() format changed in Chrome new Date().toLocaleString() in Chrome now returns: 3/13/2013 9:25:28 AM
It used to return: Tue Oct 30 2012 23:59:59 GMT-0500 (Central Daylight Time)
Why/when did it change?  Thank you.

A: The string depends on locale, have you recenlty upgraded your browser? That could be why.
Check the (window.)navigator language parameters in debug, for example navigator.language to determine if the language of your browser has changed from what you expect it to be.
You might want to pick out parts of the Date object and construct your own string (preferably after some standard) to aviod this kind of event for users.


text:
Q: Image Processing and Effects in ActionScript-3 I want to implement various effects like Sepia, GrayScale, Posterization etc. on BitmapData in ActionScript-3.
How to do this and What is most efficient way to do this ?
Thanks in advance!!

A: The most efficient way to do image processing would be to use Adobe Pixel Bender. This is basically a pixel shader like language that can be used to create filters for Photoshop, After Effects and Flash. There is also an exchange where developers share filters.
Here is a tutorial on how to load pixel bender filter into flash.
There is more information available if you search Google for "pixel bender flash".

A: This post explains how to do the GrayScale:
AS3:How to change a colored Bitmap's BitmapData to black and white?
Sepia is a combination of grayscale and tinting.  Tinting is typically accomplished by multiplying one of the colour channels by a certain amount to boost that colour.
The techniques illustrated in that post are the way you should proceed.  You'll have to look up the per-pixel filtering algorithms, but many of them exist on wikipedia or math sites.


text:
Q: Issues with sending Mass sms with API call using CURL and Laravel Job I am calling an API to send SMS using CURL and Laravel. I am facing the issues below:

*

*php artisan queue:work stops abruptly after sending some of the SMSs

*For some SMS, I get the status "sms sent successfully" and for others I get no status

Below is the code which I am using to send:
class ProcessSMS implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $recipient_phone_number;
    private $message;

    /**
     * Create a new job instance.
     *
     * @param  $recipient_phone_number
     * @param  $message
     * @return void
     */
    public function __construct($recipient_phone_number, $message)
    {
        $this->recipient_phone_number = $recipient_phone_number;
        $this->message = $message;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Send sms to customer...

        $recipient_phone_no = trim(str_replace('+', '', $this->recipient_phone_number)); // Remove '+' from the number

        $recipient_phone_no = preg_replace('/^(?:\+?237|0)?/','237', $this->recipient_phone_number); // Add 237 in front of the number if it is not already there

        $message = urlencode($this->message);

        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, "https://prod-57.wxxxx.logic.azure.com/workflows/9b733blaxxxx/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=xrESGAXXYGslL__KmBMP1Oau-by6DxPG8PUU&to=$recipient_phone_no&from=Eneo&content=$message&username=blah&password=blah");

        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // Maximum amount of time in seconds that is allowed to make the connection to the server
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        // $output contains the output string
        $output = curl_exec($ch);

        echo $output ."\n";
        echo $ch ."\n";

        // close curl resource to free up system resources
        curl_close($ch);
    }
}

What is causing queue:work to stop execution and also why is some of the SMS not returning a status?
I even commented the line CONNECTTIMEOUT but nothing has changed.


text:
Q: Struggling to bind and match DOM elements with vanilla JS I prefer to bind all my DOM elements at the top of my code so that the ID or class reference is only hard coded once, even though the element is used multiple times within the code. Something like this:
var startButton = "#startButton";
var closeButtons = ".button.close";

That works well with selectors, such as document.querySelector. The challenge occurs when I'm about to compare an element ID to one of the static variables above, like for instance during a click event:
e.target.id == startButton

Since the variable startButton contains a sharp, I would have to do something like this:
e.target.id == startButton.replace('#', '')

This is obviously not the ideal way of handling things, so I'm wondering if there's a better way to bind DOM elements for later use?
Please note that I did consider retrieving the elements using a selector right away, like document.querySelector, but that prevents me from manipulating the elements later on.
EDIT: My note above turns out to be wrong. It's totally possible to manipulate the elements later on. So the question is whether it's better to store selectors in variables, or to store nodes in variables. As pointed out below, the DOM element might not exist while it's being declared, so it might be better to store the selector in a variable, like I'm doing above.

A: For the specific example in your question, you can use .matches():
if (e.target.matches(startButton))

The .matches() DOM API takes a selector as its argument.


text:
Q: Iframe vs Ajax into div - problems and considerations I have a requirement that i seek advice for.
I need to load a page B as part of page A. Page A could be any random customers website basically.
I need the background of Page B to be transparent, or to somehow inherit the background of page A.
I tried iframes, but i not sure how to get Page B to inherit Page A's background.
I considered using Ajax (jquery) in Page A to load Page B into a div within Page A, like so:

    ....
    $("#remotepage").load("PageB.php");
But in doing so I'm worried that if Page A has included a jquery library, that it might conflict with Page Bs included jquery library, which may not even be of the same version.
I'm basically trying to develop a page that is plug and play with several customer websites, to make it seem as part of my customer website.
Please advice me the best way to go about this?


text:
Q: Solving a Complicated Trig Problem I am preparing for AIME and I came across this problem which I need help solving:
$$\begin{eqnarray} 10^{10^{10}} \sin\left( \frac{109}{10^{10^{10}}} \right) - 9^{9^{9}} \sin\left( \frac{101}{9^{9^{9}}} \right) - 8^{8^{8}} \sin\left( \frac{17}{8^{8^{8}}} \right) + 7^{7^{7}} \sin\left( \frac{76}{7^{7^{7}}} \right) + 6^{6^{6}} \sin\left( \frac{113}{6^{6^{6}}} \right) \end{eqnarray} $$
There must be some simple way to do this for sure, but I don't know how to.

A: Since $\sin x\approx x$ for small $x$, this should be pretty darn close to $$109−101−17+76+113=180.$$
How close? By far the largest error comes from the $6^{6^6}\sin\frac{113}{6^{6^6}}$ term, because that argument to the sine is hugely larger than the other arguments (power towers grow fast). And we can estimate the relative difference between $\sin\frac{113}{6^{6^6}}$ and $\frac{113}{6^{6^6}}$ by the mean value theorem: the relative error is between $0$ and $1-\cos\frac{113}{6^{6^6}}$. And we can again estimate the cosine as $1-\cos x\approx \frac12x^2$ for small $x$, so the absolute difference from 180 should be close to
$$ 113 \cdot \frac12 \cdot \frac{113^2}{6^{2\cdot 6^6}} \approx \frac{113^3}{2\cdot 6^{2\cdot 6^6}} $$
where the $6^{2\cdot 6^6}$ in the denominator dominates absolutely everything.
Since $\log_{10}(6^{2\cdot 6^6}) = \log_{10}(6)\cdot 2\cdot 6^6 > 6^6 = 46656$, the answer is
$$ 179.\underbrace{999999\ldots999999}_{\text{at least 46,650 nines}}\ldots $$

A: It can be shown that
$$\lim_{x \to 0}\, \sin x = x$$
so for $n \gg a$
$$\begin{align}
\sin(a/n) & \approx a/n\\
n\sin(a/n) & \approx a
\end{align}$$
Thus (as others have mentioned) the sum in the OP is approximately 180, assuming (as we should :) ) that the arguments of the $\sin()$ functions are in radians.
To estimate the error we can use the first few terms of the power series expansion of $\sin(x)$:
$$\sin(x) = x - x^3/3! + x^5/5! - x^7/7! + \cdots$$
So
$$\begin{align}
a - n\sin(a/n) & = a(1 - sin(a/n)/(a/n))\\
& \approx a(1 - ((a/n) - (a/n)^3/3! + (a/n)^5/5!))/(a/n)\\
& = a(1 - (1 - (a/n)^2/3! + (a/n)^4/5!))\\
& = a((a/n)^2/6 - (a/n)^4/120))\\
\end{align}$$
This approximation is ok even for relatively large $a/n$, as the table below shows.
 n: 1 - n sin(1/n) 1/(6n^2)       1/(6n^2) - 1/(120n^4)
 2: 4.11489228e-02 4.16666667e-02 4.11458333e-02
 4: 1.03841630e-02 1.04166667e-02 1.03841146e-02
 8: 2.60213292e-03 2.60416667e-03 2.60213216e-03
16: 6.50914522e-04 6.51041667e-04 6.50914510e-04
32: 1.62752470e-04 1.62760417e-04 1.62752469e-04
64: 4.06896075e-05 4.06901042e-05 4.06896075e-05

As Henning Makholm mentioned, most of the error comes from the $6^{6^{6}} \sin\left( \frac{113}{6^{6^{6}}} \right)$ term, so we can safely ignore the other terms.
For $a= 113, n = 6^{6^6}$
$n \approx$ 2.65911977e+36305
$a(a/n)^2/6 \approx$ 3.40101291e-72606
$a(a/n)^4/120 \approx$ 3.07085545e-145214
So the error is somewhat smaller than Henning's estimate. An error of 3.4e-72606 is tiny by anyone's standards, but it's positively enormous compared to the error in the next largest term:
For $a = 76, n = 7^{7^7}$
$n \approx$ 3.75982353e+695974
$a(a/n)^2/6 \approx$ 5.17552731e-1391945
$a(a/n)^4/120 \approx$ 1.05734538e-2783891


text:
Q: what is the difference between pathpattern and antpathmatcher in spring mvc? what is the difference between pathpattern and antpathmatcher in spring mvc?

what is the difference between pathpattern and antpathmatcher in spring mvc?

A: The reason PathPattern was introduced is explained in details in this post on spring.io. Here're few excerpts from the post:

In Spring applications AntPathMatcher is used to identify classpath, file system, remote, and other resources in Spring configuration. It has also been used in Spring MVC to match URL paths. Over time the use of patterns in web applications grew in number and syntax with AntPathMatcher evolving to meet those needs but some pain points remain without a solution.

The introduction of Spring WebFlux in Spring Framework 5.0 was a good opportunity to re-think all this and to create an alternative.

With PathPattern:

Patterns are parsed on startup and re-used at runtime for efficient URL matching. How much more efficient? It's hard to give numbers without a concrete use case but our jmh benchmark shows 6-8 times the throughput and 30-40% reduction in allocation rate.

PathPattern is compatible with AntPathMatcher syntax except couple cases (listed in the post.)


text:
Q: Qt Symbian Memory, unexpected application termination on device Recently I did develop a Symbian application. In Qt simulator it works perfect but in actual device the application terminates unexpectedly. I suspect this is a memory leak issue.
Already i have followed all possible(following) memory cleaning mechanisms:

*

*Creating new objects as pointers.

*deleting the objects after use

*using 'delete' keyword. using deleteLater() function on ui objects.

But still the application terminates on the device.
please suggest me possible solutions for this.

A: You can try increasing the Heap and/or Stack sizes using the EPOCHEAPSIZE and EPOCSTACKSIZE statements in your .PRO file
http://qt-project.org/doc/qt-4.8/qmake-platform-notes.html#stack-and-heap-size
Although it may depend on which Qt SDK you are using as the documentation now states that the Qt toolchain already sets these to the maximum possible values.


text:
Q: Hierarchical clustering on sparse observation matrix I'm trying to perform hierarchical clustering on large sparse observation matrix. The matrix represents movie ratings for a number of users.
My goal is to cluster similar users based on their movie preferences. However, I need a dendrogram, rather than single division. In order to do this, I tried to use SciPy:
R = dok_matrix((nrows, ncols), dtype=np.float32)

for user in ratings:
    for item in ratings[user]:
        R[item, user] = ratings[user][item]

Z = hierarchy.linkage(R.transpose().toarray(), method='ward')

This works fine on a small data-set:

However, I (obviously) get memory problems when scaling up.
If there any way I can feed sparse matrix to the algorithm?

A: From scipy/cluster/hierarchy.py linkage processes the y argument as:
y = _convert_to_double(np.asarray(y, order='c'))

if y.ndim == 1:
    distance.is_valid_y(y, throw=True, name='y')
    [y] = _copy_arrays_if_base_present([y])
elif y.ndim == 2:
    if method in _EUCLIDEAN_METHODS and metric != 'euclidean':
        raise ValueError("Method '{0}' requires the distance metric "
                         "to be Euclidean".format(method))
    y = distance.pdist(y, metric)
else:
    raise ValueError("`y` must be 1 or 2 dimensional.")

When I apply asarray to a dok I get a 0d object array.  It just wraps the dictionary in an array.
In [905]: M=sparse.dok_matrix([[1,0,0,2,3],[0,0,0,0,1]])
In [906]: M
Out[906]:
<2x5 sparse matrix of type '<class 'numpy.int32'>'
    with 4 stored elements in Dictionary Of Keys format>
In [908]: m = np.asarray(M)
In [909]: m
Out[909]:
array(<2x5 sparse matrix of type '<class 'numpy.int32'>'
    with 4 stored elements in Dictionary Of Keys format>, dtype=object)
In [910]: m.shape
Out[910]: ()

linkage accepts a 1d compressed style distance matrix, or the equivalent 2d one.
Looking further in linkage I deduce that ward uses nn_chain, which is in the compiled scipy/cluster/_hierarchy.cpython-35m-i386-linux-gnu.so file.  That puts the working part of the method even further out of reach of the casual Python programmer.


text:
Q: Windows Low-Level keyboard hook, allow (Win + H) not other Win + hotkeys We have a kiosk app where we would like to allow use of the Win + H hotkey to bring up Voice Typing, but still filter out other Win + ... hotkeys and the Win key by itself.
The hook is set with SetWindowsHookEx(WH_KEYBOARD_LL, callback, hInstance, 0);
Log from pressing Win + H:
// w = bool, GetAsyncKeyState for left and right windows keys
// h = bool, ...for "h" key
// key = KBDLLHOOKSTRUCY* pkh->vkCode,  72 = h, 91 = left Windows key
// flags = KBDLLHOOKSTRUCT* pkh->flags
// pressed Windows, then H, then released
w=0  h=0  key= 91  flags = 1
w=-1  h=0  key= 91  flags = 1
... repeats ....
w=-1  h=0  key= 91  flags = 1
w=-1  h=0  key= 72  flags = 0
w=-1  h=-1  key= 72  flags = 80
w=-1  h=0  key= 91  flags = 81

What I'm finding while trying different permutations of code in the callback is, either I get no keypress, or I get a plain h (so Voice Typing is not launched), or all other Win + ... hotkeys get through not just Win + H.
This treats the press as a plain h, so apparently at least some of the Win key events before the h events must be allowed past the filter:
if (nCode == HC_ACTION)
{
    BOOL bWinKeyDown = (GetAsyncKeyState(VK_LWIN) >> 15) | (GetAsyncKeyState(VK_RWIN) >> 15);
    if (pkh->vkCode == 'H')
    {
        // w=-1  h=0  key= 72  flags = 0
        // w=-1  h=-1  key= 72  flags = 80
        return CallNextHookEx(g_hHookKbdLL, nCode, wp, lp);
    }
    else if ((pkh->vkCode == VK_LWIN || pkh->vkCode == VK_RWIN))
    {
        // also just "h" if we allow through the w=-1  h=0  key= 91  flags = 1 events
        // if ((bWinKeyDown && (pkh->flags == 1))   )
        //    return CallNextHookEx(g_hHookKbdLL, nCode, wp, lp);
        //  else
        return -1;
    }
}
return CallNextHookEx(g_hHookKbdLL, nCode, wp, lp);

This lets all Win + ... hotkeys through, it seems like the first event acts as a "dead key" that gets applied to any next letter key:
if (nCode == HC_ACTION)
{
    BOOL bWinKeyDown = (GetAsyncKeyState(VK_LWIN) >> 15) | (GetAsyncKeyState(VK_RWIN) >> 15);
    if (pkh->vkCode == 'H')
    {
        // w=-1  h=0  key= 72  flags = 0
        // w=-1  h=-1  key= 72  flags = 80
        return CallNextHookEx(g_hHookKbdLL, nCode, wp, lp);
    }
    else if ((pkh->vkCode == VK_LWIN || pkh->vkCode == VK_RWIN))
    {
        if ((!bWinKeyDown && (pkh->flags == 1))) // // w=0  h=0  key= 91  flags = 1 - first event in log
            return CallNextHookEx(g_hHookKbdLL, nCode, wp, lp);
        else
            return -1;
    }

Is there any way to trap all Win + ... hotkey except for Win + H?

A: According to my test, win+h produces four messages, Index 1 to 4.

You can trap them at the second message. The following code which traps all Win+... hotkey except for win+h works for me.
LRESULT CALLBACK Proc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode == HC_ACTION)
    {
        KBDLLHOOKSTRUCT* s= (KBDLLHOOKSTRUCT*)lParam;
        std::cout << " Index=" << nwinhooksdll++ << "wParam="<< wParam <<" s->vkCode=" << s->vkCode << " s->scanCode=" << s->scanCode << " s->flags=" << s->flags << " s->dwExtraInfo=" << s->dwExtraInfo << "\n";
        if (GetAsyncKeyState(VK_LWIN))
        {
            if (s->vkCode == 'H')
            {

           }
            else
            {
                return 1;
            }
        }
    }

    return CallNextHookEx(_hook, nCode, wParam, lParam);
}

Update:
LRESULT CALLBACK CallWndProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode == HC_ACTION) {
        KBDLLHOOKSTRUCT* s = (KBDLLHOOKSTRUCT*)lParam;
        std::cout << " Index=" << nwinhooksdll++ << "wParam=" << wParam << " s->vkCode=" << s->vkCode << " s->scanCode=" << s->scanCode << " s->flags=" << s->flags << " s->dwExtraInfo=" << s->dwExtraInfo << "\n";
        static BOOL H = FALSE;
        static BOOL Other = FALSE;
        static BOOL Send = FALSE;
        if (Send) {
            Send = FALSE;
            INPUT inputs = {};
            inputs.type = INPUT_KEYBOARD;
            inputs.ki.wVk = VK_LWIN;
            inputs.ki.dwFlags = KEYEVENTF_KEYUP;
            UINT uSent = SendInput(1, &inputs, sizeof(INPUT));
        }
        if (GetAsyncKeyState(VK_LWIN) >> 15) {
            if (s->vkCode == 'H') {
                H = TRUE;
            }
            else if (s->vkCode == 91) {
                if (H || Other)
                {
                    H = FALSE;
                    Other = FALSE;
                    Send = TRUE;
                    std::cout << "return 1\n";
                    return 1;
                }else{

                }
            }else{
                Other = TRUE;
                if (wParam == 256) {
                    std::cout << "return 1\n";
                    return 1;
                }
            }
        }
    }
    return CallNextHookEx(_hook, nCode, wParam, lParam);
}

Update 2:
LRESULT CALLBACK Proc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode == HC_ACTION)
    {
        if (wParam > 0)
        {
            std::cout << "sent by the current thread wParam=" << wParam;
        }
        KBDLLHOOKSTRUCT* s= (KBDLLHOOKSTRUCT*)lParam;

        std::cout << " Index=" << nwinhooksdll++ << "wParam="<< wParam <<" s->vkCode=" << s->vkCode << " s->scanCode=" << s->scanCode << " s->flags=" << s->flags << " s->dwExtraInfo=" << s->dwExtraInfo << "\n";

        static BOOL H = FALSE;
        static BOOL Other = FALSE;
        static BOOL Send = FALSE;
        //TODO
        if (Send)
        {
            Send = FALSE;
            if (s->vkCode != 91 && s->scanCode != 0 && wParam == 256)
            {
                if (!H && !Other)
                {
                    INPUT inputs = {};
                    inputs.type = INPUT_KEYBOARD;
                    inputs.ki.wVk = s->vkCode;
                    inputs.ki.dwFlags = KEYEVENTF_KEYUP;
                    UINT uSent = SendInput(1, &inputs, sizeof(INPUT));
                }

                INPUT inputs = {};
                inputs.type = INPUT_KEYBOARD;
                inputs.ki.wVk = VK_LWIN;
                inputs.ki.dwFlags = KEYEVENTF_KEYUP;
                UINT uSent = SendInput(1, &inputs, sizeof(INPUT));
            }
        }

        H = FALSE;
        Other = FALSE;

        if (GetAsyncKeyState(VK_LWIN)>>15 && s->scanCode != 0)
        {
            if (s->vkCode == 'H')
            {
                H = TRUE;
            }
            else if (s->vkCode == 91)
            {
                    if (wParam == 257)
                    {
                        if (s->scanCode !=0)
                        {
                            Send = TRUE;
                            std::cout << "return 1\n";
                            return 1;
                        }
                    }
            }
            else
            {
                Other = TRUE;
                if (wParam == 256)
                {
                    std::cout << "return 1\n";
                    return 1;
                }
            }
        }
    }

    return CallNextHookEx(_hook, nCode, wParam, lParam);
}

A: You can just add a test for WM_KEYDOWN and add test when Win+ key is down and H is pressed down.
Returning non-zero value is not recommended, and the code below ends up eating a message, which is no good. But this is only eating the message for key down state. So everything should be okay once that key is released.
LRESULT CALLBACK kbd_proc(int nCode, WPARAM wp, LPARAM lp)
{
    if (nCode == HC_ACTION)
    {
        KBDLLHOOKSTRUCT* pkh = (KBDLLHOOKSTRUCT*)lp;
        BOOL bWinKeyDown = (GetAsyncKeyState(VK_LWIN) >> 15) |
                    (GetAsyncKeyState(VK_RWIN) >> 15);
        if (pkh->vkCode != 'H' && wp == WM_KEYDOWN && bWinKeyDown)
        {
            OutputDebugString(L"not Win+H...\n");
            return 1;
        }
    }
    return CallNextHookEx(g_hHookKbdLL, nCode, wp, lp);
}


text:
Q: How to compare two Foreach loops My current script checks if a specific folder on some clients exists.
I'd like to check if the client is online or offline before checking if the folder exists.
My current script looks like this:
$CDS = Get-content C:\Users\XY\Desktop\Clientliste.txt

Foreach($c in $CDS) {

    IF (Test-Connection -BufferSize 32 -Count 1 -ComputerName $c -Quiet) {

        Foreach ($c in $CDS) {
            $Test = Test-Path -path "\\$c\c$\apps\perl"
            Start-Sleep -s 0.25

            If ($Test -eq $True) {
                Write-Host "Path exists on $c."
            }
            Else {
                Write-Host "Path NOT exist on $c."
            }
        }
    }
    Else {
        Write-Host "The remote computer " $c " is Offline"
    }
}

I don't know how to link the foreach loops so that they work together.
Because when I run my script now, it goes after the first if request in the 2nd foreach loop and it does leave it first, when it finishes the 2nd foreach loop.
I don't want that. I want that if the client is online, it checks if the paths exists and then goes to the next client and checks again if it is online and then...
Maybe you can help me :)

A: Why do another identical loop over the items from the text file is you have already tested the machine is reachable?
Just remove that second loop and do:
$CDS = Get-Content -Path 'C:\Users\XY\Desktop\Clientliste.txt'
foreach($computer in $CDS) {
    if (Test-Connection -BufferSize 32 -Count 1 -ComputerName $computer -Quiet) {
        if (Test-Path -Path "\\$computer\C$\apps\perl" -PathType Container) {
            Write-Host "Path exists on computer '$computer'."
        }
        else {
            Write-Host "Path NOT exist on computer '$computer'."
        }
    }
    else {
        Write-Host "The remote computer '$computer' is Offline"
    }
}


text:
Q: Changing domain I set my domain in the WordPress without www i.e xyz.com but realised after setting that xyz.com wasn't redirecting to www.xyz.com. Now I am unable to login into the admin panel. I grepped through the code but saw that the domain is not set as a value to any variable. Is it saved in the DB? How can I change it?

A: You need to change your url for two places one is for "WordPress address (URL)" and for "Site address (URL)"
As you are unable to login to admin panel there is one option you can change it by modifying your database table in phpmyadmin. You might also need to udate Upload URL as well.
Easiest way to search tables is search your defined URL (e.g xyz.com) than you will find all tables using that URL than change all those to your full URL I would prefer with http (e.g. http://www.xyz.com)
Also check your config.php at root and if url is there and not correct than change it too.
If you are not using such plugin than it should not more than 2-3 places.


text:
Q: How to replace values between two rasters (matrix)? I have two rasters r and r2that I would like to replace some valus in r from r1
 library (raster)
 r <- raster(nrows=10, ncols=10)
 r <- setValues(r, 1:ncell(r))

 r1 <- raster(nrows=10, ncols=10)
 r1 <- setValues(r1, 1:ncell(r))

If the value for any pixel in r  equals 40 put the corresponding (replace it with) values from r1 .
so finally I will get r with values of 40 replaced with corresponding values from r1
well the two rasters here are identical but my data are not
Thanks for any help

A: Here's an approach. First, find the values in r that are equal to 255. Second, replace these values with corresponding values from r1.
idx <- values(r) == 255
values(r)[idx] <- values(r1)[idx]

A: There are two common ways to make replacements in rasters. Here I profile two:
> library(raster)
> rm(list=ls())
> r = raster('G:\\Faculty\\Mann\\Projects\\India_Index_Insurance\\Data\\India\\MOD13Q1_2002193_h24v05.250m_16_days_EVI.tif')
> r1 = raster('G:\\Faculty\\Mann\\Projects\\India_Index_Insurance\\Data\\India\\MOD13Q1_2002193_h24v05.250m_16_days_EVI.tif')
>
> ptm <- proc.time()
> idx <- values(r) <=0
> values(r)[idx] <- values(r1)[idx]
> proc.time() - ptm
   user  system elapsed
   2.76    0.73    7.19
>
> r = raster('G:\\Faculty\\Mann\\Projects\\India_Index_Insurance\\Data\\India\\MOD13Q1_2002193_h24v05.250m_16_days_EVI.tif')
> r1 = raster('G:\\Faculty\\Mann\\Projects\\India_Index_Insurance\\Data\\India\\MOD13Q1_2002193_h24v05.250m_16_days_EVI.tif')
>
> ptm <- proc.time()
> index = r<=0
> r[index]=r1[index]
> proc.time() - ptm
   user  system elapsed
   5.44    0.89    9.20

If you are running this operation on a rasterstack or a large number of smaller rasters I would recommend learning foreach %dopar% to parallelize your code. Vignette here: https://cran.r-project.org/web/packages/foreach/vignettes/foreach.pdf
If you are running it on one or two very large rasters (running into memory limits) you should read the vignette on handling large rasters: https://cran.r-project.org/web/packages/raster/vignettes/functions.pdf
For a detailed discussion of R data types (and explanations of why some things are so slow) see Hadley Wickam's site http://adv-r.had.co.nz/ in particular: http://adv-r.had.co.nz/Performance.html#implementation-performance


text:
Q: Run Github Action as sudo I am using a fastlane Github action. I need to run it as the root user.
      - name: Deploy
        uses: maierj/fastlane-action@v1.4.0
        with:
          lane: 'alpha'
          subdirectory: 'android-staging'

How can I run this as sudo?

A: The Linux and macOS virtual machines both run using passwordless sudo. When you need to execute commands or install tools that require more privileges than the current user, you can use sudo without needing to provide a password.
Taken from https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#administrative-privileges


text:
Q: HI, I want to visualise a specific row plot for all columns in a dataframe using plotly In the dataframe attached, I want to plot all the columns(fat, saturates, sugars, salt and cal) for  diet_coke  against date as the x axis for all the dates using plotly barchart function.
dataframe