text:
Q: Boost async server buffer error I am trying to make a server & client in boost asio. Currently I am receiving this error. Can you point me what I am doing wrong?
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>

// Forward declaration
class ASyncConnectionMT;
class ASyncEchoServerMT;

// Typedef for the buffer type (shared_ptr)
typedef boost::array < char , 65536 > Buffer;
typedef boost::shared_ptr < Buffer > BufferPtr;

// Typedef for the ASyncConnectionMT shared_ptr
// Typedef for the ASyncEchoServerMT shared_ptr
// Derived from "enable_shared_from_this" so the 'this' object can
// be passed as shared_ptr to the callback function
typedef boost::shared_ptr < ASyncConnectionMT > ASyncConnectionMTPtr;
typedef boost::shared_ptr < ASyncEchoServerMT > ASyncEchoServerMTPtr;

// Class the handles the client
class ASyncConnectionMT : public::boost::enable_shared_from_this<ASyncConnectionMT>
{

private:    // The socket class for communication.
            boost::asio::ip::tcp::socket m_socket;

            // Strand object to synchronise calling handlers. Multiple threads might acces the socked
            // at the same time since send and recieve are started asynchronously at the same time
            boost::asio::strand m_strand;

public:     // Constructor with the IO service to use
            ASyncConnectionMT ( boost::asio::io_service& ios) : m_socket(ios), m_strand (ios)
            {
            }

            // Retrieve the socked used by this connection
            // Need to be passed to acceptor.accept() function
            boost::asio::ip::tcp::socket& Socket()
            {
                return m_socket;
            }

            // Start handling the connection
            void Start()
            {
                std:: cout << m_socket.remote_endpoint() << ": Connection accepted" << std:: endl ;
                StartReceiving() ;
            }

            // Start receiving data
            void StartReceiving()
            {
                // Create receive buffer
                BufferPtr receiveBuffer ( new Buffer ) ;

                // Start async read, must pass 'this' as shared_ptr, else the
                // 'this' object will be destroyed after leaving this function
                async_write ( m_socket,  boost::asio::buffer ( *receiveBuffer ) , m_strand.wrap ( boost::bind ( &ASyncConnectionMT::HandleReceived, shared_from_this() ,
                    receiveBuffer , boost::asio::placeholders::error ,
                    boost::asio::placeholders::bytes_transferred ) ) ) ;
            }

            // Handle received data
            void HandleReceived ( BufferPtr receiveBuffer , const boost::system::error_code& ec , size_t size)
            {

                if (!ec)
                {
                    // Print received message
                    std:: cout << m_socket.remote_endpoint() << ": Message received: " << std:: string (receiveBuffer -> data() , size ) << std:: endl ;

                    // Convert to uppercare. We can't use the same buffer because that could be
                    // overwritten by another recieve

                    // UPD -> boost shared_ptr<TBuffer> sendBuffer(new TBuffer());
                    BufferPtr sendBuffer ( new Buffer ) ;
                    for ( size_t i=0 ; i!=size ; i++ )
                    {
                        (( &sendBuffer )[i]) = toupper (( &receiveBuffer )[i]) ;
                    }

                    // Start sending reply, must pass 'this' as shared_ptr, else the 'this' object will be
                    // destroyed after leaving this function. We pass the buffer as shared_ptr to the handler
                    // so the buffer is still in memory after sending is complete. Without it, the buffer could
                    // be deleted before the send operation is complete. The Handle Set is now synchronised via the strand.
                    async_write ( m_socket,  boost::asio::buffer ( *sendBuffer , size ) , m_strand.wrap ( boost::bind ( &ASyncConnectionMT::HandleSent ,
                                                                                shared_from_this() , sendBuffer ,
                                                                                boost::asio::placeholders::error ,
                                                                                boost::asio::placeholders::bytes_transferred ) ) ) ;

                    // Start receiving next bit

                    StartReceiving() ;

                }

                else if ( ec == boost::asio::error::eof)
                {
                    // Client disconnected. Close the socket.
                    std:: cout << m_socket.remote_endpoint() << ": Connection closed ( handle received )" << std:: endl;
                    m_socket.close();
                }

            }

            // Handle for when the data si sent
            void HandleSent ( BufferPtr sendBuffer , const boost::system::error_code& ec , size_t size)
            {

                if (!ec)
                {
                    // Start receiving again
                    StartReceiving() ;

                }

                else if ( ec == boost::asio::error::eof)
                {
                    // Client disconnected. Close the socket.
                    std:: cout << m_socket.remote_endpoint() << ": Connection closed ( handle received )" << std:: endl;
                    m_socket.close();
                }

                else
                {
                    std:: cout << "Error: " << ec.message << std:: endl ;
                }
            }

};

I am receiving the following errors.

*

*C3967 - boost::system::error_code::message': function call missing argument list; use '&'boost::system::error_code::message' to create a pointer to member

*C2664 - 'toupper' : cannot convert parametor 1 from 'BufferPtr' to 'int'

*C2512 - 'boost::array' : no appropriate default constructor available

*C2039 - 'data' : is not a member of 'boost::shared_prt'

*C2027 - use of undefined type 'boost::array '

*pointer to incomplete class type is not allowed

*no suitable conversion function from "BufferPtr" to "int" exists

*incomplete type is not allowed

Thanks in advance.

A: *

*You missed the include
#include <boost/array.hpp>

*The toupper loop is wrong
((&sendBuffer)[i]) = toupper((&receiveBuffer)[i]);

should be more like
((*sendBuffer)[i]) = toupper((*receiveBuffer)[i]);

or even more like
std::transform(receiveBuffer->begin(), receiveBuffer->end(), sendBuffer->begin(), static_cast<int(&)(int)>(std::toupper));

Pro tip: consider using unsigned char in the buffer to avoid unwanted sign extension when passing int to_upper
((*sendBuffer)[i]) = toupper(static_cast<unsigned char>((*receiveBuffer)[i]));

*like the comment (and the compiler message) says:
        std::cout << "Error: " << ec.message << std::endl;

should be
        std::cout << "Error: " << ec.message() << std::endl;

Then it compiles. No guarantees it does what you expect (I haven't read the code)


text:
Q: Good Case For Interfaces I work at a company where some require justification for the use of an Interface in our code (Visual Studio C# 3.5).
I would like to ask for an Iron Clad reasoning that interfaces are required for.  (My goal is to PROVE that interfaces are a normal part of programming.)
I don't need convincing, I just need a good argument to use in the convincing of others.
The kind of argument I am looking for is fact based, not comparison based (ie "because the .NET library uses them" is comparison based.)
The argument against them is thus:  If a class is properly setup (with its public and private members) then an interface is just extra overhead because those that use the class are restricted to public members.  If you need to have an interface that is implemented by more than 1 class then just setup inheritance/polymorphism.

A: To enable unit testing of the class.
To track dependencies efficiently (if the interface isn't checked out and touched, only the semantics of the class can possibly have changed).
Because there is no runtime overhead.
To enable dependency injection.
...and perhaps because it's friggin' 2009, not the 70's, and modern language designers actually have a clue about what they are doing?
Not that interfaces should be thrown at every class interface: just those which are central to the system, and which are likely to experience significant change and/or extension.

A: Interfaces and abstract classes model different things. You derive from a class when you have an isA relationship so the base class models something concrete. You implement an interface when your class can perform a specific set of tasks.
Think of something that's Serializable, it doesn't really make sense (from a design/modelling point of view) to have a base class called Serializable as it doesn't make sense to say something isA Serializable. Having something implement a Serializable interface makes more sense as saying 'this is something the class can do, not what the class is'

A: Interfaces are not 'required for' at all, it's a design decision. I think you need to convince yourself, why, on a case-by-case basis, it is beneficial to use an interface, because there IS an overhead in adding an interface. On the other hand, to counter the argument against interfaces because you can 'simply' use inheritance: inheritance has its draw backs, one of them is that - at least in C# and Java - you can only use inheritance once(single inheritance); but the second - and maybe more important - is that, inheritance requires you to understand the workings of not only the parent class, but all of the ancestor classes, which makes extension harder but also more brittle, because a change in the parent class' implementation could easily break the subclasses. This is the crux of the "composition over inheritance" argument that the GOF book taught us.

A: You've been given a set of guidelines that your bosses have thought appropriate for your workplace and problem domain. So to be persuasive about changing those guidelines, it's not about proving that interfaces are a good thing in general, it's about proving that you need them in your workplace.
How do you prove that you need interfaces in the code you write in your workplace? By finding a place in your actual codebase (not in some code from somebody else's product, and certainly not in some toy example about Duck implementing the makeNoise method in IAnimal) where an interface-based solution is better than an inheritance-based solution. Show your bosses the problem you're facing, and ask whether it makes sense to modify the guidelines to accommodate situations like that. It's a teachable moment where everyone is looking at the same facts instead of hitting each other over the head with generalities and speculations.
The guideline seems to be driven by a concern about avoiding overengineering and premature generalisation. So if you make an argument along the lines of we should have an interface here just in case in future we have to..., it's well-intentioned, but for your bosses it sets off the same over-engineering alarm bells that motivated the guideline in the first place.
Wait until there's a good objective case for it, that goes both for the programming techniques you use in production code and for the things you start arguments with your managers about.

A: Code decoupling.  By programming to interfaces you decouple the code using the interface from the code implementing the interface.  This allows you to change the implementation without having to refactor all of the code using it.  This works in conjunction with inheritance/polymorphism, allowing you to use any of a number of possible implementations interchangeably.
Mocking and unit testing.  Mocking frameworks are most easily used when the methods are virtual, which you get by default with interfaces.  This is actually the biggest reason why I create interfaces.
Defining behavior that may apply to many different classes that allows them to be used interchangeably, even when there isn't a relationship (other than the defined behavior) between the classes.  For example, a Horse and a Bicycle class may both have a Ride method.  You can define an interface IRideable that defines the Ride behavior and any class that uses this behavior can use either a Horse or Bicycle object without forcing an unnatural inheritance between them.

A:
The argument against them is thus: If
  a class is properly setup (with its
  public and private members) then an
  interface is just extra overhead
  because those that use the class are
  restricted to public members. If you
  need to have an interface that is
  implemented by more than 1 class then
  just setup inheritance/polymorphism.

Consider the following code:
interface ICrushable
{
  void Crush();
}

public class Vehicle
{
}

public class Animal
{
}

public class Car : Vehicle, ICrushable
{
  public void Crush()
  {
     Console.WriteLine( "Crrrrrassssh" );
  }
}

public class Gorilla : Animal, ICrushable
{
  public void Crush()
  {
     Console.WriteLine( "Sqqqquuuuish" );
  }
}

Does it make any sense at all to establish a class hierarchy that relates Animals to Vehicles even though both can be crushed by my giant crushing machine?  No.

A: *

*Test Driven Development

*Unit Testing

Without interfaces producing decoupled code would be a pain. Best practice is to code against an interface rather than a concrete implementation. Interfaces seem rubbish at first but once you discover the benefits you'll always use them.

A: *

*You can implement multiple interfaces. You cannot inherit from multiple classes.

*..that's it. The points others are making about code decoupling and test-driven development don't get to the crux of the matter because you can do those things with abstract classes too.

A: Interfaces allow you to declare a concept that can be shared amongst many types (IEnumerable) while allowing each of those types to have its own inheritance hierarchy.
In this case, what we're saying is "this thing can be enumerated, but that is not its single defining characteristic".
Interfaces allow you to make the minimum amount of decisions necessary when defining the capabilities of the implementer. When you create a class instead of an interface, you have already declared that your concept is class-only and not usable for structs. You also make other decisions when declaring members in a class, such as visibility and virtuality.
For example, you can make an abstract class with all public abstract members, and that is pretty close to an interface, but you have declared that concept as overridable in all child classes, whereas you wouldn't have to have made that decision if you used an interface.
They also make unit testing easier, but I don't believe that is a strong argument, since you can build a system without unit tests (not recommended).

A: In addition to things explained in other answers, interfaces allow you simulate multiple inheritance in .NET which otherwise is not allowed.
Alas as someone said
Technology is dominated by two types of people: those who understand what they do not manage, and those who manage what they do not understand.

A: If your shop is performing automated testing, interfaces are a great boon to dependency injection and being able to test a unit of software in isolation.

A: The problem with the inheritance argument is that you'll either have a gigantic god class or a hierarchy so deep, it'll make your head spin.  On top of that, you'll end up with methods on a class you don't need or don't make any sense.
I see a lot of "no multiple inheritance" and while that's true, it probably won't phase your team because you can have multiple levels of inheritance to get what they'd want.
An IDisposable implementation comes to mind.  Your team would put a Dispose method on the Object class and let it propagate through the system whether or not it made sense for an object or not.

A: An interface declares a contract that any object implementing it will adhere to. This makes ensuring quality in code so much easier than trying to enforce written (not code) or verbal structure, the moment a class is decorated with the interface reference the requirements/contract is clear and the code won't compile till you've implemented that interface completely and type-safe.
There are many other great reasons for using Interfaces (listed here) but probably don't resonate with management quite as well as a good, old-fashioned 'quality' statement ;)

A: Well, my 1st reaction is that if you've to explain why you need interfaces, it's a uphill battle anyways :)
that being said, other than all the reasons mentioned above, interfaces are the only way for loosely coupled programming, n-tier architectures where you need to update/replace components on the fly etc. - in personal experience however that was too esoteric a concept for the head of architecture team with the result that we lived in dll hell - in the .net world no-less !

A: Please forgive me for the pseudo code in advance!
Read up on SOLID principles.  There are a few reasons in the SOLID principles for using Interfaces.  Interfaces allow you to decouple your dependancies on implementation.  You can take this a step further by using a tool like StructureMap to really make the coupling melt away.
Where you might be used to
Widget widget1 = new Widget;

This specifically says that you want to create a new instance of Widget.  However if you do this inside of a method of another object you are now saying that the other object is directly dependent on the use of Widget.  So we could then say something like
public class AnotherObject
{
    public void SomeMethod(Widget widget1)
    {
        //..do something with widget1
    }
}

We are still tied to the use of Widget here.  But at least this is more testable in that we can inject the implementation of Widget into SomeMethod.  Now if we were to use an Interface instead we could further decouple things.
public class AnotherObject
{
    public void SomeMethod(IWidget widget1)
    {
        //..do something with widget1
    }
}

Notice that we are now not requiring a specific implementation of Widget but instead we are asking for anything that conforms to IWidget interface.  This means that anything could be injected which means that in the day to day use of the code we could inject an actual implementation of Widget.  But this also means that when we want to test this code we could inject a fake/mock/stub (depending on your understanding of these terms) and test our code.
But how can we take this further.  With the use of StructureMap we can decouple this code even more.  With the last code example our calling code my look something like this
public class AnotherObject
{
    public void SomeMethod(IWidget widget1)
    {
        //..do something with widget1
    }
}

public class CallingObject
{
    public void AnotherMethod()
    {
        IWidget widget1 = new Widget();
        new AnotherObject().SomeMethod(widget1);
    }
}

As you can see in the above code we removed the dependency in the SomeMethod by passing in an object that conforms to IWidget.  But in the CallingObject().AnotherMethod we still have the dependency.  We can use StructureMap to remove this dependency too!
[PluginFamily("Default")]
public interface IAnotherObject
{
    ...
}

[PluginFamily("Default")]
public interface ICallingObject
{
    ...
}

[Pluggable("Default")]
public class AnotherObject : IAnotherObject
{
    private IWidget _widget;
    public AnotherObject(IWidget widget)
    {
        _widget = widget;
    }

    public void SomeMethod()
    {
        //..do something with _widget
    }
}

[Pluggable("Default")]
public class CallingObject : ICallingObject
{
    public void AnotherMethod()
    {
        ObjectFactory.GetInstance<IAnotherObject>().SomeMethod();
    }
}

Notice that no where in the above code are we instantiating an actual implementation of AnotherObject.  Because everything is wired for StructurMap we can allow StructureMap to pass in the appropriate implementations depending on when and where the code is ran.  Now the code is truely flexible in that we can specify via configuration or programatically in a test which implementation we want to use.  This configuration can be done on the fly or as part of a build process, etc.  But it doesn't have to be hard wired anywhere.

A: Appologies as this doesn't answer your question regarding a case for Interfaces.
However I suggest getting the person in question to read..
Head First Design Patterns
-- Lee

A: I don't understand how its extra overhead.
Interfaces provide flexibility, manageable code, and reusability. Coding to an interface you don't need to worry about the concreted implementation code or logic of the certain class you are using. You just expect a result. Many class have different implementation for the same feature thing (StreamWriter,StringWriter,XmlWriter)..you do not need to worry about how they implement the writing, you just need to call it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Making sprite appear at random position I'm trying to make a sprite "comet" appear at a random position at random times. So far, I wanted to test if my random position code works, however, I can't seem to even see the sprite. This is my code:
 func spawnAtRandomPosition() {
        let height = self.view!.frame.height
        let width = self.view!.frame.width

        let randomPosition = CGPointMake(CGFloat(arc4random()) % height, CGFloat(arc4random()) % width)

        let sprite = SKSpriteNode(imageNamed: "comet")
        sprite.position = randomPosition
        self.addChild(sprite)
    }

As I said, I'm not seeing anything. Any help? If you already know how to make it appear at a random time that would be appreciated as well, because that's having problems of its own, however this is my focus right now. Thanks!

A: Your code for setting the random position is incorrect. Additionally, your code has issues that should make it impossible to compile in Swift 3. Your full function should look like this:
func spawnAtRandomPosition() {
        let height = UInt32(self.size.height)
        let width = UInt32(self.size.width)

        let randomPosition = CGPoint(x: Int(arc4random_uniform(width)), y: Int(arc4random_uniform(height)))

        let sprite = SKSpriteNode(imageNamed: "comet")
        sprite.position = randomPosition
        self.addChild(sprite)
    }

Note the changes to randomPosition and the height and width:
let randomPosition = CGPoint(x: Int(arc4random_uniform(width)), y: Int(arc4random_uniform(height)))

This determines a random value between 0 and your width and does the same thing for the height.
As for the height and width, see @Whirlwind's comment on the question explaining the difference between the view and the scene.
Additionally, you may want to check if you're setting up your node properly (set size, try with fixed location, etc) before you test the random positioning, to determine where the problem truly lies.

A: I came up with this bit of code and it works for me:
    let randomNum = CGPoint(x:Int (arc4random() % 1000), y: 1)

    let actionMove =  SKAction.moveTo(randomNum, duration: 1)

I only wanted the x to be randomized, however if you need "y" to be randomized as well, you can just copy the specification to x to y.


text:
Q: Laravel config subfolder not recognized on new server I have some config files of US state counties, for example:
config/
    state/
        alabama/
            counties.php
        alaska/
            counties.php
        ...

And on my development localhost server, I call them with:
Config::get('state/alabama/counties');

and it works, it loads an array of counties which I display somewhere.
But when I deploy this app on the Heroku, they won't show up.
    I was thinking that it maybe has a problem with treating the config/state/subfolder as an environment config?
I do have a config/staging subfolder, in which I have new DB config stuff, and it works with no problem,
    but on the Heroku app, the states just won't show up.

A: Have you added this directory to your autoload mapping in composer.json and then run composer dump-autoload?  Without this, Laravel doesn't know to load your new files in to consideration.
Composer is a CLI-run file that exists in the Root of each laravel installation.  composer.json is the config file for Composer - it uses this to manage your dependencies.
There's a section in composer.json called "autoload."  These are the files that will automatically be loaded each time the app boots.  Mine looks like this:
"autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php",
            "app/core"
        ]

For each folder that didn't exist before and that I wanted Laravel to understand, I added an entry here.  Then, I ran composer dump-autoload and Laravel "understood" where the files I wanted to use were.
Each time you add a file, class, repository - anything that you want Laravel to automatically use, you'll have to run composer dump-autoload.
P.S: If composer dump-autoload doesn't work, try composer.phar dump-autoload.


text:
Q: Google Play Developer Console Showing Security Alerts Even Updating the Cordova Version 5.0.0 I have already upgraded my Cordova version to: 5.0.0 and Google Play Developer console still showing this below alert and that affected my latest APK version.
Your app is using a version of Apache Cordova containing one or more security vulnerabilities. Please see this Google Help Center article for details, including the deadline for fixing the app.
Affects APK version 1.


text:
Q: error when install hg in mac os x 10.9 with python 2.7 I'm trying to install hg in my mac.  My OS is 10.9(BD2). I use easy_install mercurial or pip install -U Mercurial, but all these prints error:
error: command 'gcc' failed with exit status 1
And I can use gcc command in my mac, what's wrong?

A: This might be because you do not have python development headers installed.  If you're on Linux, try installing the dev packages:
apt-get install python-dev
apt-get install libevent-dev

Otherwise, you can install Mercurial in a virtualenv:
sudo easy_install virtualenv
mkdir myenv && cd myenv && virtualenv . && . bin/activate
pip install Mercurial hg-git

(only include hg-git in pip install if you need it)
If the virtualenv command in the second line of the Mac instructions is not found in your PATH, then supplying a full path, like this, might work:
$  /usr/local/Cellar/python/2.7.1/Frameworks/Python.framework/Versions/2.7/bin/virtualenv .

A: For things like Mercurial, it's often easier and "better" to use the binary distribution. The release for OS X 10.8 can be found here -- I imagine it will also work on 10.9.  The different releases for different versions of OS X are primarily related to differences in system python. Since 10.8 comes with Python 2.7, which is the newest -- and last -- version of the Python 2.x series, I think it's safe to assume that the Python version won't produce much difficulty here.
The binary distribution has two advantages:

*

*you avoid compilation issues, such as ones not related to being able to find the correct headers (suggested in this answer

*the binary installer will also do all the necessary work involving your path
The "disadvantage" is basically that you have effectively installed a full-fledged Unix utility and not just a python package in your site-packages folder.
Another option, albeit much more complicated, is to download the sources and do a full build yourself. It's actually not as hard as it sounds, and you would be able to see exactly where the compile step fails.


text:
Q: Adding node to Cassandra cluster causes CPU overload on existing nodes So, here is our setup so far:

*

*Cassandra 2.0.10, JDK 1.7.0_65-b17

*6 nodes (EC2 c3.8xlarge/ 32 cores/60GB RAM, EBS disks for data,
ephemeral SSD for commit logs etc)

*pretty heavy write load - 100Ks/second

*RF=2, one dc, 2 racks

*everything works just fine with low CPU consumption - load average tends to be around 4-10

Now, we are trying to add a node. This cases a heavy load on existing nodes - like over 100 load average. The cluster becomes unresponsive, writes and reads mostly fail.
The weird observations are that:
 - without adding new node CPU is low
 - if we turn off writes while adding a new node load average on existing nodes drops back to 4-10 and the new node just fine
I've checked VisualVM sampling and basically all the CPU on existing nodes is consumed by org.jboss.netty.channel.socket.nio.SelectorUtil.select().
What we tried so far:

*

*throttling streaming - no impact

*disabling internode compression - no impact

*disabling autocompaction on existing nodes - no impact

*even running with -Dorg.jboss.netty.epollBugWorkaround=true - no impact

And as of now we are somewhat desperate as this behavior is a blocker for us - we can't afford losing writes and we will need to expand C* dynamically.
Anyone has encountered something similar? Any ideas/hints? Thanks
EDIT: OS is Ubuntu 12.04
EDIT: I still have no idea what causes the behavior above and I'm still curious. OTOH, I've managed to add a couple of nodes w/o any disruption, cpu usage increase, etc by using the following sequence of actions:

*

*set auto_bootstrap: false

*start node, join

*run nodetool rebuild on this new node

*bingo

This scheme will do as a workaround for our case. But it looks somewhat clumsy

A: Have you tried Cassandra virtual node?
I guess with RF=2, when you try to add a new node, 2 existing nodes would be very busy to transfer their data to the new node while responding to your heavy write load at the same time, which would possibly lead to a hot spot problem.


text:
Q: why wont jquery work on my js fiddle? this is a very simple question, I have never gotten jquery selectors to work on jsfiddle and I still dont know why. I don't think there's anything wrong with my code, but its not outputting what its supposed to in my firebug console. Not even a simple id selector.
This is my Jsfiddle

 inner

var h = $('#hi');
console.log(h);
output is [p#hi]

My main objective is to get this array to output:
var allDates = $("[data-test='date']");
allDates.each(function(item,index){ //each is javascript function
 item[index] = new Date($(this).text());

A: Your selector is wrong. You are requesting var h = $('#id');, but you're looking for var h = $('#hi');
FYI a
 tag inside a table tag is invalid HTML. This should either be inside a th or td or outsize the table tag.

A: In your html place your P tag in a cell in a table row:

inner

      12/09/14

        12/10/14

        12/11/14

        12/12/14

Then in your javascript select by the corect identifier - $('#hi') in your case:
var allDates = $("[data-test='date']");
var h = $('#hi');
allDates.each(function(item,index)
{
     item[index] = new Date($(this).text());
});
console.log(allDates);
console.log(h);


text:
Q: Заменить символ в начале строки Нужно реализовать следующее:
Заменять английскую E на YE, если E стоит в начале любого слова в строке или после a, o, i, e, u, y
Буду очень благодарен за пример регулярного выражения! Или объяснению тому, как с помощью preg_replace можно проверить каждую первую букву в каждом слове и заменить ее

A: Как то так на вскидку -
preg_replace("/(^|\s|a|o|i|e|u|y)([e|E])/", "$1Y$2", $string);

с учетом регистра.


text:
Q: How to set shipping method to shipping class in woo commerce? How to set shipping method to shipping class. like an example
Flate rate shipping class - Flate rate method
Usps Shipping class - Usps Method
Or
How can we by hook also?

A: Use woocommerce_package_rates hook.This will do the trick
 add_filter('woocommerce_package_rates', 'manage_method_basedon_shipping_class', 10, 2);
function manage_method_basedon_shipping_class($methods, $package)
{
    // $package have cart  items, so loop through that and get your shipping classes available in the cart. like $item->get_shipping_class().

// So you have all the classes now. Now based on this unset shipping methods from $method function. $method have all available shipping methods

// now return $methods;

}

I have written logic in the above code, not with actual shipping IDs. This is pretty easy. You can manage it.


text:
Q: Main app component not able to get params I have a scenario where the first segment in the url will be a unique identifier. That unique identifier will be used in main routes and in the child routes as well.
Here is how i have defined my routes config
export const routes:RouterConfig = [{
    path: ':academy_url',
    children: [
        {path: '', component: CoursesComponent},
        {path: 'courses',
            children: [
                {path: '', component: CoursesComponent}
            ]
        }
    }
];

:academy_url is the param i plan on using in the child components. I can access this param in the child components (CoursesComponent for example), but i do not have for some reason access to it in the main app component.
The params array is empty in the main component when i try observables as well as snapshot.How do i access this param in app component? Right now i have a workaround which depends on a service emitting the param value from child components, but that is very inconvenient as this happens every time a component loads or page refreshed.
I need a more direct approach and i feel that it's either a bug or maybe the main app component is not supposed to have access to entry level params?
Also, i tried to create a plunker but i'm not sure how i make it work in there as it gives me undefined route error for it's plunker url key.


text:
Q: Is there an R function for finding differences in ChiSqr results Here is an example contingency table using R
group = c("A","B","C","D","E")
Fail = c(424, 357, 324, 339, 160)
Pass = c(314, 263, 212, 252, 540)
Q1tab = data.frame(group, Fail, Pass)

From what i'm reading, I think I should be doing a Chi Sqr test.
chisq.test(Q1tab,correct=F)

#Output
Pearson's Chi-squared test

data:  Q1tab
X-squared = 272.99, df = 4, p-value < 2.2e-16

It shows significance but I have no idea where the differences are. With an ANOVA, I can use Tukey's but I can't here. I feel like I'm missing something basic - any help is appreciated.

A: Check out the documentation for chisq.test ?chisq.test It tells you what you can get out of the function. In general with R, it best to save your test result to variable (ANOVA, linear regressions, t.tests etc) because there is always more information that what R prints out. They try to keep it simple for people who just want run some fast tests. See below for an example of what you can get from chisq.test.
results<-chisq.test(Q1tab,correct=F)
results$residuals #Pearson residuals
results$observed #observed counts
results$expected #expected counts


text:
Q: Swift - Filter an array by pruning child "owned" items from a given parent I have a relationship which can be described as:
Factory -< Engine
A player only has a reference to engines that he owns;
ie:
Player: { name: "Bob", engines: [Engine]() }
I wish to filter the factories on whether a certain player can afford the factory; but also I want to filter out all the engines that the player already owns.
That is to say,

a player can only ever buy each factory once.

..
My code to filter out affordable factories is this:
  let results = factories.filter { (factory:Factory) -> Bool in
      return ((factory.cost <= Int(firstPlayer.cash)) && (factory.isUnlocked))
  }

My code to filter engines that a player owns, for a given parent factory
  let ownedEngines = player.engines.filter { (eng:Engine) -> Bool in
      return ((eng.owner == player) && (eng.parent == factory))
  }

But how to I combine them to say;
Give me a list of all factories that I don't already own, and that I can afford?
Many thanks

Edit: Classes outlines follow
class Factory {
  var name: String
  var cost: Int
  var engines: [Engine] = [Engine]()
}

class Engine {
  var name: String
  weak var parent: Factory?
  weak var owner: Player?
  var units: Int
}

class Player {
  var name: String
  var cash: Int
  var engines: [Engine] = [Engine]()
}

Further info
The best way I can describe it is;
The game represents several Factories collected together in [decks].
Each deck has multiple cards in it; these are the Engines.
Each player cannot buy the same factory more than once.
I need a reference to how many units and other meta data for the child object, hence this is why there is an Engine entity.
So when a player buys a factory, they in fact buy an Engine and never directly own the Factory.  All references can be gathered from the child objects.
I require to filter out:

*

*my decks of all factories that I can afford

*all factories that I already own via my engine cards

So I do it this way currently;
// static Function in my factory model
    public static func filterDecksForCash(decks: [Factory], cash:Int) -> [Factory] {
            let results = decks.filter { (f:Factory) -> Bool in
                return ((loco.cost <= Int(cash)) && (loco.isUnlocked))
            }
            return results
        }

let decks = Factory.createAll()

        // filter deck for cost, unlock but also all trains but also remove trains they've already purchased
        var results = Factory.filterDecksForCash(decks: decks, cash: firstPlayer.cash)

        for (index, factory) in results.enumerated() {
            for eng in factory.engines {
                if (eng.owner == firstPlayer) {
                    results.remove(at: index)
                }
            }
        }

A: I've decided to run a for-loop which prunes off items I don't want.
Issue closed.
I am using also experimenting with a similar function to this;
let filtered = decks.filter { (deck:EYLocomotive) -> Bool in
            return ((deck.isUnlocked) && (deck.orders.count > 0))
            }.map({ $0.engines.filter({ (eng:EYEngine) -> Bool in
                return (eng.owner != nil)
            })})


text:
Q: Pandas Group by and then find mean not working as expected Given the following table:
quarter     town    flat_type   median_rent
2011    CLEMENTI    4-RM    2250
2011    CLEMENTI    4-RM    2300
2011    CLEMENTI    4-RM    2300
2011    CLEMENTI    4-RM    2400

The median average rent for 4-RM in 2011 is (2250+2300+2300+2400)/4 = 2312.5.
My current code:
test = df.groupby(["town","quarter"], as_index=True)

print(test['median_rent'].mean())

output:
town      quarter
CLEMENTI  2011       5.625575e+14
          2012       5.875638e+14
          2013       6.500675e+14
          2014       6.875675e+14
          2015       6.625650e+14
          2016       6.500650e+14
          2017       6.250613e+14
          2018       5.750575e+14
          2019       7.667467e+10
          2020       4.800470e+18
          2021       6.000625e+14
Name: median_rent, dtype: float64

This is not what is expeced. What am I doing wrong?

A: Judging by the sample code that you have written, you actually need to group by flat_type and quarter, not town and quarter. Just try
test = df.groupby(["flat_type", "quarter"], as_index=True)

and see whether it is what you were expecting.
Edit: also, it is a great idea to share what you WERE expecting, because otherwise we have no way of knowing what do you want us to help with. This specific line of code does exactly what it is expected to do - groups by 2 attributes and takes an average of the 3rd attribute.

A: the groupby object should be used either to split the groupBy key and grouped df, or to apply actions directly to
example of applying mean directly to the groupby
import pandas as pd

df = pd.read_csv('tmp.csv')
print(df)

test = df.groupby(["town","quarter"], as_index=True)['median_rent'].mean()
print(test)

tmp.csv
quarter,town,flat_type,median_rent
2011,CLEMENTI,4-RM,2250
2011,CLEMENTI,4-RM,2300
2011,CLEMENTI,4-RM,2300
2011,CLEMENTI,4-RM,2400
2012,CLEMENT,4-RM,2250
2012,CLEMENT,4-RM,2300
2011,CLEMENT,4-RM,2300
2011,CLEMENT,4-RM,2400

output
   quarter      town flat_type  median_rent
0     2011  CLEMENTI      4-RM         2250
1     2011  CLEMENTI      4-RM         2300
2     2011  CLEMENTI      4-RM         2300
3     2011  CLEMENTI      4-RM         2400
4     2012   CLEMENT      4-RM         2250
5     2012   CLEMENT      4-RM         2300
6     2011   CLEMENT      4-RM         2300
7     2011   CLEMENT      4-RM         2400
town      quarter
CLEMENT   2011       2350.0
          2012       2275.0
CLEMENTI  2011       2312.5
Name: median_rent, dtype: float64


text:
Q: Does Java strictfp modifier have any effect on modern CPUs? I know the meaning of the strictfp modifier on methods (and on classes), according to the JLS:
JLS 8.4.3.5, strictfp methods:

The effect of the strictfp modifier is to make all float or double
  expressions within the method body be explicitly FP-strict (§15.4).

JLS 15.4 FP-strict expressions:

Within an FP-strict expression, all intermediate values must be
  elements of the float value set or the double value set, implying that
  the results of all FP-strict expressions must be those predicted by
  IEEE 754 arithmetic on operands represented using single and double
  formats.
Within an expression that is not FP-strict, some leeway is granted for
  an implementation to use an extended exponent range to represent
  intermediate results; the net effect, roughly speaking, is that a
  calculation might produce "the correct answer" in situations where
  exclusive use of the float value set or double value set might result
  in overflow or underflow.

I've been trying to come up with a way to get an actual difference between an expression in a strictfp method and one that is not strictfp. I've tried this on two laptops, one with a Intel Core i3 CPU and one with an Intel Core i7 CPU. And I can't get any difference.
A lot of posts suggest that native floating point, not using strictfp, could be using 80-bit floating point numbers, and have extra representable numbers below the smallest possible java double (closest to zero) or above the highest possible 64-bit java double.
I tried this code below with and without a strictfp modifier and it gives exactly the same results.
public static strictfp void withStrictFp() {
    double v = Double.MAX_VALUE;
    System.out.println(v * 1.0000001 / 1.0000001);
    v = Double.MIN_VALUE;
    System.out.println(v / 2 * 2);
}

Actually, I assume that any difference would only show up when the code is compiled to assembly so I am running it with the -Xcomp JVM argument. But no difference.
I found another post explaining how you can get the assembly code generated by HotSpot (OpenJDK documentation). I'm running my code with java -Xcomp -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly.
The first expression (v * 1.0000001 / 1.0000001) with the strictfp modifier, and also the same without it, is compiled to:
  0x000000010f10a0a9: movsd  -0xb1(%rip),%xmm0        # 0x000000010f10a000
                                                ;   {section_word}
  0x000000010f10a0b1: mulsd  -0xb1(%rip),%xmm0        # 0x000000010f10a008
                                                ;   {section_word}
  0x000000010f10a0b9: divsd  -0xb1(%rip),%xmm0        # 0x000000010f10a010
                                                ;   {section_word}

There is nothing in that code that truncates the result of each step to 64 bits like I had expected. Looking up the documentation of movsd, mulsd and divsd, they all mention that these (SSE) instructions operate on 64-bit floating point values, not 80-bit values as I expected. So it seems logical that the double value-set that these instructions operate on is already the IEEE 754 value set, so there would be no difference between having strictfp and not having it.
My questions are:

*

*Is this analysis correct? I don't use Intel assembly very often so I'm not confident of my conclusion.

*Is there any (other) modern CPU architecture (that has a JVM) for which there is a difference between operation with and without the strictfp modifier?

A: If by "modern" you mean processors supporting the sort of SSE2 instructions that you quote in your question as produced by your compiler (mulsd, …), then the answer is no, strictfp does not make a difference, because the instruction set does not allow to take advantage of the absence of strictfp. The available instructions are already optimal to compute to the precise specifications of strictfp. In other words, on that kind of modern CPU, you get strictfp semantics all the time for the same price.
If by "modern" you mean the historical 387 FPU, then it is possible to observe a difference if an intermediate computation would overflow or underflow in strictfp mode (the difference being that it may not overflow or, on underflow, keep more precision bits than expected).
A typical strictfp computation compiled for the 387 will look like the assembly in this answer, with well-placed multiplications by well-chosen powers of two to make underflow behave the same as in IEEE 754 binary64. A round-trip of the result through a 64-bit memory location then takes care of overflows.
The same computation compiled without strictfp would produce one 387 instruction per basic operation, for instance just the multiplication instruction fmulp for a source-level multiplication. (The 387 would have been configured to use the same significand width as binary64, 53 bits, at the beginning of the program.)


text:
Q: How to Convert Special character in URL format My Api does not accept special character it thoroughgoing error as access-controller allow origin does not accept
My File Name is Hello{#$^%.net}.pdf
My Url Format Like This
 http://localhost:5300/api/Insert/DeleteRec/1-1920-9/36/Hello%7B#$^%.net}/pdf

My Angular Code
fac.DeleteRecFromTemp = function (EnqId, UId, FileName,exten) {
        var fixedstring = decodeURIComponent(escape(FileName));
        return $http({
            url: hostapiUrl + 'Inser/DeleteRec/'+EnqId+"/"+UId+"/" +fixedstring+"/"+exten,
            method: "DELETE",
            headers: { 'content-type': 'application/json' }
        })
    }

Please Help me how can i convert that url into my browser url

A: Try this one:
url = encodeURI(url)


text:
Q: EEA Faceted Navigation - How to create a new widget in our own product I created a new widget 'Slider' for EEA Faceted Navigation.
It works fine but I made these changes directly in the original products.
For details, I added a new folder in eea/facetednavigation/widgets and modified eea/facetednavigation/widgets/configure.zcml.
I would like to move this new widget in my own product.
I've created some files and folder:

*

*my/product/widgets

*my/product/widgets/slider

*my/product/widgets/configure.zcml

and included my new package 'widgets' in the root zcml.
But it doesn't work:
Module eea.facetednavigation.browser.app.view, line 89, in get_sections
Module eea.facetednavigation.browser.app.view, line 96, in get_view_widgets
Module eea.facetednavigation.browser.app.view, line 111, in get_widgets
TypeError: 'NoneType' object is not callable

Is there a way to do this?

A: I'm looking at https://github.com/eea/eea.facetednavigation since I don't know what version you have.
It looks like that <facet:widget /> directive (I assume you have in your my/products/widgets/configure.zcml file) attaches the widget to the widget registry class. They register all of their widgets, then instantiate the registry as a utility.
So, try re-instantiating that class by adding an overrides.zcml to your product at
my/product/overrides.zcml
with the following
<configure
    xmlns="http://namespaces.zope.org/zope"
    xmlns:browser="http://namespaces.zope.org/browser">

  <configure package="eea.facetednavigation">
    <utility provides=".interfaces.IWidgetsInfo"
             factory=".widgets.WidgetsInfo" />
  </configure>

</configure>

A: You don't have to re-instantiate IWidgetsInfo :)
All you have to do is to register your widget:
<faceted:widget factory=".widget.Widget" />
See this faceted widget registered outside eea.facetednavigation namespace:

*

*https://svn.eionet.europa.eu/repositories/Zope/trunk/eea.dataservice/trunk/eea/dataservice/facetednavigation/lastversion/configure.zcml

*https://svn.eionet.europa.eu/repositories/Zope/trunk/eea.dataservice/trunk/eea/dataservice/facetednavigation/lastversion/


text:
Q: Check if user said ok to beforeunload? I want to run an AJAX script when a user says "Ok" to a "beforeunload" event. Now I mean beforeunload, and not onbeforeunload (the latter doesn't work for some reason).
Is there any way to do this?

A: Just listen to the unload event, which will occur after beforeunload if the user proceeded. However, at this point the UI will not be visible to the user anymore and nothing can stop the unloading process. Perhaps you will be able to make your AJAX call, but I'm not sure if callbacks will be executed and/or if it's reliable.

A: You can try to listen to the unload event, but you will probably not be able to complete any AJAX request there.  For security reasons, the browser will abort it.


text:
Q: React/Redux project giving me the error 'Failed to compile. Module build failed: Error: ENOENT: no such file or directory'' This is the component triggering the error:
TodoList.js
import React from 'react';
import Task from './Task';

const TodoList = (props) => {
  const tasks = props.tasks.map((task, i) => <Task task={task} key={i} index={i} />);
  return (
    <ul>
      { tasks }
    </ul>
  );
};

export default TodoList;

What's incorrect in how I'm exporting the component that would cause it to not be found when compiling?

A: import Task from './Task';

try
import Task from './Task.js';

Or
import Task from './Task.jsx';

if using jsx files


text:
Q: Why is the label color not turning green when the radio is checked? I'm having some problems with changing the color of the label when the radio input is checked.
When I use this:
input:checked + label {
color: green}

Then normally it works, but not on this little project.
Can someone please explain it to me why it is not working. I think it has something to do with the usage of SASS. It always works when I'm using plain CSS.
Github repository: https://github.com/Nova988/Tip-calculator-App
Netlify Site: https://priceless-hodgkin-c38abb.netlify.app/

A: Take a look at the HTML.
The label comes before the input radio button - which you can also see just looking at the page - the circle (radio button) is after the % label.
Your CSS relies on the label coming after the input.


text:
Q: Ionic Cordova app links + camera plugin intent issue in Android Ionic 4.11.0
Cordova 8.1.2
Android platform: 8.0.0
I am building an Ionic/Cordova app that makes use of an external authentification mobile app ("Itsme") and I have an issue running it with Android.
From my app, I open the authentification app with an app link. The authentification app then redirects to my app also using an app link, but when it does, my app is actually restarted twice as I can see from the logs in the console.
Furthermore, when I keep using the latest instance of my app that is generated, and I try to use the camera plugin (which is start through an Intent) I can never get the picture back. The return of the plugin switches back to the home Android screen, my app remains in the background, and I don't get any result if I make it come back to the foreground.
I have tested using many different flags in the definition of the app link to my own app (singleTask, singleTop, ...) to no avail.
Using a test native app, I have determined that the flags sent by the authentication app when redirecting to mine with a VIEW intent are the following:

*

*FLAG_ACTIVITY_CLEAR_TASK

*FLAG_ACTIVITY_NO_HISTORY

*SCROLLBARS_OUTSIDE_INSET
Any ideas or pointers how to figure out what is exactly going on ?


text:
Q: Extracting and sorting data from a binary file So I just started a programming course in python and I have this assignment called 'Wind data analysis' in which I am to extract data from a bin.file and sort it into  x,y and z values. So far I got:
filename="turb21351_L72u.bin"
with open(filename,'br') as f:

buffer = f.read(100000)
print("Length of buffer is %d" % len(buffer))

for i in buffer:
    print(int(i))

Which works fine (note; there are some indentation error on the script i wrote here) and gives me value in the range 1 to 300.
The problem is sorting the data. The description of the assignment sounds like this:
"The data file consists of Nz X Ny X Nx numbers (floating point single precision). The sequence of the numbers corresponds to indexes
z, y and x which all increase sequentially from 1 to Nz, Ny and Nx respectively. The fastest-varying index is z, followed by y, and the slowest varying index is x. That is,
the first Nz numbers from the sequence correspond to indexes z going from 1 to Nz, y = 1, and x = 1. Based on this ordering rule, the function must convert the data to a three-dimensional array with dimensions Nz X Ny X Nx."
My question is:
How is the assigniment description to be understood mathmathtically and how would one go about sorting it based on the ordering rule?

A: Can you try with the following code:
filename="turb21351_L72u.bin"
with open(filename,'br') as f:
    buffer = f.read(100000)
print("Length of buffer is %d" % len(buffer))

for i in buffer:
    print(int(i))

In python the with keyword is used when working with unmanaged resources (like file streams). The with statement works like a block statement, where it needs indentation.
From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I'll discuss the statement as it will commonly be used. In the next section, I'll examine the implementation details and show how to write objects for use with this statement.
The with statement is a control-flow structure whose basic structure is:
with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).


text:
Q: .toggleClass not toggling a certain class, but is working on all others So I have a page on my website that has some navigation elements that stick on the page when the user scrolls past a certain point. There are three of them, one on the top, one on the left, and one on the right. HTML and CSS is as follows:

.nav {
    position: absolute;
    top: 108px;
    height: 45px;
    width: 100%;
    left: 0;
    right: 0;
}

.nav_sticky {
    position: fixed;
    top: 0;
    height: 45px;
    left: 0;
    right: 0;
    background-image: url(images/backgrounds/stardust_@2X.png);
    z-index: 10;
}

.right {
    width: 200px;
    height: 900px;
    position: absolute;
    right: 50%;
    margin-right: -538px;
    top: 153px;
}

.right_sticky {
    width: 200px;
    height: 900px;
    position: fixed;
    right: 50%;
    margin-right: -538px;
    top: 45px;
}

.left {
    width: 200px;
    height: 900px;
    position: absolute;
    left: 50%;
    margin-left: -538px;
    top: 153px;
}

.left_stick {
    width: 200px;
    height: 900px;
    position: fixed;
    left: 50%;
    margin-left: -538px;
    top: 45px;
}

I then use the follow JQuery to cause these elements to stick.

Here's my problem. This works perfectly for the top and right navs, however no matter what I try, the left nav continues to scroll when the others have stopped. I thought it may have been a typo in the css class, but when I looked in the inspector, the .toggleClass function doesn't even change the class on the #left element when it does on the other two. Any ideas as to what could be causing this?

A: If I copy/paste your sample code as-is to jsFiddle and run it, when you scroll down far enough, it does correctly toggle everything to *_sticky classes, but something about the negative margin-right on the right class element seems to reset the scroll to the top (at least in Chrome) when it flips between .right and .right-stick. When the scroll gets reset, it also reruns your event handeler and changes all the classes back.
Try removing these lines from your CSS and see if the behavior works right (it does in Chrome in a jsFiddle)
.right {
    ...
    /*margin-right: -538px;*/

.right-stick {
    ...
    /*margin-right: -538px;*/


text:
Q: OpenSSL PositiveSSL certificate untrusted connection I bought a SSL certificate and I cannot get it to function. I get a This Connection is Untrusted error in Firefox.
I do believe it's due to my .crt file being incomplete/wrong all together. My .crt was generated using:
 openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

What I get is a big block of data. It has a begin header and a end. The reason for thinking it's incorrect is due to the example files I've browsed. Example 1, Example 2. These have a lot more information than the chunk of data that I have in my file.
Am I experiencing the issue due to my .crt file? What else could cause the error. I've tried my very best to find some answers but the answers I've found have always been not applicable or irrelevant to my issue. I have enabled SSLEngine in my .conf file and the ssl mod is enabled.
I am completely new to installing SSL certificates and I've never attempted anything like this before, just so you know.
I run on Ubuntu 14.04 64-bit on a VPS. The certificate is active and was purchased from PositiveSSL via Namecheap as I purchased my domain.

A: That's not how this works.
You created a self signed certificate, of course no browser will trust it.
You bought a certificate, which means you should have been sent a .crt file by your provider.
The process should be something like this.
Generate a private key:
openssl genrsa -out domain.com.key 2048

Create a CSR:
openssl req -new -sha256 -key domain.com.key -out domain.com.csr

Then take the domain.com.csr file, send it to your provider.
Wait until they have done their magic (also known as "charged your credit card") and receive a .crt file from them.
Install that file on your server.


text:
Q: Changing date formats with python from one to another I have a series of tables that I am using to create a map in ArcGIS desktop. In the attribute table there is a date column in the format "19950129000000" and I would like to convert this format to something more meaningful such as "29/1/1995". The column says it is in a string format, but the metadata says it is in a date format.
I have done something similar before but I am having trouble getting it to work.
I've tried:
def dtConversion(date):
  from datetime import datetime
  od = datetime.strptime(date, "YYYYMMddhhmmss")
  nd = datetime.strftime(od, "%d/%m/%Y")
  return nd
esri_field_calculator_splitter
dtConversion(!CMPLDT!)

A: datetime.strptime('19950129000000', "%Y%m%d%H%M%S")


text:
Q: Find & Run program.exe and add "/repair" to line. (BatchFile) So the aim is to :
1) find the steam.exe on the C drive. (This part is working fine)
2) run steam.exe with the "/repair" on the end.
for /f "delims=" %%i in ('dir /b /a-d /s c:\steam.exe') do "%%~fi **/repair**"
pause
exit

This attempt returns "The directory name is invalid" So where am I going wrong?

A: ... do "%%~fi /repair"

tries to start a program named "...\steam.exe /repair" Surely, you want to start the program "...\steam.exe" with the parameter /repair (last qoute at the wrong place), so it should be:
... do "%%~fi" /repair


text:
Q: Transfering Javascript code from global variables to classes I'm trying to transfer my Javascript code from global variables to classes, but I got stuck with transferring data between classes. Here is the example of my old code which uses global variables.
var globalVar;

    function getDataFromServer () {
      const json = await sendToServer(data); // in sendToServer func I receive a large amount of data via json from server
      if (json) {
        globalVar = json;
        useGlobalData();
      }
    }

    function useGlobalData () {
      var_dump (globalVar);
      // here I can do something with globalVar
    }

getDataFromServer();

And here is the same code which I'm trying to implement in classes without using global variables and I got stuck here...
class getDataFromServer {
  serverData;

  constructor () {
          const json = await sendToServer(data); // in sendToServer func I receive a large amount of data via json from server. This data is constant and will not be changed in the future.
          if (json) {
            this.serverData = json;
            let newClass = new useGlobalData ();

          }
  }
}

class useGlobalData {
  constructor () {
    // In this class I need to use serverData data from getDataFromServer class, but I don't want to receive it again (twice) from webserver
  }
}

var serverData = new getDataFromServer ();


text:
Q: Deci to Hexa conversion in Assembly code issue I have here an assembly program that has to convert a decimal number to hexadecimal equivalent..I tested it with a number (123) and it displays right. But when I change it to (1234) it displays D2 instead of 4D2(the real equivalent.) Would you please help me to resolve this. I hope you could modify it for me to understand it more. Thanks a lot. Here's the code:
.model small
.stack 90h

.data
   counter db 0
   curValue db 0
   prevValue db 0
   hexa db 0
   msg db "Enter a decimal number: $"
   hexmsg db 13,10,"In hexadecimal: $"

.code
    mov ax, @data           ;initialize DS
    mov ds, ax

                            ;load and display the string msg
    mov ah, 09h
    lea dx, msg
    int 21h

accept:
    mov ah, 01
    int 21h                 ;read a digit

    cmp al, 13              ;compare al with 13
    je hexAccept            ;jump to label exit if input is 13

    sub al, 48              ;subract al with 48
    mov curValue, al        ;move al to curValue

    cmp counter, 1          ;compare counter with 1
    jl inc_ctr              ;jump to label inc_ctr if al<1

    mov al, prevValue       ;move prevValue to al
    mov bl, 10
    mul bl

    add al, curValue        ;add curValue to al

    mov prevValue, al       ;move al tp prevValue

    inc counter             ;inc_ctr counter
    jmp accept              ;jump to label accept

inc_ctr:
    mov prevValue, al       ;move al to prevValue

    inc counter             ;inc_ctr counter
    jmp accept              ;jump to label accept

hexAccept:
    mov bl,prevValue        ;move prevValue to bl
    mov hexa, bl            ;move bl to hexa
    mov bl, 0               ;move 0 to bl

    mov ah, 09h             ;load and display the string hexmsg
    lea dx, hexmsg
    int 21h

    mov bl,hexa             ;move hexa to bl
    ;mov octal, bl          ;move bl to octal
     xor bx, bx             ;clear bx

    mov bh, 240             ;move 240 to bh
    and bh, hexa            ;multiply hexa with bh
    mov bl, 15              ;move 15 to bl
    and bl, hexa            ;multiply hexa with bl

    mov cl, 4               ;move 4 to cl
    rol bh, cl              ;rotate bh 4x

    cmp bh, 9               ;compare bh with 9
    jg Letters              ;jump to Letters if bh>9
    add bh, 48              ;add 48 to bh
    mov ah, 02h             ;set the output function
    mov dl, bh              ;move bh to dl
    int 21h                 ;print the character
    jmp Second_digit        ;jump to Second_digit

Letters:
    add bh, 55              ;add 55 to bh

    mov ah, 02h             ;set the output function
    mov dl, bh              ;move bh to dl
    int 21h                 ;print the character

Second_digit:
    cmp bl, 9               ;compare bl with 9
    jg dispSecond_digit       ;jump to dispSecond_digit if bl>9
    add bl, 48              ;add 48 to bl
    mov ah, 02h             ;set the outputfunction
    mov dl, bl              ;move bl to dl
    int 21h                 ;print the character
    jmp terminate           ;jump to convertTooctall

dispSecond_digit:
    add bl, 55              ;add 55 ot bl
    mov ah, 02h             ;set the output function
    mov dl, bl              ;move bl to dl
    int 21h                 ;print the character

terminate:

    mov ah, 04ch            ;return control to DOS
    int 21h


text:
Q: NIntegrate::inumr: error I'm new to Mathematica and I keep getting this error(in the title) when I'm trying to solve this definite integral numerically.  This is for a math class where we have to use the arc length.
f[x_] := 6 x[1 - x]
NIntegrate[Sqrt[1. + f'[x]^2], {x, 0., 1.}]

Any help would be appreciated.  I've googled several times and while a lot of people are getting the same error, their solutions/problems aren't really the same as mine.  My instructor showed us this exact syntax I am pretty sure and he was getting the correct answer.
The error is

NIntegrate::inumr: The integrand Sqrt[1. +36 (1[1+Times[<<2>>]]-(x^[Prime])[Plus[<<2>>]])^2] has evaluated to non-numerical values for all sampling points in the region with boundaries {{0.,1.}}.

EDIT:  Thank you.  I thought it was brackets for some reason.

A: f[x_] := 6 x[1 - x]

This is a mistake!
The right definition of a function is:
f[x_]:=6x(1-x)

Please  remember: [] is a function flag. () is grouping the terms of a expression.


text:
Q: Importerror: DLL load failed while importing ie_api I'm using python==3.8 anaconda environment. I'm getting the error DLL load failed while importing ie_api.
Dose python 3.8 support OpenVino?

A: OpenVINO toolkit supports Python 3.6-3.9 (64-bit) version, as mentioned in the software System Requirements.
The error is due to OpenVINO environment not being configured. If you installed OpenVINO from the installer, you need to call the Setupvars.bat script to initialize the OpenVINO environment. The script can be found in openvino/bin directory.
For OpenVINO installed from PyPi repository, you need to add your PYTHON PATH into your environment variables. In your case, add path of your Anaconda installation into the environment variables as below:


text:
Q: How to customise quick launch/left hand links on a subsite? I am using SharePoint 2013 and I have create an enterprise wiki site as a subsite. I would like to edit the navigation links on the left hand side bar (aka quick launch) but I read that subsites will not have the "edit link" button for customization.
I have tried changing the settings under "site settings > navigation", but nothing changed.
This is what I'm seeing on my subsite

This is the "edit links" button I am referring to in the master site

If possible, I do not wish to go into codes editing. Please assist! Thanks!

A: Go to Site Settings >> Under Look and Feel click Navigation >> Under Structural Navigation: Sorting

Here you can change your Current and Global navigation settings.
Reference:

*

*http://www.learningsharepoint.com/2012/11/22/sharepoint-2013-addedit-links-in-quick-launch-or-left-navigation/

*https://support.office.com/en-us/article/Configure-the-Quick-Launch-for-site-navigation-d3288963-4a91-4470-9192-610952daecdf


text:
Q: Arithmetic progressions without small primes The following question came up in the discussion at How small can a group with an n-dimensional irreducible complex representation be? :
Is it known that there are infinitely many primes p for which the least prime q which is 1 mod p is > c p^2 (for some positive constant c, independent of p)?
Wikipedia's article on primes in arithmetic progressions says that the expected bound for the least prime is p^{2 + \epsilon}, given various strengthenings of the Riemann Hypothesis, but it doesn't say much about lower bounds.
By the way, for the applications in the linked post, it would be even better if the same lower bound applied to finding a prime power q which is 1 mod p.

A: I don't have a reference for you, but what GRH proves has nothing to do with the truth; the proof is "lossy." The expected answer would be p^{1+\epsilon} for the smallest prime congruent to 1 mod p: an integer around N is prime with probability 1/log(N), and in most regimes (although not all) this makes accurate predictions.

A: I don't know a definite answer either way, but here's one line of questioning: I believe it is a known result that Linnik's constant is at least 2 (although it's less for almost all integers.) Do the methods used to prove that fail to distinguish between primes and composites, or between some set in which the primes have positive density and some set in which they don't?
From the other direction, however, it's apparently possible on GRH to bound the error term in the PNT in arithmetic progressions (as in Brun-Titchmarsh, although I don't think they're that tight) when N > q^{2+\epsilon}. This would put some rather tricky constraints on the error term, which one could take as evidence against it.
By the way, do you have a heuristic argument that, for instance, there are infinitely many primes for which the least prime congruent to 1 mod p is at least c p^(2-\epsilon)? Or even at least c p^e for some e > 1?

A: For a fixed a>0 it is known that there are infinitely many moduli q such that the least prime in the arithmetic progresion a mod q is at least >> q ln (q) lnln (q) ln ln ln ln (q) / (ln ln ln(q) )^2. This can be found in:
Prachar, K. Über die kleinste Primzahl einer arithmetischen Reihe. (German) J. Reine Angew. Math. 206 1961.
To the best of my knowledge this is the world record.

A: It is firmly expected that for every \epsilon > 0 each aritmetic progression with difference q and terms coprime with q will contain a prime <<{\epsilon} q^{1 + \epsilon}.
This is a direct consequence of a conjecture of H. L. Montgomery (not the one on pair correlations, another one), which implies both the GRH and the Elliott-Halberstam conjecture. But the upper bound $\ll {\epsilon} q^{1 + \epsilon}$ for the least prime in an arithmetic progression was conjectured by S. Chowla (in his book "The Riemann Hypothesis and Hilbert's tenth problem"), and probably by others independently of him, years before Montgomery made his conjecture, and presumably on the basis of the same kind of heuristic argument that moonface advances. In fact, I think that even an upper bound as strong as qlog(q)^2 has been conjectured, though I won't swear to that. But it is definitely known that qlog(q) won't work. The Montgomery conjecture seems reasonable, because it rests on the assumption that there is square root cancellation in a certain sum with D-characters as coefficients in an explicit formula - this ties in with moonface's comment about the proof that GRH implies L \leq 2 being "lossy". On the other hand, one cannot expect to get q^{1 + \epsilon} out of the Elliott-Halberstam conjecture in any direct way, because that is an averaging kind of statement. You would not expect to get L \leq 2 out of the Bombieri-A. I. Vinogradov theorem either, for that is an averaged version of GRH. The point is that information is needed about every single one of the arithmetic progressions individually.


text:
Q: Understanding Spring Webflux/Reactive endpoints I'm trying to make sense of reactive endpoints in Spring, and this is confusing me.
// in a @RestController
@GetMapping("/someendpoint")
fun someEndpoint(): ResponseEntity<Mono<Map<String, Any>>> {
    return ResponseEntity(Mono.zip(
        Mono.fromRunnable<List<SomeItem>> { someApiCall() },
        Mono.fromRunnable<List<SomeOtherItem>> { someOtherApiCall() },
    ).map { tuple ->
        val someItems = tuple.t1
        val someOtherItems = tuple.t2
        mapOf(
            "someItems" to someItems,
            "someOtherItems" to someOtherItems
        )
    }, HttpStatus.OK)
}

I have an endpoint that returns a Mono of a Map, the idea being just to render some arbitrary JSON.
As part of the request, I do a Mono.zip(Mono.fromRunnable { ... }) where I call API's for data.
After the zip, I do a .map over the results and ultimately return the Map that I expect to see rendered.
When I hit the endpoint, no JSON is rendered, but the runnables in the zip are called and the response time takes those API calls into account. The .map after the .zip is never called. I'm probably just not understanding something simple here--like the .map is not subscribed to?
What is going on here and what is the usual way to handle a situation like this using Webflux/Reactor?

A: As Rene mentioned in the comment, my mistake was using Mono.fromRunnable {} instead of Mono.fromSupplier {}


text:
Q: Given an odd prime $p$, is there another odd prime $q$ such that $p$ is a primitive root modulo all powers of $q$? As the title says, I want to know if for every odd prime $p$, there is another odd prime $q$ such that $p$ is a primitive root modulo $q^m$ for all $m\ge1$. For small $p$ such as $p=3,5,7$, I could check explicitly that $q=5,7,11$, respectively, do the job by showing that $p$ is a primitive root modulo $q$ and $p^{q-1} \not\equiv 1 \mod q^2$. But I am not sure how to show that such a $q$ exists for all $p$. I would appreciate any ideas on how to proceed.
A related question has been asked before: Is every non-square integer a primitive root modulo some odd prime?, but the answers there don't address my question.
Also related is Artin's conjecture on primitive roots, but it asks for infinitely many prime $q$ such that $p$ is a primitive root modulo $q$ rather than a single odd prime $q$ such that $p$ is a primitive root modulo all powers of $q$.


text:
Q: Python read CSV file issue when the delimiter symbol itself is in the item I'm trying to read a txt file (comma delimiter) into a CSV using csv.reader(). But because my delimiter (,) is sometimes inside the object/item the whole 'row' of read items get's shifted.
Example:
input.txt:
Stevenson Corp, 123 Main St, 3 employees\n
Johnson Inc, 456 Main St, 5 employees\n

would result in CSV columnized as:
Stevenson Corp | 123 Main St | 3 employees
Jonson Inc | 456 Main St | 5 employees

However, the issue arises if I have my input.txt file has (,) inside the items being delimitered, example:
input_bad.txt:
Stevenson Corp, 123 Main St, 3 employees\n
Johnson, Inc, 456 Main St, 5 employees\n #notice the comma before Inc

would result in in an incorrect CSV columnized as:
Stevenson Corp | 123 Main St | 3 employees #3 columns
Jonson | Inc | 456 Main St | 5 employees #4 columns (issue)

I can't think of any solution to keep the Jonson, Inc together not split by the "," delimiter.
My code opens the txt file and csv as such:
inputfile = open(os.path.join(somelocation, somefile.txt), "r", encoding="utf-8", errors="replace")

csv_data = csv.reader(inputfile, delimiter = ",")

Please help.

A: Best approach would be to go back and change the delimiter in your file from , to something more sensible but if that's not an option so you can do something like this as a workaround:
import csv
with open(os.path.join(somelocation, somefile.txt), "r", encoding="utf-8", errors="replace") as inputfile:
    spamreader = csv.reader(inputfile, delimiter='¬')
    for row in spamreader:
        new_row = row.rsplit(",", 2)
        print("|".join(new_row))

This uses a delimer not seen in your text so doesn't split any lines (so you could do the reading with inputfile.readlines() instead), then it uses rsplit to split on the two rightmost commas to create the columns


text:
Q: How to unset certain values submitted from dynamic form? I have a dynamic form that uses variable variables and it works well, but I came to an issue where some POST values must be removed once they are processed by the form's submission.
Due to the nature of variable variables and this dynamic form's programming that builds INSERT and UPDATE queries dynamically, I need to remove these values from the $_POST once they've been processed into a single variable.
The partial form processing section is in a foreach loop and contains:
$Fields = array();
$Values = array();
foreach ($_POST as $key=>$value ) :
    if (Contains("month", $key)) unset($_POST);
    if (Contains("day", $key)) unset($_POST);
    if (Contains("year", $key)) unset($_POST);
    if (Contains("hour", $key)) unset($_POST);
    if (Contains("minute", $key)) unset($_POST);
    if (Contains("second", $key)) unset($_POST);
    $Fields[] = "`$key`";
    $Values[] = isNull($value, $DBName);
endforeach;

$sqlInsert = "INSERT INTO $TableName (".implode(",",$Fields).") VALUES (".implode(",",$Values).")";

The Contains() function has:
function Contains($searchWord, $fromString) {
    if (is_array($fromString)) :
        reset($fromString);
        $key = key($fromString);
        return strpos($key, $searchWord) !== FALSE;
    else:
        return strpos($fromString, $searchWord) !== FALSE;
    endif;
}

I tried everything I can think of including:
foreach ($_POST as $key=>$value ) :
    if (Contains("month", $key)) unset($_POST[$key]);
    if (Contains("day", $key)) unset($_POST[$key]);
    if (Contains("year", $key)) unset($_POST[$key]);
    if (Contains("hour", $key)) unset($_POST[$key]);
    if (Contains("minute", $key)) unset($_POST[$key]);
    if (Contains("second", $key)) unset($_POST[$key]);
endforeach;

as $key should contain the name of the POST field that I am trying to unset() but they do not unset. Any ideas?

A: No sooner did I rewrite and simplify my original question when doing so gave me an idea that seems to have done the trick. Rather than using unset, I used continue:
if (Contains("month", $key)) continue;
if (Contains("day", $key)) continue;
if (Contains("year", $key)) continue;
if (Contains("hour", $key)) continue;
if (Contains("minute", $key)) continue;
if (Contains("second", $key)) continue;


text:
Q: Moving labels for chemfigs How do I modify or adjust the vertical and horizontal alignment of the labels? If I add spaces before or after the desired label, I can make a horizontal adjustment. But, I can't figure out the vertical adjustment. Is there a way? Please let me know and thank you.
\usepackage{chemfig,chemmacros}
\chemsetup{modules=all}
\begin{document}
\chemname{\setbondoffset{0pt}
  \chemsetup[orbital]{
    overlay ,
    opacity = .75 ,
    s/color = blue!50 ,
    s/scale = 1.6
  }
  \chemfig{
    {\orbital{s}}
    -[:30]
    (-[:-30]\orbital{s})
}}{ $A_1$} \hspace{1cm} \chemname{\setbondoffset{0pt}
  \chemsetup[orbital]{
    overlay ,
    opacity = .75 ,
    p/color = blue!50,
    p/scale = 1.3 ,
    s/color = blue!50 ,
    s/scale = 1.6
  }
  \chemfig{
    {\orbital[phase=-]{s}}
    -[:30]
    (-[:-30]\orbital{s})
}}{$B_2$ too long of a name interfere with image}

\end{document}

Furthermore, is there a way to center the said label relative to the image? And is there a way to align the left most image on the second row with the others?

\usepackage{chemfig,chemmacros}
\chemsetup{modules=all}
\begin{document}

\noindent Matching the above orbitals with the valence orbitals from C, we obtain the following series of ``molecular" orbitals:

\[\chemname[0.5cm]{\setbondoffset{0pt}
  \chemsetup[orbital]{
    overlay ,
    opacity = .75 ,
    s/color = blue!50 ,
    s/scale = 1.6
  }
  \chemfig{
    {\orbital{s}}
    -[:30]
           {\orbital[scale=2]{s}}
    (-[:-30]\orbital{s})
}}{$a_1$} \hspace{2cm} \chemname[0.5cm]{\setbondoffset{0pt}
  \chemsetup[orbital]{
    overlay ,
    opacity = .75 ,
    p/color = blue!50,
    p/scale = 1.2 ,
    s/color = blue!50 ,
    s/scale = 1.6
  }
  \chemfig{
    {\orbital[phase=-]{s}}
    -[:30]
           {\orbital[angle=180,phase=-]{p}}
    (-[:-30]\orbital{s})
}}{$b_1$} \hspace{2cm} \chemname[0.5cm]{\setbondoffset{0pt}
  \chemsetup[orbital]{
    overlay ,
    opacity = .75 ,
    p/color = blue!50,
    p/scale = 1.3 ,
    s/color = blue!50 ,
    s/scale = 1.6
  }
  \chemfig{
    {\orbital{s}}
    -[:30]
           {\orbital[angle=90,phase=-,scale=1.2]{p}}
    (-[:-30]\orbital{s})
}}{$a_1$}\]

\vspace{2cm}

\[\chemname[0.5cm]{\setbondoffset{0pt}
  \chemsetup[orbital]{
    overlay ,
    opacity = .75 ,
    p/color = blue!50,
    p/scale = 1.2 ,
    s/color = blue!50 ,
    s/scale = 1.6
  }
  \chemfig{
    -[:-20]{\orbital[angle=90]{p}}
    (-[:-150])
}}{$b_2$} \hspace{2cm} \chemname[0.5cm]{\setbondoffset{0pt}
  \chemsetup[orbital]{
    overlay ,
    opacity = .75 ,
    p/color = blue!50,
    p/scale = 1.2 ,
    s/color = blue!50 ,
    s/scale = 1.6
  }
  \chemfig{
    {\orbital{s}}
    -[:30]
           {\orbital[angle=90]{p}}
    (-[:-30]\orbital{s})
}}{$a_1$} \hspace{2cm} \chemname[0.5cm]{\setbondoffset{0pt}
  \chemsetup[orbital]{
    overlay ,
    opacity = .75 ,
    p/color = blue!50,
    p/scale = 1.2 ,
    s/color = blue!50 ,
    s/scale = 1.6
  }
  \chemfig{
    {\orbital[phase=-]{s}}
    -[:30]
           {\orbital[angle=180]{p}}
    (-[:-30]\orbital{s})
}}{$b_1$}\]
\end{document}

A: The vertical alignment of different chemfigs depends on the point from where you start to draw your molecules. This point is taken as the baseline to which the molecules are aligned. In your case you can fix the alignment by using the lower instead of the upper CH3 group as the starting point:
\documentclass{article}
\usepackage{chemfig,chemmacros}
\chemsetup{modules=all}
\newcolumntype{C}[1]{>{\centering\arraybackslash}m{#1}}

\begin{document}

\noindent Matching the above orbitals with the valence orbitals from C, we obtain the following series of ``molecular" orbitals. Please note that I have used the `\chemsetup` command before the first `\chemname` command. This way you only need it once.

\chemsetup[orbital]{
    overlay ,
    opacity = .75 ,
    p/color = blue!50,
    p/scale = 1.2 ,
    s/color = blue!50 ,
    s/scale = 1.6
  }
\setbondoffset{0pt}
\vspace{2cm}
\chemname[0.5cm]{
  \chemfig{
    -[:30]{\orbital[angle=90]{p}}
    (-[:150])
}}{$b_2$} \hspace{2cm} \chemname[0.5cm]{
  \chemfig{
    {\orbital{s}}
    -[:30]
           {\orbital[angle=90]{p}}
    (-[:-30]\orbital{s})
}}{$a_1$} \hspace{2cm}
\chemname[0.5cm]{
  \chemfig{
    {\orbital[phase=-]{s}}
    -[:30]
           {\orbital[angle=180]{p}}
    (-[:-30]\orbital{s})
}}{$b_1$}
\end{document}

However, the texts are stil not really horizontally centered under their corresponding images. I would therefor suggest to use a table in oder to allow for preciser control of the positioning of images and figures:
\documentclass{article}
\usepackage{chemfig,chemmacros}
\chemsetup{modules=all}
\newcolumntype{C}[1]{>{\centering\arraybackslash}m{#1}}

\begin{document}

\noindent Matching the above orbitals with the valence orbitals from C, we obtain the following series of ``molecular" orbitals:

\setbondoffset{0pt}
\noindent\begin{tabular}{*{3}{C{0.333\textwidth-2\tabcolsep}}}
  \\[0.5cm]
  \chemfig{
    {\orbital{s}}
    -[:30]
           {\orbital[scale=2]{s}}
    (-[:-30]\orbital{s})
} &
  \chemfig{
    {\orbital[phase=-]{s}}
    -[:30]
           {\orbital[angle=180,phase=-]{p}}
    (-[:-30]\orbital{s})
} &
  \chemfig{
    {\orbital{s}}
    -[:30]
           {\orbital[angle=90,phase=-,scale=1.2]{p}}
    (-[:-30]\orbital{s})
} \\[0.5cm]
$a_1$ & $b_1$ & $a_1$ \\[1cm]
  \chemfig{
    -[:30]{\orbital[angle=90]{p}}
    (-[:150])
} &
  \chemfig{
    {\orbital{s}}
    -[:30]
           {\orbital[angle=90]{p}}
    (-[:-30]\orbital{s})
} &
  \chemfig{
    {\orbital[phase=-]{s}}
    -[:30]
           {\orbital[angle=180]{p}}
    (-[:-30]\orbital{s})
}\\[0.5cm]
$b_2$ & $a_1$ & $b_1$ \\[1cm]
\end{tabular}
\end{document}


text:
Q: Scrapy callback problem: to scrape the follow-up page of an item I need this item's (auto_increment) ID in the database I'm trying to do the following:

*

*scrape some items (which include URLs) from some page.

*save each item to a mysql database

*get the (auto_increment) ID of the previously added record

*scrape the page pointed to by the URL above (#1)

*save all items on this page with a reference (foreign key) to the ID defined in #3

That looks to me like a very common problem which should have a reasonably simple solution.
The "item_scraped" signal looked like the obvious solution since it provides a callback for when an item has been fully processed.
However, it appears that it's impossible to start another Request from within the callback.
I read here that some people suggested using Spider Middlewares but I don't see how, especially since Spider Middlewares are not supposed to start Requests themselves.
I'm using Scrapy 2.6.2 on Python 3.8.
Thanks for your help.
My simplified code below, without error processing etc.
The spider
import scrapy
from scrapy import signals

class MySpider(scrapy.Spider):
    name = 'MySpider'
    allowed_domains = ['www.somedomain.com']
    start_urls = [
        'https://www.somedomain.com/someurl/',
        ]

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        spider = cls()
        # requests the callback once an item is scraped
        crawler.signals.connect(spider.item_scraped, signals.item_scraped)
        return spider

    def parse(self, response):
        for node in response.xpath(".//tr/td[@class='foo']"):
            yield {
                'a': ...
                'b': ...
                'url': ...
            }

    def item_scraped(self, item, response, spider):
###
### UNFORTUNATELY THIS IS NOT POSSIBLE
###
        # forwards the new ID as a meta variable
        yield Request(item['url'], meta={'id':item['id']}, callback=self.parse_page)

    def parse_page(self, response):
        for node in response.xpath("//div[@class='soemthing']//a"):
            yield {
                'id': response.meta['id'],
                'title': ...
            }

And the pipeline:
import mysql.connector

class WinebotPipeline(object):

    def __init__(self):
        self.conf = {'host': ..., 'user': ..., 'password': ..., 'database': ...}
        self.connection = self.mysql_connect()
        self.cursor = self.connection.cursor()

    def mysql_connect(self):
        return mysql.connector.connect(**self.conf)

    def process_item(self, item, spider):
        sql = "insert into `some_table` (`a`, `b`, `url`) values (%s, %s, %s)"
        self.cursor.execute(sql, list(item.values()))
        self.connection.commit()

        # id of last inserted item
        item['id'] = self.cursor.lastrowid
        return item

A: An easier way of doing this would be to get all of the info from the first page then use the url to yield a new request with your parse_page method as the callback and the scraped data as the callback kwargs.  Then once you have scraped the necessary info from the second url you can add it to the results from the first page and yield the completed item.  Then you can do all of your database entries all at once.
Spider
import scrapy
from scrapy import signals

class MySpider(scrapy.Spider):
    name = 'MySpider'
    allowed_domains = ['www.somedomain.com']
    start_urls = [
        'https://www.somedomain.com/someurl/',
        ]

    def parse(self, response):
        for node in response.xpath(".//tr/td[@class='foo']"):
            cb_kwargs = {'a': ..., 'b': ...,   'url': ...}
            yield scrapy.Request(cb_kwargs['url'],
                                 callback=self.parse_page,
                                 cb_kwargs=cb_kwargs)

    def parse_page(self, response, **kwargs):
        for node in response.xpath("//div[@class='soemthing']//a"):
            kwargs.update({'title': ...})
            yield kwargs

Pipeline
import mysql.connector

class WinebotPipeline(object):

    def __init__(self):
        self.conf = {'host': ..., 'user': ..., 'password': ..., 'database': ...}
        self.connection = self.mysql_connect()
        self.cursor = self.connection.cursor()

    def mysql_connect(self):
        return mysql.connector.connect(**self.conf)

    def process_item(self, item, spider):
        sql = "insert into `some_table` (`a`, `b`, `url`, 'title') values (%s, %s, %s, %s)"
        self.cursor.execute(sql, list(item.values()))
        self.connection.commit()
        return item


text:
Q: How to create all tables defined in models using peewee I define a lot of model classes using peewee. ClassName.create_table() can generate the table,but only one table. How could I create all tables using a single statement?

A: This snipnet will create all tables which objects are defined in the current module:
import sys

for cls in sys.modules[__name__].__dict__.values():
    try:
        if BaseModel in cls.__bases__:
            cls.create_table()
    except:
        pass

A: for cls in globals().values():
    if type(cls) == peewee.BaseModel:
        try:
            cls.create_table()
        except peewee.OperationalError as e:
            print(e)

A: Peewee has a helper that will create the tables in the correct order, but you still need to explicitly pass in all the models:
from peewee import *
db = SqliteDatabase(':memory:')
db.create_tables([ModelA, ModelB, ModelC])

A: An update for Python 3 (and everyone who comes across this question via Google like I did). If you have all models based on the main peewee Model class you can simply use:
import peewee
models = peewee.Model.__subclasses__()

Credit to this question for the idea. They also go into more detail on how to get it to work recursively if your model is more complex.

A: Extending coleifer's answer with the assumption that all tables are grouped in one module:
import inspect
import peewee
import tables
models = [
    obj for name, obj in inspect.getmembers(
        tables, lambda obj: type(obj) == type and issubclass(obj, peewee.Model)
    )
]
peewee.create_model_tables(models)

A: def create_all_tables():
    for cls in sys.modules[__name__].__dict__.values():
        if hasattr(cls, '__bases__') and issubclass(cls, peewee.Model):
            if cls is not BaseModel:
                cls.create_table()

This also works for ManyToManyField's get_through_model().

A: I found the existing answers did not support the BaseModel pattern recommended in the docs. I created a helper function to recursively find Models
def all_subclasses(base: type) -> list[type]:
    return [
        cls
        for sub in base.__subclasses__()
        for cls in [sub] + all_subclasses(sub)
    ]

I then filtered out base models, by prefixing them with an underscore.
class _BaseModel(Model):
    class Meta:
        database = db

models = [
    sub for sub in all_subclasses(Model)
    if not sub.__name__.startswith('_')
]

db.create_tables(models)


text:
Q: CSS transition only on not active I have a scenario where I need to immediately change the background colour on hover, and revert back immediately to the original colour on dehovering. This is simple enough with:
#el {
    background-color: black;
}
#el:hover {
    background-color: gray;
}

However, I'm having an issue where I also need to immediately change the background colour on active, but to use a transition when active is released.
#el:active {
    background-color: green;
}

#el:hover:deactivate { /*does not exist*/
    background-color: gray;
    transition: background-color 1s ease;
}

#el:deactivate { /*does not exist either*/
    background-color: black;
    transition: background-color 1s ease;
}

I can't do this by setting #el:hover because then the hover entry also gets animated and I can't do this on #el itself because then dehovering also gets animated.
Is there any way to do this using pure CSS and without JS?

A: You can use :not(:active)

#el:active {
    background-color: green;
}

#el:not(:active):hover {
    background-color: gray;
    transition: background-color 1s ease;
}

#el:not(:active) {
    background-color: black;
    transition: background-color 1s ease;
}
active

A: You can simulate this using a pseudo element and you will be able to manage two different things. The hover will change the background and the active state will change the pseudo-element:

#el {
  color: white;
  background-color: black;
  border: 1px solid white;
  height: 200px;
  width: 200px;
  position:relative;
  z-index:0;
}
#el:before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:transparent;
  transition:1s;
}

#el:hover {
  background-color: gray;
}

#el:active::before {
  background: green;
  transition: 0s;
}

  CONTENT HERE