text:
Q: tar + compress folder to tar.gz and removed the folder by the following way we tar the folder presto-server-0.210 to file
tar -czvf presto-server-archive.tar.gz presto-server-0.210

so after we tar the folder , folder still exists
is it possible to use the tar or other approach and replace the folder to tar file , so folder will removed and instead of folder we create the tar file

A: As noted in the comments, the proper way to do this is rm. For safety purposes, tar -jcvf folder.tar folder && rm -rf folder would only execute if the tar was successful - see "RETURN VALUE" section of the man page.


text:
Q: Unable to filter JSON output using jq. I am using CURL I am unable to filter the following.
I need to find out the count of names starting with "SnapshotSet" which are under the name tag of the below JSON file.
Example - "name": "SnapshotSet.1475076959480"
As a first step I am trying to filter out all the names starting with SnapshotSet...but receiving the following error.
jq '.snapshot-sets[]' testjq
error: sets is not defined
But when I filter out links I am able to get an output
  jq '.links[]' testjq
{
  "href": "https://test.com/api/json/v2/types/snapshot-sets/",
  "rel": "self"
}

Anything to do with the name "snapshot-sets"?
Please find the JSON file below.
{
"links": [
    {
        "href": "https://test.com/api/json/v2/types/snapshot-sets/",
        "rel": "self"
    }
],
"snapshot-sets": [
    {
        "href": "https://test.com/api/json/v2/types/snapshot-sets/1",
        "name": "SnapshotSet.1475076959480"
    },
    {
        "href": "https://test.com/api/json/v2/types/snapshot-sets/3",
        "name": "SnapshotSet.1475165496304"
    },
    {
        "href": "https://test.com/api/json/v2/types/snapshot-sets/2",
        "name": "SnapshotSet.1475158265437"
    },
    {
        "href": "https://test.com/api/json/v2/types/snapshot-sets/63659",
        "name": "server1a_b_c_STFS1474869600618"
    },

A: As explained here, the abbreviated form .keyname cannot be used when the key contains the - character.
You can run the following to get the list of all names from your file:
jq '."snapshot-sets"[].name' testjq

redpajama_set_name: RedPajamaStackExchange


text:
Q: Render HTML definition lists in Lift Another lift beginner question:
I want to render a HTML Definition List in a Lift Snippet like this:

Name

Seppl

Street

abc

The snippet-template looks now like this:

Term

Description

The Scala Snippet code:
def render = {
  val values=List(("Name", "Seppl"), ("Street", "abc"))

  ".definition" #> values.map(value =>
    ("dt" #> value._1) &
    ("dd" #> value._2))
}

This works, but I want a definition list without div-Tags (I think, this it isn't valid HTML.)
Is this possible with CSS Transformers?

A: As you don't seem to use CSS I would recommend you to use the following:
Snippet Template code:

Scala Snippet code:
def render = {
  val values=List(("Name", "Seppl"), ("Street", "abc"))

  values.map(value =>

{value._1}

{value._2}

  )
}

Of course I avoid using CSS selectors so I don't know if it is exactly what you are looking for.

A: See http://www.assembla.com/spaces/liftweb/wiki/Binding_via_CSS_Selectors
At the end of the page (Iteration) there's an example with unordered list.


text:
Q: flask-jwt-extended TypeError: Object of type 'function' is not JSON serializable I'm trying to make an API jwt authenticate with flask using flask_sqlalchemy and flask_jwt_extended,marshmallow to validate input data
Login route to get token:
from flask import Flask,request,jsonify, abort
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from models import Book, Publisher, User
from crud import session
from config import DATABASE_URL
from marshmallow import Schema, fields, validates, ValidationError
from marshmallow.validate import Length, Range
from flask_jwt_extended import (
    JWTManager, jwt_required, create_access_token,
    get_jwt_identity
)
import os
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = '1234'
jwt = JWTManager(app)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#init db
db = SQLAlchemy(app)
#init ma
ma = Marshmallow(app)
@app.route('/login', methods=['POST'])
def login():
  if not request.is_json:
    return jsonify({"msg": "Missing JSON in request"}), 400
  username = request.json['username']
  password = request.json['password']
  if not username:
    return jsonify({"msg": "Missing username"}), 400
  if not password:
    return jsonify({"msg": "Missing password"}), 400
  if not db.session.query(User).filter(User.username == username, User.password == password).first():
    return jsonify({"msg": "Wrong username or password"}), 401
  access_token = create_access_token(identity=username)
  return jsonify(access_token=create_access_token), 200
#protected route
@app.route('/book', methods=['POST'])
@jwt_required
def add_book():
  id = request.json['id']
  title = request.json['title']
  author = request.json['author']
  publisher_id = request.json['publisher_id']
  price = request.json['price']
  pages = request.json['pages']
  published = request.json['published']
  errors = create_book_schema.validate(request.get_json())
  if errors:
    return jsonify(msg=errors), 400
  new_book = Book(id=id,title=title,author=author,publisher_id=publisher_id,price=price,pages=pages,published=published)
  db.session.add(new_book)
  db.session.commit()
  return jsonify(msg='book successfully created', book_id=new_book.id), 200

When i send json input through postman at "/login" route to get the token i got this error return :

TypeError: Object of type 'function' is not JSON serializable

What am i doing wrong ? Thank
EDIT
Here the input json which is the same as in my database
{
    "username": "linh",
    "password": "123"
}

A: You need to return a serializable object for jsonify to work:
return jsonify(dict(access_token=access_token)), 200

You already have your access_token defined in a variable, you can just return it inside of a dictionary.


text:
Q: Magento 2 express checkout want to disable using product sku? In my Magento 2 i have two products with sku's

*

*seller-commission-product

*Austinmer 4 Door

*

*I need to show paypal express checkout for the item sku is seller-commission-product  & (this flow is working fine)

*I don't want to show the paypal express checkout if item sku is not a seller-commission-product, i want to show remaining payment methods as it is (Not working)
Hence i have followed the below procedure.

app/code/Ewall/Account/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="payment_method_is_active">
<observer name="Ewall_Account_Payment_Methods_For_Active" instance="Ewall\Account\Observer\PaymentMethodAvailable" />
</event>
</config>

app/code/Ewall/Account/Observer/PaymentMethodAvailable.php

<?php
namespace Ewall\Account\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\ManagerInterface;
class PaymentMethodAvailable implements ObserverInterface
{
    /**
     * payment_method_is_active event handler.
     *
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $writer = new \Zend\Log\Writer\Stream(BP.'/var/log/stackexchange.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);

        $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
        $paymentHelper = $objectManager->get('Ewall\Account\Model\Paymentmethod');
        $activePaymentMethods = $paymentHelper->toOptionArray();
        $cart = $objectManager->get('\Magento\Checkout\Model\Cart');
        // retrieve quote items array
        $items = $cart->getQuote()->getAllVisibleItems();
        $requiredSku = '';
        foreach($items as $item)
        {
            $requiredSku = $item->getSku();
        }
        $logger->info("activePaymentMethods===".print_r($activePaymentMethods,true));

        if($requiredSku == 'seller-commission-product')
        {
            if($observer->getEvent()->getMethodInstance()->getCode() != 'paypal_express')
            {
                $checkResult = $observer->getEvent()->getResult();
                $checkResult->setData('is_available', false); //This is disabling all payment methods except paypal_express
            }

        }elseif($requiredSku != 'seller-commission-product')
        {

            if($observer->getEvent()->getMethodInstance()->getCode() == 'paypal_express')
            {
                $checkResult = $observer->getEvent()->getResult();
                $checkResult->setData('is_available', false); //This is enable all payment methods except paypal_express
            }

        }

    }

}

app/code/Ewall/Account/Model/Paymentmethod.php

<?php

namespace Ewall\Account\Model;

use \Magento\Framework\App\Config\ScopeConfigInterface;
use \Magento\Payment\Model\Config;

class Paymentmethod extends \Magento\Framework\DataObject implements \Magento\Framework\Option\ArrayInterface
{
    /**
     * @var ScopeConfigInterface
     */
    protected $_appConfigScopeConfigInterface;
    /**
     * @var Config
     */
    protected $_paymentModelConfig;

    /**
     * @param ScopeConfigInterface $appConfigScopeConfigInterface
     * @param Config               $paymentModelConfig
     */
    public function __construct(
        ScopeConfigInterface $appConfigScopeConfigInterface,
        Config $paymentModelConfig
    ) {

        $this->_appConfigScopeConfigInterface = $appConfigScopeConfigInterface;
        $this->_paymentModelConfig = $paymentModelConfig;
    }

    public function toOptionArray()
    {
        $payments = $this->_paymentModelConfig->getActiveMethods();
        $methods = array();
        $myCustomPaymentMethods = array();
        foreach ($payments as $paymentCode => $paymentModel) {

            $myCustomPaymentMethods[]=$paymentCode;

            $paymentTitle = $this->_appConfigScopeConfigInterface
                ->getValue('payment/'.$paymentCode.'/title');
            $methods[$paymentCode] = array(
                'label' => $paymentTitle,
                'value' => $paymentCode
            );
        }

        return $myCustomPaymentMethods;//Here i am returning active payment method codes

    }
}

Please suggest me how can fix this? the second flow not working for me. please suggest  me whether this approach is correct or not?


text:
Q: PL/SQL: Row isn't inserting I'm learning PL/SQL and I've created this procedure, which compiles; I'm not experiences enough with PL/SQL to spot where I went wrong:
Just to be clear, my question is, 'what did I do wrong?'
I'm using Datagrip and port forwarding to an OracleVM; I doubt there's a problem there, because I've inserted rows before, but this just isn't working.
CREATE OR REPLACE PROCEDURE basket_add_sp
  (
    p_basketid IN bb_basketitem.idbasket%TYPE,
    p_prodid IN bb_basketitem.idproduct%TYPE,
    p_qty IN bb_basketitem.quantity%TYPE,
    p_price IN bb_basketitem.price%TYPE,
    p_size IN bb_basketitem.option1%TYPE,
    p_form IN bb_basketitem.option2%TYPE
  )
  IS
  BEGIN
  INSERT INTO BB_BASKETITEM(idbasketitem, idproduct, quantity, price, idbasket, option1, option2)
    VALUES (bb_idBasketitem_seq.NEXTVAL, p_prodid, p_qty, p_price, p_basketid, p_size, p_form);
  COMMIT;
END;

Which completes.
[2016-07-21 21:18:28] completed in 18ms

I run the procedure:
BEGIN
  basket_add_sp(14,8,1,10.80,2,4);
END;

Also completes.
[2016-07-21 21:18:39] completed in 14ms

But when I check the table to verify, no rows are returned.
SELECT * FROM BB_BASKETITEM WHERE IDBASKETITEM = 14;

Returns this:

However, when I check the table, there are other rows there.
SELECT * FROM BB_BASKETITEM WHERE IDBASKETITEM = 20;

Returns this:

A: SELECT * FROM BB_BASKETITEM WHERE IDPRODUCT = 8;

IDBASKETITEM is a unique ID that Oracle generates by sequence when you do the insert.


text:
Q: Object isn't recognized as part of collection I'm trying to create a script which gathers puts elements from XML in a list and verifies that a specific object is a part of this list. Please find my script below:
class BaggageEntitlement{
    String allowancePieces
    String ruleType
    String ruleId
    String passengerNameRef
    String segmentNumber

boolean equals(BaggageEntitlement that) {
    return (
            this.allowancePieces.equals(that.allowancePieces) &&
                    this.ruleType.equals(that.ruleType) &&
                    this.ruleId.equals(that.ruleId) &&
                    this.passengerNameRef.equals(that.passengerNameRef) &&
                    this.segmentNumber.equals(that.segmentNumber)

        )
    }
}

ArrayList<BaggageEntitlement> expectedEntitlements = new ArrayList<BaggageEntitlement>()
ArrayList<BaggageEntitlement> actualEntitlements = new ArrayList<BaggageEntitlement>()

BaggageEntitlement segment1Entitlement = new BaggageEntitlement(allowancePieces : '2', ruleType : 'OVERRIDE', ruleId : '15483', passengerNameRef: '01.01', segmentNumber: '1')

def cbfNode = new XmlSlurper().parseText(messageExchange.getResponseContentAsXml()).Body.CalculateBagFeesRS

def baggageEntitlementNode = cbfNode.AncillaryOffers.Itinerary.BaggageEntitlements

baggageEntitlementNode.EntitlementItineraryPart.each{
    def baggageAllowanceEntitlementNode = it.BaggageAllowanceEntitlement
    BaggageEntitlement baggageEntitlement = new BaggageEntitlement()
    baggageEntitlement.allowancePieces = baggageAllowanceEntitlementNode.MaxPieces.text().toString()
    baggageEntitlement.ruleType = baggageAllowanceEntitlementNode.@ruleType.toString()
    baggageEntitlement.ruleId = baggageAllowanceEntitlementNode.@ruleId.toString()
    baggageEntitlement.passengerNameRef = it.PassengerReference.@nameReferenceNumber.toString()
    baggageEntitlement.segmentNumber = airIdToSegmentNumber[it.SegmentReference.@segmentNumber.toString()]

    actualEntitlements.add(baggageEntitlement)

}

But after creating a collection, objects which are present in created collection aren't recognized as a part of collection. I've created the following piece of code to demonstrate this:
println "Is iterator in collection: ${actualEntitlements.contains(segment1Entitlement)}"
println "Is object equals (I) to iterator: ${actualEntitlements[0] == segment1Entitlement}"
println "Is object equals (II) to iterator: " + actualEntitlements[0].equals(segment1Entitlement)
println "Is 'allowancePieces' members are equal: " + (actualEntitlements[0].allowancePieces == segment1Entitlement.allowancePieces)
println "Is 'ruleType' members are equal: " + (actualEntitlements[0].ruleType == segment1Entitlement.ruleType)
println "Is 'ruleId' members are equal: " + (actualEntitlements[0].ruleId == segment1Entitlement.ruleId)
println "Is 'passengerNameRef' members are equal: " + (actualEntitlements[0].passengerNameRef == segment1Entitlement.passengerNameRef)
println "Is 'segmentNumber' members are equal: " + (actualEntitlements[0].segmentNumber == segment1Entitlement.segmentNumber)

And the console output for comparing object member by member is looks like:
Is iterator in collection: false
Is object equals (I) to iterator: true
Is object equals (II) to iterator: true
Is 'allowancePieces' members are equal: true
Is 'ruleType' members are equal: true
Is 'ruleId' members are equal: true
Is 'passengerNameRef' members are equal: true
Is 'segmentNumber' members are equal: true

Could you tell me why my object isn't considered to be a part of collection though member by member comparison returns 'true' for every member?

A: Because you did not override equals. You supplied your own equals method with a different signature. Override the correct equals method...
public boolean equals(Object o) {
    ... your code here...
}

...and the Collection will recognize your object, as by the Collection contract for Collection.contains(...)

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

(This means the correct equals method and not any equals method. The parameter must be an object, otherwise it is a different equals method and will not help you.)
Having a convenient method like boolean equals(BaggageEntitlement that) may be nice for other purposes (though I doubt it), but this method won't be called since most other classes will expect an Object and not a "BaggageEntitlement". Equals is one of the basic methods of Object, so you should always override that instead of creating your own different version.


text:
Q: What is the meaning of the globe icon next to some player names when searching for friends? When searching for people to add to the list of friends I noticed some people have this small icon of a globe next to their names:

As far as I could tell it makes no difference in who I can/can't try to add. What does the icon actually mean?

A: This icon is related to the addition of emblems on players' profiles in the Season 2 update on October 18th 2018. When you achieve certain trophies, you have the option of displaying the associated emblem on your profile. This emblem will also show up when you navigate to your friends list.
The emblem you referenced in the image is the Tenacious Adventurer - Bronze emblem and can be obtained by receiving 5 quest trophies.
To set an emblem on your profile:

*

*Select the Menu button in the top-right corner

*Select Player Info

*Select Set Emblem


text:
Q: Allow suggested edits on beta site metas There is a long standing ban on allowing suggested edits on per-site meta:

*

*Why can't I suggest edits on SE meta sites?
I would like this relaxed on beta sites to allow broader participation to help shape beta site meta posts.

I just ran into this on this post where I wanted to correct the list of sites that allow software recommendations. Wouldn't it make sense to allow edit suggestions on beta sites since restricting edits to +1k users on beta sites means an extremely limited group of people can even suggest a change to a post?
Here is the problem:

*

*Undocumented behavior. The about page says "Any user can propose edits, but not all edits are publicly visible immediately."

*Confusing behavior. Why are meta edits harder to moderate than site edits? Where else on SE does a control show dimmed out when you cannot even exercise that control? Shouldn't the edit text be hidden if no suggested edits are allowed?

*Reduces input. Anyone who reviews edits knows that some absolute gems come from anonymous and new editors. How is preventing edits making the meta site better for the users or the moderators? Restricting diversity is bad, especially if it's not for a clear and convincing reason. The only reason posted for this restriction characterizes the edit review queue as needing a 10k user to process (which isn't applicable anymore since 2k users review edits now site wide - 1k on beta sites). The argument that "yet another queue" seems out of place with the current design and this doesn't have to be another queue.

*Causes more work. If someone wants to edit a post on a beta meta, they have to:

*

*(ab)use the comments like I did. (Which does discuss the question, but causes more work and noise for someone to do the edit rather than approve or deny the edit).

*Flag it for a moderator to help. (Which presumably would be the last flag a moderator should be handling, but really - how many flags happen on beta meta sites?)

*Go away and not edit a post on a site meta where you wanted to edit a post.

Proposed solution.

*

*Document the current behavior in the help pages site wide. If meta are special, say so clearly.

*This is subjective, but I believe we should strive for "making things as simple as possible but not simpler" What we have may have been good when the kinks were being worked out, but it's not simple enough IMO.

*Roll per site meta edits for beta sites into the main edit queue just as proposed on the request to change this site wide:

the ideal solution would be to just add the suggested edits on the meta to the queue on the main site. That way there would be no additional queue, and the meta sites would be editable by anyone like all the main sites


text:
Q: Java Repository can't implement method I am using the Micronaut framework, and I have the following setup:
have an Entity called Transaction, with a Long ID, and three fields, a UUID, a String Report and a String State:
@Entity
public class Transaction {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

private UUID uuid;

private String report;

private String state;
}

In a CrudRepository, I have defined the following query:
int updateByUuid(UUID uuid, String state);

This correctly updates my Transaction entity with the given new State.
Now I wanted to write a different query:
int updateByUuid(UUID uuid, String report):

Obviously this failes to build, since the signature is the same.
I tried to write the following:
int updateReportByUuid(UUID uuid, String report);

or:
int updateReportByUuid(String report, UUID uuid);

(So changing the parameters around)
This fails as well, with the error message of
Projections are not supported on batch updates

and
No possible implementations found

The only time it did not fail to build is when I changed the function to the following:
int updateReportByUuid(@Id Long id, String report);

But obviously this is incorrect (since I specified ByUuid, and as the first parameter I have given a Long id), and also not the functionality I want. What I want is for the database to find the Transaction I want to update by its' UUID, and update its' Report column.

A: The reason why this is considered as a batch update is, because you are updating records on a non primary key field.
As mentioned above the field uuid is technically unique and you also declared it as unique but it is not a primary key. Therefore Micronaut Data considers it as a batch update.
You have at least the following two options.

*

*Convert the id field from Long to UUID and drop the field uuid. With that case your primary key is a UUID and your update methods will start to work.

*Tell Micronaut Data what to do by adding at @Query annotation.


text:
Q: Advice about javascript configuration for objects/widgets and where to add this I have a lot of javascript configuration that I need to output (configuration objects for my own needs, jquery dialog setup and so on). They are for specific fields in forms.
I was using 1 script block for this that is always added, but now have decided to add the a scriptblock to my templating system's partials for each field, so that only the configuration for the actual fields used is included in the generated html. I decided to give the scrip block a class which is basically the path to the partial so that I know where to find that script block exactly and quickly.
Is this a good approach? I find this better than a huge script that just contains all the configuration that I need for certain interface widgets, popups, ajax requests and so on.
Will it slow down the page having lots of separate script blocks, there are no functions in th eblocks just objects with properties.

A: I think it is a better approach than having a giantic script block since it is more modular.
However, why do you need to find the script block?
Script inside script tag is automatically executed once appended to the html.
You don't have to manually run it.


text:
Q: Need to use Volume Shadow Copy Service in 32/64 bit QT C++ program I have a couple questions about using Volume Shadow Copy Service for my QT C++ program.

*

*I read that in order to use VSS you must be running native 32/64 bit
no WOW64 supported.  So this means I need to compile my program in
whatever bits Windows is using on the computer where the program exe is running correct?

*Do I need to use MSVC or can I do this using MinGW?

*If I need MSVC how do I do a static build for 32 and 64 bit?  I found the first 4 links on google for "qt msvc static build" but they all vary a little bit so I'm wondering which is the best to use.

*Also for either MSVC or MinGW do I need to include VSS libraries in the project?  I need to get the VSS SDK correct?  How do I integrate such into the program?  I already know the code to use.

Thanks :)

A: *

*That is correct, the program must be compiled to match the target OS's architecture.

*Since most of the VSC API is COM, I don't really see how trying to do this using MinGW would be better.

*In Visual Studio, all you need to do is to include the VssApi lib, i.e.
#pragma comment (lib, "VssApi.lib")

*All you really need are the VSS specific headers. This also really depends on the OS your're targeting. If you plan on supporting say, Windows XP, you'll need the XP specific SDK.

Some reading: https://technet.microsoft.com/en-us/library/ee923636(v=ws.10).aspx


text:
Q: get the generic class type at runtime when autowiring I'm having a base class which operates on third party library and specific repo class. I'm using the base class as composition. I'm getting error while autowiring the base class while getting generic type as run time.
@Repository
public interface BaseRepo<T, K> {
  public void save(T obj);
  public T get(K id);

}

@Repository
public class BaseRepoImpl<T, K> implements BaseRepo<T, K>{

  private Class<T> classType;

  public BaseRepoImpl(){
    Type[] types = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments();
   this.classType = types[0];
  }

  public void save(T obj){
    somethirdParty.save(obj);
  }

  public T get(K id){
     return somethirdParty.get(classType, id);
   }
}

@Repository
public interface MyRepo {
  public void save(MyObject obj);
  public T get(String id);

}

@Repository
public class MyRepoImpl implements MyRepo{

   private BaseRepo<MyClass, String> baseRepo;

   public void save(T obj){
     baseRepo.save()
   }

  public T get(String id){
    return baseRepo.get(id);
  }
}

Getting below error while tomcat startup -
main ContextLoader Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseRepoImpl' defined in file [...BaseRepoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.intuit.qbo.data.dynamodb.DynamoDBRepositoryImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: class java.lang.Class cannot be cast to class java.lang.reflect.ParameterizedType (java.lang.Class and java.lang.reflect.ParameterizedType are in module java.base of loader 'bootstrap')
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1303)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1197)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)


text:
Q: The following code for "prime sieve" is not working with Release mode ,,but works perfectly with Debug mode The following code for "prime sieve" is not working with Release mode ,,but works perfectly with Debug mode.. I cannot figure out why ,, am using Microsoft Visual c++ 2010 express
#include <iostream>
#include <fstream>
#include <cmath>
#include <time.h>
#include <vector>
using namespace std;
void main(){

    clock_t start= clock();

    int n = 10000000;
    bool* primes= new bool[n];
    primes[0]=0;
    int g = (int)sqrt(n*1.0) +1;
    for (int i = 2 ;i <g ; i++){
        if(primes[i]){
            for (__int64 j = i*i ; j <n ; j+=i)
                primes[j]=0;
        }

    }
    printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);

    int* p = new int[n/2];
    int c = 0;
    for (int x = 0 ; x<n ; x++)
        if (primes[x]){
            p[c]=x;
            c++;
        }

    cout<<p[481516]<<endl;
    system("pause");
}

A: You haven't initialized the rest of the values in your primes array before you start accessing them. Try adding
for (int i=1; i<n; i++)
    primes[i] = 1;

before your calculation of g.


text:
Q: Independent Probabilities for Multiple Events I don't understand my professor's definition of multiple independent events.
Does he mean that for $A_1,A_2,A_3,\ldots, A_n$ events to be independent that each $n$-tuplet (for $n = 2$ to $n$) must all be independent?
e.g., If 4 events (call them $A,B,C,D$) are independent then the number of equations that must be satisfied are:
      $4 \choose 2$ pairs, $4 \choose 3$ trios, and the equation $P(A\wedge B\wedge C\wedge D)=P(A)P(B)P(C)P(D)$

A: Suppose $P(A)=P(B)=1/2$ and $P(A\cap B)=1/4$, so these are independent events.
Let $C$ be false if $A$ and $B$ are both false or both true; and let $C$ be true otherwise.
Then obviously $C$ cannot be considered "independent" of $A$ and $B$ in any reasonable sense of the word.
But $P(A)P(B)=P(A\cap B)$ and $P(A)P(C)=P(A\cap C)$ and $P(B)P(C)=P(B\cap C)$.
And $P(A)P(B)P(C)=\dfrac18\ne0=P(A\cap B\cap C)$.


text:
Q: Is there a way to record user's activity offline and update them when they online? I just want to allow users make modification offline with insecure data. Namely modifying their profile name, add new content (page), photos and so forth. When they come online all these activities must be updated accordingly in the online server.
I need some vast ideas on this. It's going to be a web app, mostly sort of personal website.If I were to do this app, should I ensure they have mysql and wamp server installed so that offline changes can be recorded in the local host?
I refer to few forums and some of them mentioning html5 localstorage. Here's one of them: Mobile site/app - capture data offline and push to live database
The site to be developed mainly in PHP, MYSQL, HTML5 and JQUERY.

A: If you don't want to bother your users on how to install some programs in order to store their data while offline - (this process should flow unnoticed or with less pain for the user as possible) I suggest you going for LocalStorage -
If you're fine with 10MB (Chrome and Firefox, 5MB on mobile) of user disk quota.
Need more space?
Cache API as an interface of the ServiceWorker API

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)

IndexedDB :

*

*https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB

*https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB

*https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/

*https://github.com/jonnysmith1981/getIndexedDbSize Calculate the IDB size!
Worth knowing that (FF at least) all IndexedDB bases (from multiple sources/websites) cannot take more than 50% total disk size - and from that size one IDB cannot take up more than 20%. Also, according to Least Recently Used Policy, if the databases available space gets full, the browser can (and will) kill an IndexedBD.
Note that for older browsers that do not support IndexedDB you might want to use a shim to fallback to Web SQL Database (which is no longer maintained)


text:
Q: How to login using request type post.? I need to login with email and password using post method. For this i add this part of code on login button, please look at this.
 if (_email.text.length >0 ) {
    if (_password.text.length >0) {
        Reachability *reach = [Reachability reachabilityForInternetConnection];
        NetworkStatus status = [reach currentReachabilityStatus];
        if (status) {
            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(self.view.frame.origin.x, 60)];

            [SVProgressHUD showWithStatus:@"loading.." ];
            NSString *urlString = [NSString stringWithFormat:@"email=%@&password=%@&deviceToken=testdata",_email.text,self.password.text];

            NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[urlString length]];
            NSMutableURLRequest *req = [[NSMutableURLRequest alloc]init];
            NSString *url = @"http://qa.networc.in:1336/api/users/app/login";
            [req setURL:[NSURL URLWithString:url]];
            [req setHTTPMethod:@"POST"];
            [req setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [req setHTTPBody:[urlString dataUsingEncoding:NSUTF8StringEncoding]];
            [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue currentQueue] completionHandler:
             ^(NSURLResponse *reponse , NSData *data, NSError *error){
                 NSError *errre1;
                 diclogin=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&errre1];
                 NSLog(@"result is%@ :",diclogin);
                 [user setObject:[diclogin objectForKey:@"email"] forKey:@"email"];

                 NSLog(@"user %@", user);

                 if ([diclogin objectForKey:@"email"]) {
                     [SVProgressHUD dismiss  ];
                     ViewController *secondViewController =[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"Map"];
                     [self.navigationController pushViewController:secondViewController animated:YES];
                 }else {
                     [SVProgressHUD dismiss  ];
                     loginalerview.tag = 1;
                     loginalerview = [[UIAlertView alloc] initWithTitle:@"SignIn !" message:[diclogin objectForKey:@"msg"] delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
                     loginalerview.tag = 1;

                     [loginalerview show];
                 }

             }];
        } else {
            [[[UIAlertView alloc] initWithTitle:@"Internet Alert" message:@"Please check your internet." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil] show];
        }
    }else{
        [[[UIAlertView alloc] initWithTitle:@"Password Alert !" message:@"Please enter the password" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil] show];
    }
}else{
    [[[UIAlertView alloc] initWithTitle:@"Email Alert !" message:@"Please enter email." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil] show];
    _password.text = @"";
}

But when i print user in console i get null value. i entered correct credentials. This block is not compile right now.
if ([dictLogin objectForKey:@"email"]) {
                         [SVProgressHUD dismiss  ];
                         ViewController *secondViewController =[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"Map"];
                     [self.navigationController pushViewController:secondViewController animated:YES];

                        }


text:
Q: Why do GCP's AMD EPYC VM instances seem to have 1 "problematic" vCPU? Sorry for the longish post, here's TLDR: For each instance of Google Cloud Engine AMD-powered VMs, 1vCPU is crippled in some way compared to the rest. Any idea how/why?
I did a performance/value analysis for various instance types the Google Compute Engine provides and found that for our workloads the AMD EPYC Milan-powered n2d types offered the best performance and value. I then extended the comparison to other cloud providers, you can see a detailed cloud provider performance/value comparison here (perl workloads, as well as compiling and Geekbench thrown in for good measure) and in the course of this, as I was trying to calculate things like scalability, I could see something odd happening just with Google's AMD EPYC VMs: If you created a 2xvCPU, 4xvCPU or 8xvCPU (did not try further) AMD Rome (n2d) or AMD Milan (n2d, t2d, c2d) instance, 1 of the vCPUs is not the same as the others, performing at times significantly worse (depending on the workload, even over 50% worse). An exception is 2xvCPU t2d or Rome-n2d, in which case sometimes you can get BOTH vCPUs be the "slow" type.
The issue shows up as a significant performance variance when running single-threaded benchmarks, as the vCPUs appear the same to the scheduler so it's sort of a matter of luck which one ends up handling the load. But it is very clear if you use taskset to set the processor affinity of the process. So, taking Geekbench for example on a c2d where CPU 0 is the "slow" one we run:
taskset 1 ./geekbench5

And get a single core result of 986 (multi-core runs 2 threads on that single vCPU so is similar). Then try running on the other vCPU:
taskset 2 ./geekbench5

And get what the EPYC Milan can actually do, which is 1266 in this case.
If you look at the benchmark breakdown, several benchmarks seem unaffected, being within 5% either side of performance between the two runs, but there are some big differences, with AES-XTS being 3x faster on the second core! Here is a table with the fast vs slow vCPU results on the various AMD Milan (M) and Rome (R) instances:

vCPU
n2d-s2 (M)
n2d-s2 (R) A
c2d-s2 (M)
t2d-s2 (M)

fast
1251
970
1266
1150

slow
979
788
986
893

If you have an 8xvCPU instance only 1 of those cores will have the performance issue, so it will affect you less. There is actually not pattern which #vCPU is the problematic, e.g. if you have an 8xvCPU instance you would try parameters 1, 2, 4, 8, 16, 32, 64, 128 for taskset (it takes a bitmask) and either of those can be the one.
I tried the LMbench microbenchmarks to see if there was any difference in the memory latency timings, in case the slow core doesn't get access to all the caches etc, but all the LMbench memory benchmarks gave similar results for fast vs slow cores, apart from libc bcopy and Memory bzero bandwidth, which reported over twice the bandwidth for the non-affected CPU for the first 512b - 1k, with the slow CPU slowly catching up after the 4k mark:
fast vCPU           slow vCPU

libc bcopy unaligned
0.000512 74850.98   0.000512 39376.69
0.001024 102429.05  0.001024 56302.91
0.002048 104352.51  0.002048 74090.38
0.004096 108161.33  0.004096 90174.68
0.008192 97034.51   0.008192 85216.90
0.016384 99009.57   0.016384 93743.92
0.032768 54218.61   0.032768 52910.72
0.065536 53300.89   0.065536 49660.89
0.131072 50072.18   0.131072 51533.84

libc bcopy aligned
0.000512 82067.77   0.000512 38346.13
0.001024 103010.95  0.001024 55810.31
0.002048 104568.18  0.002048 72664.92
0.004096 105635.03  0.004096 85124.44
0.008192 91593.23   0.008192 85398.67
0.016384 93007.97   0.016384 91137.35
0.032768 51232.94   0.032768 49939.64
0.065536 49703.80   0.065536 49675.92
0.131072 49760.35   0.131072 49396.37

Memory bzero bandwidth
0.000512 83182.36   0.000512 43423.32
0.001024 95353.76   0.001024 61157.60
0.002048 103437.22  0.002048 76770.77
0.004096 70911.40   0.004096 61986.23
0.008192 84881.63   0.008192 77339.78
0.016384 95343.37   0.016384 87949.77
0.032768 97565.34   0.032768 91436.64
0.065536 93136.11   0.065536 89826.23
0.131072 95790.48   0.131072 90689.07

All the other benchmarks, including unrolled bcopy and memory read/writes, latency etc were within the margin of error between the vCPUs. I am not sure what this could tell us, in general I am at a loss on how this is happening (some sort of google hypervisor bug?), and why no-one seems to have noticed something that was quite obvious from the start of my benchmarking - I find no references googling for it. And, surely you test performance when you design a cloud solution, this couldn't have gone past any QA in the first place.
I can't see what I may be doing wrong on my side, I did try apart from Debian Bullseye other distros, and saw the same with Debian Buster, Ubuntu, CentoOS. A bit more details on things I tried are at the last part of my aforementioned cloud performance comparison blog post.
Anyone with any insight into this, I'd be curious to know what's going on.

A: Just to let you know, this is Google's official answer:

I believe the behaviour that has been captured here is the underlying Compute Engine resource that Google Cloud uses within its hypervisor to run essential networking and management tasks. As a result of this component, CPU may not be able to reach 100% on all cores. Smaller instances may see this more so due to the relative size of the component to the size of the machine.
The overall stance of this symptom at this time is that this is part of the infrastructure and working as intended. You're welcome to choose other CPU architecture types, or use use a larger machine type; either of these should make up for the overhead which is taken up by the hypervisor resource. I've still forwarded your findings, reproduction steps and comments to the Compute Engine team for their record.

It sounds a bit reasonable, until you start wondering why it only happens with EPYC instances, why nothing similar happens with other provider's EPYC instances, why it is random whether 1 or 2 vCPUs of your instance are affected, and why it only affects small writes.
So, for me, it can't exactly be "working as intended", but I don't think it's worth pursuing further with them, as I said it's not a big issue, unless of course you happen to run something very specific. E.g. AES encryption on 4k blocks will run at just 1/3rd the speed on the compromised vCPU.
Update 11/2022:
The problem seems to have gone for new n2d and t2d instances for me. It is still a problem with c2d instances, which were a waste of money IMHO anyway (not at all faster than the cheaper types), so they are to be avoided.


text:
Q: Apache HTTP client org.apache.http.NoHttpResponseException even after lower validateAfterInactivity I have HTTP client and it receiving following error occasionally. At the time of this exception receive the actual request is not hit the target server.
org.springframework.ws.client.WebServiceIOException: I/O error: xxxx:yy failed to respond; nested exception is org.apache.http.NoHttpResponseException: xxxx:yy failed to respond
Apache http client version : 4.5.13
I have reduced the validateAfterInactivity to 100ms but no luck. Still I am receiving the errors in same rate.
My HttpClient pool configuration is in below.
    public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
        PoolingHttpClientConnectionManager result = new PoolingHttpClientConnectionManager();
        result.setMaxTotal(500);
        result.setDefaultMaxPerRoute(75);
        result.setValidateAfterInactivity(100);
        return result;
    }

A: This was able to sort out by adding both HttpRequestRetryHandler and setValidateAfterInactivity.
httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() {
               @Override
               public boolean retryRequest(java.io.IOException exception, int executionCount, HttpContext context) {
                   if (executionCount > 2) {
                       log.warn("Skipped retry");
                       return false;
                   }
                   if (exception instanceof org.apache.http.NoHttpResponseException) {
                       log.warn("Executed retry " + exception.getMessage());
                       return true;
                   }
                   return false;
               }
           });


text:
Q: Is there a way to convert Class extends Something> to Class> I am currently working on a plugin, where I want to offer the possibility to create addons for.
Therefore i use a ClassLoader, which checks the folder of my plugin for JarFiles and search in them for a class extending my abstract class.
Now my ClassLoader is giving me back a list with Class<? extends MyClass>, but I need them to be Class<?> to execute the methods of this class.
I've already tried to cast it to an Object or to the class itsself, which gives me an ClassCastException.
Is there a way to convert Class<? extends MyClass> to Class<?> or a workaround way?
ClassLoader:
public class SPClassLoader {

@SuppressWarnings("unchecked")
public <T> List<Class<? extends T>> findClasses(
        @NonNull final ClassLoader classLoader,
        @NonNull final File file,
        @NonNull final Class<T> clazz,
        @NonNull final Predicate<Class<T>> predicate
) {

    return findClasses(classLoader, file, clazz).stream()
            .filter(aClass -> predicate.test((Class<T>) aClass))
            .collect(Collectors.toList());
}

@SuppressWarnings("unchecked")
public <T> List<Class<? extends T>> findClasses(
        @NonNull final ClassLoader classLoader,
        @NonNull final File file,
        @NonNull final Class<T> clazz
) {

    return findClasses(classLoader, file, clazz::isAssignableFrom).stream()
            .map(aClass -> (Class<T>) aClass.asSubclass(clazz))
            .collect(Collectors.toList());
}

public List<Class<?>> findClasses(
        @NonNull final ClassLoader classLoader,
        @NonNull final File file,
        @NonNull final Predicate<Class<?>> predicate
) {

    if (!file.exists()) {
        return new ArrayList<>();
    }

    if (file.isDirectory()) {
        return findClassesInSourceRoot(classLoader, file, predicate);
    } else if (!file.getName().endsWith(".jar")) {
        return new ArrayList<>();
    }

    final List<Class<?>> classes = new ArrayList<>();

    try {

        final URL jar = file.toURI().toURL();

        final List<String> matches = new ArrayList<>();

        try (final JarInputStream stream = new JarInputStream(
                jar.openStream()); final URLClassLoader loader = new URLClassLoader(new URL[]{jar},
                classLoader)
        ) {
            JarEntry entry;
            while ((entry = stream.getNextJarEntry()) != null) {
                final String name = entry.getName();
                if (name == null || name.isEmpty() || !name.endsWith(".class")) {
                    continue;
                }

                matches.add(name.substring(0, name.lastIndexOf('.')).replace('/', '.'));
            }

            for (final String match : matches) {
                try {
                    final Class<?> loaded = loader.loadClass(match);
                    if (predicate.test(loaded)) {
                        classes.add(loaded);
                    }
                } catch (final NoClassDefFoundError ignored) {
                }
            }
        }
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }

    return ImmutableList.copyOf(classes);
}

private List<Class<?>> findClassesInSourceRoot(
        @NonNull final ClassLoader classLoader,
        @NonNull final File sourceRoot,
        @NonNull final Predicate<Class<?>> predicate
) {
    File[] files = sourceRoot.listFiles();

    if (files == null) return new ArrayList<>();

    ArrayList<Class<?>> classes = new ArrayList<>();

    List<String> classNames = getClassNames("", sourceRoot, sourceRoot);
    try {
        URLClassLoader loader = new URLClassLoader(new URL[]{sourceRoot.toURI().toURL()}, classLoader);

        for (String className : classNames) {
            try {
                Class<?> aClass = loader.loadClass(className);
                if (predicate.test(aClass)) {
                    classes.add(aClass);
                }
            } catch (ClassNotFoundException ignored) {
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return classes;
}

private List<String> getClassNames(String basePath, File sourceRoot, File file) {

    ArrayList<String> classNames = new ArrayList<>();
    if (file.isFile() && file.getName().endsWith(".class")) {
        classNames.add(basePath + file.getName().replace(".class", ""));
    } else if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null) {
            for (File subFile : files) {
                classNames.addAll(getClassNames(file.equals(sourceRoot) ? "" : basePath + file.getName() + ".", sourceRoot, subFile));
            }
        }
    }

    return classNames;
}

}
My methods i use:
    private void loadModes() {

    File file = new File("plugins/MyPlugin/TheFolderWhereTheAddonsAreIn");

    if(!file.exists())
        file.mkdirs();

    addFromDir(file);
    addFromDir(new File("plugins")); //to check the plugins folder if there is an addon as a plugin

    for(Class<? extends SpectateMode> spectateMode : listedSpectateModes) {
        if(spectateMode != null) {
            //spectateMode.onEnable(); //not possible to enter
            Bukkit.getLogger().log(Level.CONFIG, spectateMode.getName() + " loaded");
        }
    }

}

private void addFromDir(File dir) {
    SPClassLoader loader = new SPClassLoader();

    Arrays.stream(Objects.requireNonNull(dir.listFiles())).forEach(jar -> {
        if(jar.getName().endsWith(".jar")) {
            if(!loader.findClasses(instance.getClassLoader(), jar, SpectateMode.class).isEmpty()) {
                listedSpectateModes.addAll(loader.findClasses(instance.getClassLoader(), jar, SpectateMode.class));
            }
        }
    });
}

SpectateMode class:
public abstract class SpectateMode {

/**
 * Do something when the SpectateMode get registered
 * For example registering an EventListener
 */
public abstract void onEnable();

/**
 * Returns the name of the SpectateMode
 *
 * @return the name of the SpectateMode
 */
public abstract String getName();

/**
 * Gets executed every Tick when a player has equipped this mode
 */
public abstract void execute(Spectator spectator);
}

Looking forward for a positive answer.
Greets.


text:
Q: $(f_n)$ a Cauchy sequence in $C[-1,1]$ in the $||\cdot||_1$ norm? $||\cdot||_{\infty}$ norm? Consider the sequnce of  functions $(f_n)$ in $C[-1,1]$ defined by $f_n(x)=x^{\frac{1}{2n+1}}$
Is $(f_n)$ a Cauchy sequence in $C[-1,1]$ in the $||\cdot||_1$ norm? Why?
Is $(f_n)$ a Cauchy sequence in $C[-1,1]$ in the $||\cdot||_{\infty}$ norm? Why?
So my attempt to prove it's Cauchy in  $||\cdot||_1$ norm:
$||f_n-f_m||_1=\int^1_{-1}x^{1/(2n+1)}-x^{1/(2m+1)}dx=\frac{x^{1/(2n+1)+1}}{1/(2n+1)+1}-\frac{x^{1/(2m+1)+1}}{1/(2m+1)+1}=$ $ \frac{(2n+1)x^{\frac{2n+2}{2n+1}}}{2n+2}\Big|^1_{-1}-\frac{(2m+1)x^{\frac{2m+2}{2m+1}}}{2m+2}\Big|^1_{-1}=\frac{2n+1}{n+1}-\frac{2m+1}{m+1}\to 0$ as $n\to \infty,m\to\infty$
So the sequence is cauchy
For the $||\cdot||_{\infty}$ norm:
$||f_n-f_m||_{\infty}=1$ So, it's not Cauchy
Would this be correcT?


text:
Q: Google Charts, sometimes it works and sometimes it does not? Google Charts works sometimes and sometimes it does not work! Please notice that I am using the same data in both cases ,no difference at all, when it does not work it throws a message error in the console.
I am sure that the problem is not happening from my side, it is happening from google side. Did this problem happen to anyone before and does it happen often?

A: There are many duplicate reports on this issue.  There seems to have been a bit of a problem with the loader system with caching browsers and caching proxies keeping redirects from the 'current' version during the latest release.
Switching to a fixed version (43 for before this update, or 44 for the new version) has been an effective workaround for most people.
This the Google Visualization team assures us this is a temporary issue, will solve itself as caches expire, and they'll look into solving the underlying problem before the next release.

A: the solution is to explicitly specify previous version of the API to load instead of using current:
-     google.charts.load('current', {'packages':['bar']});
+     google.charts.load('43', {'packages':['bar']});

Here is a link to a discussion about the new version v44 from Google Charts team.
From: https://stackoverflow.com/a/35648674/1857295


text:
Q: How to query for the occurrence of an element in the array in mongo DB aggregation pipeline
I'm using mongoose to connect to Mongo DB.

At first this is my schema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const TestSchema = new Schema({
  story: String,
  seenByUser: [String],
  medicationStage: {
    type: String,
    enum: [
      "no-medication",
      "just-after-medication",
      "towards-end-of-medication",
    ],
    required: true,
  },
});

// Compile model from schema
const TestModel = mongoose.model("Test", TestSchema);

module.exports = {
  Test: TestModel,
};

Here you can see I have a field called seenByUser which is an array of strings that is an array of user names. I'm setting up a data aggregation pipeline where I want to see given a user name fetch me all the documents where this user Name does not occur in seenByUser array. grouped by medicationStage. I'm unable to create this pipeline. Please help me out.

A: If I've undesrtood correctly you can try this aggregation:

*

*First $match where does not exists yourValue into the array seenByUser.

*Then $group by medicationStage. This create a nested array (because $push add the whole array)

*And $project to use $reduce and flat the array.

db.collection.aggregate({
  "$match": {
    "seenByUser": {
      "$ne": yourValue
    }
  }
},
{
  "$group": {
    "_id": "$medicationStage",
    "seenByUser": {
      "$push": "$seenByUser"
    }
  }
},
{
  "$project": {
    "_id": 0,
    "medicationStage": "$_id",
    "seenByUser": {
      "$reduce": {
        "input": "$seenByUser",
        "initialValue": [],
        "in": {
          "$concatArrays": [
            "$$value",
            "$$this"
          ]
        }
      }
    }
  }
})

Example here


text:
Q: Good Library for Creating E-mail Templates with Merge Ability I'm looking for a really good library/component/framework for creating e-mail templates for my web application.
We send out a number of e-mails on a regular basis:

*

*Activate Your Account

*Welcome

*Thanks for Your Order

*Etc.

I'd like to give the non-technical administrators of my web app a way to:

*

*See the current e-mail template (HTML, WYSIWYG)

*Make some minor modifications to copy, colors, etc.

*Preview, Test, Save, and "deploy" a new version of the e-mail template.

The tool needs to support "merge" fields.  For an example, see MailChimp.com.  They allow users to create e-mail templates and then specify any number of fields like this:
|FIELD1|
|FIELD2|
Then, when sending an e-mail, the developer passes-in the appropriate info for each field.
An example:

Hi *|FIRSTNAME|*,

Thanks for signing up.  You rule!

Best regards,
MyWebSite.com

Does anyone know of a tool like this that can plug into my ASP.NET / C# web app?  I assume someone out their wrote a library/component/something that I can license.
Thanks!

A: Try this one. It's free and open source:
http://mailsystem.codeplex.com/
It includes some classes specifically designed for mail merging
What's nice is that you can use its mail merging capabilities and still use system.net.mail for sending the email to avoid breaking your code.

A: Here is another option.
http://ntemplates.codeplex.com/


text:
Q: Uniform convergence implies Convergence in the mean If $f_n$ is a sequence of Riemann integrable functions on $[a,b]$ and f is Riemann integrable on $[a,b]$ we say that "$f_n$ converges in the mean to f" if $\lim_{n\to\infty} \int_{a}^{b} (f_n - f)^2 = 0$.
Show that if $f_n$ is uniformly convergent to f on $[a,b]$ then $f_n$ converges in the mean to f.
I know the definitions of uniformly convergent, namely that there exists N such that if $n \geq N$ then $|f_n(x) - f(x)| < \epsilon$. But where can I go from here?

A: Assume $(f_n)$ converge uniformly to $ f $ at $ [a b]$.
Let $\epsilon>0$ given.
$$\exists N\ge 0 : \forall n\ge N \;  \forall x\in[a,b] \;$$
$$ |f_n(x)-f(x)|<\sqrt{\frac{\epsilon}{b-a}}$$
$$\implies$$
$$\exists N\ge 0 : \forall n\ge N \; \forall x\in[a,b] \;$$
$$ (f_n(x)-f(x))^2<\frac{\epsilon}{b-a}$$
$$\implies$$
$$\exists N\ge 0 \; \;:\; \forall n\ge N \; \int_a^b(f_n(x)-f(x))^2dx<\epsilon$$
$$\implies$$
$$\lim_{n\to+\infty}\int_a^b(f_n(x)-f(x))^2dx=0$$


text:
Q: Do you put your database static data into source-control ? How? I'm using SQL-Server 2008 with Visual Studio Database Edition.
With this setup, keeping your schema in sync is very easy. Basically, there's a 'compare schema' tool that allow me to sync the schema of two databases and/or a database schema with a source-controlled creation script folder.
However, the situation is less clear when it comes to data, which can be of three different kind :

*

*static data referenced in the code. typical example : my users can change their setting, and their configuration is stored on the server. However, there's a system-wide default value for each setting that is used in case the user didn't override it. The table containing those default settings grows as more options are added to the program. This means that when a new feature/option is checked in, the system-wide default setting is usually created in the database as well.

*static data. eg. a product list populating a dropdown list. The program doesn't rely on the existence of a specific product in the list to work. This can be for example a list of unicode-encoded products that should be deployed in production when the new "unicode version" of the program is deployed.

*other data, ie everything else (logs, user accounts, user data, etc.)
It seems obvious to me that my third item shouldn't be source-controlled (of course, it should be backuped on a regular basis)
But regarding the static data, I'm wondering what to do.

*

*Should I append the insert scripts to the creation scripts?  or maybe use separate scripts?

*How do I (as a developer) warn the people doing the deployment that they should execute an insert statement ?

*Should I differentiate my two kind of data? (the first one being usually created by a dev, while the second one is usually created by a non-dev)
How do you manage your DB static data ?

A: I have explained the technique I used in my blog Version Control and Your Database. I use database metadata (in this case SQL Server extended properties) to store the deployed application version. I only have scripts that upgrade from version to version. At startup the application reads the deployed version from the database metadata (lack of metadata is interpreted as version 0, ie. nothing is yet deployed). For each version there is an application function that upgrades to the next version. Usually this function runs an internal resource T-SQL script that does the upgrade, but it can be something else, like deploying a CLR assembly in the database.
There is no script to deploy the 'current' database schema. New installments iterate trough all intermediate versions, from version 1 to current version.
There are several advantages I enjoy by this technique:

*

*Is easy for me to test a new version. I have a backup of the previous version, I apply the upgrade script, then I can revert to the previous version, change the script, try again, until I'm happy with the result.

*My application can be deployed on top of any previous version. Various clients have various deployed version. When they upgrade, my application supports upgrade from any previous version.

*There is no difference between a fresh install and an upgrade, it runs the same code, so I have fewer code paths to maintain and test.

*There is no difference between DML and DDL changes (your original question). they all treated the same way, as script run to change from one version to next. When I need to make a change like you describe (change a default), I actually increase the schema version even if no other DDL change occurs. So at version 5.1 the default was 'foo', in 5.2 the default is 'bar' and that is the only difference between the two versions, and the 'upgrade' step is simply an UPDATE statement (followed of course by the version metadata change, ie. sp_updateextendedproperty).

*All changes are in source control, part of the application sources (T-SQL scripts mostly).

*I can easily get to any previous schema version, eg. to repro a customer complaint, simply by running the upgrade sequence and stopping at the version I'm interested in.

This approach saved my skin a number of times and I'm a true believer now. There is only one disadvantage: there is no obvious place to look in source to find 'what is the current form of procedure foo?'. Because the latest version of foo might have been upgraded 2 or 3 versions ago and it wasn't changed since, I need to look at the upgrade script for that version. I usually resort to just looking into the database and see what's in there, rather than searching through the upgrade scripts.
One final note: this is actually not my invention. This is modeled exactly after how SQL Server itself upgrades the database metadata (mssqlsystemresource).

A: If you are changing the static data (adding a new item to the table that is used to generate a drop-down list) then the insert should be in source control and deployed with the rest of the code. This is especially true if the insert is needed for the rest of the code to work. Otherwise, this step may be forgotten when the code is deployed and not so nice things happen.
If static data comes from another source (such as an import of the current airport codes in the US), then you may simply need to run an already documented import process. The import process itself should be in source control (we do this with all our SSIS packages), but the data need not be.

A: Here at Red Gate we recently added a feature to SQL Data Compare allowing static data to be stored as DML (one .sql file for each table) alongside the schema DDL that is currently supported by SQL Compare.
To understand how this works, here is a diagram that explains how it works.
The idea is that when you want to push changes to your target server, you do a comparison using the scripts as the source data source, which generates the necessary DML synchronization script to update the target. This means you don't have to assume that the target is being recreated from scratch each time. In time we hope to support static data in our upcoming SQL Source Control tool.
David Atkinson, Product Manager, Red Gate Software

A: I really like your distinction of the three types of data.
I agree for the third.
In our application, we try to avoid putting in the database the first, because it is duplicated (as it has to be in the code, the database is a duplicate). A secondary benefice is that we need no join or query to get access to that value from the code, so this speed things up.

If there is additional information that we would like to have in the database, for example if it can be changed per customer site, we separate the two. Other tables can still reference that data (either by index ex: 0, 1, 2, 3 or by code ex: EMPTY, SIMPLE, DOUBLE, ALL).

For the second, the scripts should be in source-control. We separate them from the structure (I think they typically are replaced as time goes, while the structures keeps adding deltas).

How do I (as a developer) warn the people doing the deployment that they should execute an insert statement ?

We have a complete procedure for that, and a readme coming with each release, with scripts and so on...

A: I have come across this when developing CMS systems.
I went with appending the static data (the stuff referenced in the code) to the database creation scripts, then a separate script to add in any 'initialisation data' (like countries, initial product population etc).

A: For the first two steps, you could consider using an intermediate format (ie XML) for the data, then using a home grown tool, or something like CodeSmith to generate the SQL, and possible source files as well, if (for example) you have lookup tables which relate to enumerations used in the code - this helps enforce consistency.
This has another benefit that if the schema changes, in many cases you don't have to regenerate all your INSERT statements - you just change the tool.

A: See this thread's answer. Static data from your first two points should be in source control, IMHO.
Edit: *new

*

*all-in-one or a separate script? it does not really matter as long as you (dev team) agree with your deployment team. I prefer to separate files, but I still can always create all-in-one.sql from those in the proper order [Logins, Roles, Users; Tables; Views; Stored Procedures; UDFs; Static Data; (Audit Tables, Audit Triggers)]

*how do you make sure they execute it: well, make it another step in your application/database deployment documentation. If you roll out application which really needs specific (new) static data in the database, then you might want to perform a DB version check in your application. and you update the DB_VERSION to your new release number as part of that script. Then your application on a start-up should check it and report an error if the new DB version is required.

*dev and non-dev static data: I have never seen this case actually. More often there is real static data, which you might call "dev", which is major configuration, ISO static data etc. The other type is default lookup data, which is there for users to start with, but they might add more. The mechanism to INSERT these data might be different, because you need to ensure you do not destoy (power-)user-created data.

A: First off, I have never used Visual Studio Database Edition. You are blessed (or cursed) with whatever tools this utility gives you. Hopefully that includes a lot of flexibility.
I don't know that I'd make that big a difference between your type 1 and type 2 static data. Both are sets of data that are defined once and then never updated, barring subsequent releases and updates, right?  In which case the main difference is in how or why the data is as it is, and not so much in how it is stored or initialized.  (Unless the data is environment-specific, as in "A" for development, "B" for Production. This would be "type 4" data, and I shall cheerfully ignore it in this post, because I've solved it useing SQLCMD variables and they give me a headache.)
First, I would make a script to create all the tables in the database--preferably only one script, otherwise you can have a LOT of scripts lying about (and find-and-replace when renaming columns becomes very awkward).  Then, I would make a script to populate the static data in these tables.  This script could be appended to the end of the table script, or made it's own script, or even made one script per table, a good idea if you have hundreds or thousands of rows to load. (Some folks make a csv file and then issue a BULK INSERT on it, but I'd avoid that is it just gives you two files and a complex process [configuring drive mappings on deployment] to manage.)
The key thing to remember is that data (as stored in databases) can and will change over time.  Rarely (if ever!) will you have the luxury of deleting your Production database and replacing it with a fresh, shiny, new one devoid of all that crufty data from the past umpteen years. Databases are all about changes over time, and that's where scripts come into their own. You start with the scripts to create the database, and then over time you add scripts that modify the database as changes come along -- and this applies to your static data (of any type) as well.
(Ultimately, my methodology is analogous to accounting: you have accounts, and as changes come in you adjust the accounts with journal entries. If you find you made a mistake, you never go back and modify your entries, you just make a subsequent entries to reverse and fix them. It's only an analogy, but the logic is sound.)

A: The solution I use is to have create and change scripts in source control, coupled with version information stored in the database.
Then, I have an install wizard that can detect whether it needs to create or update the db - the update process is managed by picking appropriate scripts based on the stored version information in the database.


text:
Q: Get the selected item of a ListView how can I get the selected item (the object) from a ListView in WinRT?

A: Use the SelectedItem property. You can use binding:
<ListView x:Name="myListView" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />

Or you can access the property from code behind:
var item = myListView.SelectedItem;

If your SelectionMode isn't Single use SelectedItems instead.


text:
Q: Rancid err: failed router manufacturer: Permission Denied I'm having some trouble with my initial Rancid set up for my network config backups.
I am at the phase where I am attempting to use the rancid-run command to test. When the script completes, I will receive one of the following messages in the log entries:
sh: /usr/local/rancid/bin/rancid-fe: /root/localperl/bin/perl: Bad interpreter: Permission Denied
or
exec(rancid -t cisco) failed router manufacturer: Permission Denied
I did some research regarding the first error message and I found answers relating to the perl path inside of the rancid-fe scripts and other rancid scrips in the bin folder. The path #!/root/localperl/bin/perl was at the top of the "rancid-fe" script and a few other rancid scripts. Apparently this is not the correct path for perl (or the fact that it is in the root home prevents the rancid user from accessing it).
I modified that shebang to #!/usr/bin/perl in rancid-fe and that is when the second error began appearing inside of the generated log files. I am not entirely sure what "permissions" the error messages are referring to or how perl interacts with rancid. This is my first time dealing with rancid. I would like some help in fixing this issue or understanding the relationship between perl, rancid, and the error message so that I may move forward in troubleshooting.
I could not find any resources or insight into the second error, thus the thread title. Apologies if I missed anything or repeated an already answered question.
Additional Context:
Rancid version 3.9,
CentOS 6.9,
updated Perl 5.28.1 (installed from source),


text:
Q: ExternalInterface escapes strings using JSON conventions I'm getting hundreds of lines in my trace log per second!
WARNING: For content targeting Flash Player version 14 or higher, ExternalInterface escapes strings using JSON conventions. To maintain compatibility, content published to earlier Flash Player versions continues to use the legacy escaping behavior.
I already found a question on how to prevent this warning. However, I'm using SWC libraries for my SWF. So I don't have their source code. I need a way to suppress this warning. I don't mind turning all warnings/errors off for this SWF. Is there a way to stop it?

A: Try add debug=false to compiler options.


text:
Q: openCL strange NaNs occurrence I've run into a very strange behaviour with my openCL code again. In my code I have nodes, which are updated with some incremental learning rule which uses a gaussian to determine the weight.
The strange behaviour I am having now, is that when I only do a few update cycles, everything seems to work okay, however if I do more cycles, I sometimes start to get NaNs in my nodes.
The even funnier thing however is, that once I start to look for the cause of the NaNs by placing an "if (isnan(x))" in there, I do not get NaNs anymore.
I know that as a dirty hack I could just leave that test in there and hope that it will always prevent the NaNs from occuring, but I do not like that false solution, and I would really like to know where those come from.
All I am doing is some products and sums, as well as one gaussian (meaning exp). All the initials values are definetly not NaNs and in the next cycle only the results from the previous are used.
Where they could come from, or even just why they do not appear when I try to look for them?


text:
Q: How to Customize Bootstrap 4.3 from BootstrapCDN I'm trying to customize the Bootstrap 4.3 BootstrapCDN from the link from an external css file but I can't seem to do it.
I have positioned the custom css file below the bootstrap one which should override it. Does anybody know why this isn't working?
What I have
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">

EDIT:
I am trying to change the <nav class="navbar navbar-expand navbar-dark bg-dark"> class

A: If it is a class in bootstrap you want overridden, you would need to add something like this: .class {
   color:red !important;
}
It is basically saying like apply this style. It will have priority over other styles the same class has, regardless of order in your stylesheet.


text:
Q: Automatically detect by payload if POST, PUT or PATCH is needed I have a frontend TypeScript app that uses a RESTful api.
I have following domains there:
interface Foo {
  id: string;
  prop: string;
  anotherProp: string;
}

interface Bar {
  id: string;
  someProp: string;
  yetAnotherProp: string;
}

I also have some endpoints to create / update objects of this domain:
POST  - /api/foo
PUT   - /api/foo/{id}

POST  - /api/bar
PATCH - /api/bar/{id}

Now I want to detect if I need to call my endpoint with POST, PUT or PATCH.
Since the definition of POST is that I want to create a new object, I don't need an id. So that would be my condition. If my object has no property id, I call POST. Easy.
I'm struggling at making a difference for PUT and PATCH though. Since you use PUT if you send the whole object as payload, and use PATCH if you only send parts of the object (e.g. a Bar as { id: 1, someProp: 'value' } with yetAnotherProp missing), I thought about checking the object to have all available properties to be defined, and call PUT then.
But that would not work in case I want to call a PATCH with all properties changing.
What can I do here to detect what protocol I need in that situation?


text:
Q: Angular 2 api call promise array not resolving I'm using Angular 2 with TypeScript and experimenting with a Facebook SDK wrapper.
I need to resolve the Facebook data in a loop. Somehow my promise array is not resolving. But when I log the response from the api call, everything seems fine.
So I'm doing something wrong with the Promise handling.
Promise function:
getOrgData(): Promise<any> { // I ONLY NEED TO STORE THE ORGANISATION IDS, DONT NEED FB API FOR THAT ... ??? I DO NEED THE CATEGORIES, PLACE_TOPICS, EMAILS, ...
  let promiseArray: Array<any> = []
  for (var o in this.per50) {
    promiseArray.push(new Promise((resolve,reject) =>
      this._facebookService.api('/?ids=' + this.per50[o] + '&fields=id,name,category,category_list,place_topics,place_type,emails,phone,location&access_token='+ this.access_token)
      .then(
        (resp) => {
          console.log(resp);
          resolve(true)
        },
        (error) => this.errorMessage = error
      )
    ));
  }

  return Promise.all(promiseArray);
}

And I'm calling it like this:
this.getOrgData().then(
  resp => console.log(resp),
  error => console.log(error),
)

The reason of the for loop is that a Facebook api call can only handle 50 items at a time so I had to make an object containing an array of maximum 50 items.
So foreach array of 50 I'm doing a Facebook call. All that works fine ... It's just that the Promise array doesn't seem to get resolved. Anyone got an idea ?
I'm not really experienced with Promises and I'd prefer Observables but this Facebook SDK Wrapper works with Promises so ...
---------------------------SOLVED----------------------------
Apparently the promises were working fine but I didn't catch the errors of the Facebook Api call so I never got in the then() of the Facebook call so no resolving was happening, my bad.

A: use let instead of var in you for loop
for (let o in this.per50) {
    promiseArray.push(new Promise((resolve,reject) =>
      this._facebookService.api('/?ids=' + this.per50[o] + '&fields=id,name,category,category_list,place_topics,place_type,emails,phone,location&access_token='+ this.access_token)
      .then(
        (resp) => {
          console.log(resp);
          resolve(true)
        },
        (error) => this.errorMessage = error
      )
    ));
  }


text:
Q: Adding entries to HashMap become null after method ends I have this class:
    public class MyClass{

        private static Map<int[], Terrain> allTerrain = new HashMap<int[], Terrain>();

        public static void main(String[] args){
            populate();
            int[] test = {0, 0};
            System.out.println(allTerrain.get(test));
        }

        private static void populate() {
            for (int i=0; i<10; i++) {
                int[] index = {i, i};
                allTerrain.put(index, new Terrain());
            }
            int[] test = {0, 0};
            System.out.println(allTerrain.get(test));
        }

    }

Inside the method the allTerrain.get() method returns the instance of the object, but when I use allTerrain.get() outside of the method, it returns null for all the entries.
Everything runs on the main thread so concurrency is not a problem (I think).
Any ideas on how to fix this?

A: It's not retrieving the value from the allTerrain map both inside the scope and outside.
null
null

The problem, is that when you use an object for keys in a HashMap, it needs to implement hashcode and equals in a useful way. Arrays with the same values are not considered equal. Therefor they don't reference the same key
Boolean equal = new int[]{1, 2}.equals(new int[]{1, 2}) // is false

A: Using an array as a key to your map as you are doing won't work unfortunately.
Can a java array be used as a HashMap key
Perhaps try an Integer
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

A: Because arrays are equal only if they are the same object. One int[]{0,0} is not the same as another int[]{0,0}. You could define a type class for storing composite key or I'd say use lombok @value annotation, it creates sensible equals and hashCode method.


text:
Q: Ошибка при использовании calendar-telegram
Выдаёт ошибку!!!
ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body: [b'{"ok":false,"error_code":400,"description":"Bad Request: can\'t parse reply keyboard markup JSON object"}']"
https://github.com/unmonoqueteclea/calendar-telegram

import telebot
import traceback
import telegramcalendar
import datetime

class Bot:
    """docstring for bot"""
    def __init__(self, token):
        self.server_name="bot"
        self.tg=telebot.TeleBot(token=token)
        self.tg_m=telebot.types
    def sms(self,chat_id,text,parse_mode=None,reply_to_message_id=None,reply_markup=None):
        self.tg.send_message(chat_id=chat_id,text=text,parse_mode=parse_mode,reply_to_message_id=reply_to_message_id,reply_markup=reply_markup)
    def means(self,message):
        message=message
        try:
            Return=message
        except: Return=""
        if Return!="":
            chat_id=message.chat.id
            user_id=message.from_user.id
            message_id=message.message_id
            msg=message.text
            try:
                first_name=message.from_user.first_name
            except:
                first_name=""
            try:
                last_name=" "+message.from_user.last_name
            except:
                last_name=""
            return chat_id, user_id, message_id, first_name, last_name,msg
    def get(self,chat_id):
        r=self.tg.get_chat_members_count(chat_id=chat_id)
        return r
    def photo(self,chat_id,file_id=None,file_size=None,caption=None,parse_mode=None):
        self.tg.send_photo(chat_id=chat_id,photo=file_id,caption=caption,parse_mode=parse_mode)
    def button(self,text=None):
        R=self.tg_m.ReplyKeyboardMarkup(resize_keyboard=True,one_time_keyboard=True)
        R.row('/start','hello')
        return R
    def start(self):
        while True:
            try:
                @self.tg.message_handler(commands=['start'])
                def answer(message):
                    chat_id, user_id, message_id, first_name, last_name=self.means(message=message)
                    markup=self.button()
                    self.sms(chat_id=chat_id,text="Welcome my master.",reply_markup=markup)
                @self.tg.message_handler(commands=['calendar'])
                def calendar_handler(message):
                    chat_id, user_id, message_id, first_name, last_name, msg = self.means(message=message)
                    now = datetime.datetime.now() #Текущая дата
                    date = (now.year,now.month)
                    markup = telegramcalendar.create_calendar(now.year,now.month)
                    self.tg.send_message(chat_id=chat_id, text="Пожалуйста, выберите дату",reply_markup=markup)
                @self.tg.message_handler(content_type=["text"])
                def answer_1(message):
                    chat_id, user_id, message_id, first_name, last_name=self.means(message=message)
                    if message.text=='hello':
                        print("123")
                        self.sms(chat_id=chat_id,text="Hi.\nHow are you?")
                try:
                    self.tg.polling(none_stop=True,interval=0)

                except Exception as e:
                    try:
                        print(traceback.format_exc())
                        self.sms(chat_id="your_telegram_id",text="Error!\n"+traceback.format_exc())
                    except:
                        print(traceback.format_exc())
            except Exception as e:
                try:
                    print(traceback.format_exc())
                    self.sms(chat_id="your_telegram_id",text="Error!\n"+traceback.format_exc())
                except:
                    print(traceback.format_exc())

bot=Bot(token="token")
bot.start()

А это telegramcalendar.ру
from telegram import InlineKeyboardButton, InlineKeyboardMarkup,ReplyKeyboardRemove
import datetime
import calendar

def create_callback_data(action,year,month,day):
    """ Create the callback data associated to each button"""
    return ";".join([action,str(year),str(month),str(day)])

def separate_callback_data(data):
    """ Separate the callback data"""
    return data.split(";")

def create_calendar(year=None,month=None):
    """
    Create an inline keyboard with the provided year and month
    :param int year: Year to use in the calendar, if None the current year is used.
    :param int month: Month to use in the calendar, if None the current month is used.
    :return: Returns the InlineKeyboardMarkup object with the calendar.
    """
    now = datetime.datetime.now()
    if year == None: year = now.year
    if month == None: month = now.month
    data_ignore = create_callback_data("IGNORE", year, month, 0)
    keyboard = []
    #First row - Month and Year
    row=[]
    row.append(InlineKeyboardButton(calendar.month_name[month]+" "+str(year),callback_data=data_ignore))
    keyboard.append(row)
    #Second row - Week Days
    row=[]
    for day in ["Mo","Tu","We","Th","Fr","Sa","Su"]:
        row.append(InlineKeyboardButton(day,callback_data=data_ignore))
    keyboard.append(row)

    my_calendar = calendar.monthcalendar(year, month)
    for week in my_calendar:
        row=[]
        for day in week:
            if(day==0):
                row.append(InlineKeyboardButton(" ",callback_data=data_ignore))
            else:
                row.append(InlineKeyboardButton(str(day),callback_data=create_callback_data("DAY",year,month,day)))
        keyboard.append(row)
    #Last row - Buttons
    row=[]
    row.append(InlineKeyboardButton("<",callback_data=create_callback_data("PREV-MONTH",year,month,day)))
    row.append(InlineKeyboardButton(" ",callback_data=data_ignore))
    row.append(InlineKeyboardButton(">",callback_data=create_callback_data("NEXT-MONTH",year,month,day)))
    keyboard.append(row)

    return InlineKeyboardMarkup(keyboard)

def process_calendar_selection(bot,update):
    """
    Process the callback_query. This method generates a new calendar if forward or
    backward is pressed. This method should be called inside a CallbackQueryHandler.
    :param telegram.Bot bot: The bot, as provided by the CallbackQueryHandler
    :param telegram.Update update: The update, as provided by the CallbackQueryHandler
    :return: Returns a tuple (Boolean,datetime.datetime), indicating if a date is selected
                and returning the date if so.
    """
    ret_data = (False,None)
    query = update.callback_query
    (action,year,month,day) = separate_callback_data(query.data)
    curr = datetime.datetime(int(year), int(month), 1)
    if action == "IGNORE":
        bot.answer_callback_query(callback_query_id= query.id)
    elif action == "DAY":
        bot.edit_message_text(text=query.message.text,
            chat_id=query.message.chat_id,
            message_id=query.message.message_id
            )
        ret_data = True,datetime.datetime(int(year),int(month),int(day))
    elif action == "PREV-MONTH":
        pre = curr - datetime.timedelta(days=1)
        bot.edit_message_text(text=query.message.text,
            chat_id=query.message.chat_id,
            message_id=query.message.message_id,
            reply_markup=create_calendar(int(pre.year),int(pre.month)))
    elif action == "NEXT-MONTH":
        ne = curr + datetime.timedelta(days=31)
        bot.edit_message_text(text=query.message.text,
            chat_id=query.message.chat_id,
            message_id=query.message.message_id,
            reply_markup=create_calendar(int(ne.year),int(ne.month)))
    else:
        bot.answer_callback_query(callback_query_id= query.id,text="Something went wrong!")
        # UNKNOWN
    return ret_data


text:
Q: Pick Active Date in a Web Page with Selenium (Python) I am trying to get the data from this web page  https://rapor.epias.com.tr/rapor/xhtml/ptfSmfListeleme.xhtml
As you can see I need to pick a beginning and end date and get the data. But the problem is when u open the calendar you can see the non-active days too especially at the final date.
I write a code for the beginning date and it is worked well but it is not practical.
import re
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
url = r'https://rapor.epias.com.tr/rapor/xhtml/ptfSmfListeleme.xhtml'

driver = webdriver.Chrome(r'...\chromedriver.exe')
driver.get(url)
link = driver.find_element_by_xpath('//*[@id="PmumBI:baslangicTarih"]/button/span[1]')
link.click()
while True:
    try:
        input_date = driver.find_element_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr[1]/td[1]/a')
        input_date.click()
    except:
        try:
            input_date = driver.find_element_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr[1]/td[2]/a')
            input_date.click()
        except:
            try:
                input_date = driver.find_element_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr[1]/td[3]/a')
                input_date.click()
            except:
                try:
                    input_date = driver.find_element_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr[1]/td[4]/a')
                    input_date.click()
                except:
                    try:
                        input_date = driver.find_element_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr[1]/td[5]/a')
                        input_date.click()
                    except:
                        try:
                            input_date = driver.find_element_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr[1]/td[6]/a')
                            input_date.click()
                        except:
                            try:
                                input_date = driver.find_element_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr[1]/td[7]/a')
                                input_date.click()
                            except:
                                break

But I if I want to use the same for the final date I have to create more then 7 try code. Is there any way to make this simple, Like choosing between the active dates?

A: Instead of :
while True:

You can use a for loop and use the index inside your xpath expression :
for i in range(20):
    try:
        input_date = driver.find_element_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr[1]/td[' +str(i)+']/a')
        input_date.click()
        break
    except:
        pass

Hope it'll help !


text:
Q: Yii CDbConnection failed to open the DB connection: could not find driver with google cloud sql I'm having an issue with Yii and a mysql database running on Google Cloud sql.
Quick overview:
We have moved this from an existing server where it all worked with no issues at all and have now set up a Google Compute Engine server with php and all the relivant drivers mysql_pdo being one of them. We also have a Google Cloud SQL database storing all of our existing database information.
What I have tried
I have written a simple php script which uses
PDO('mysql:<IPADDRESS>;dbname=<MYDBNAME>,'MYUSERNAME','MYPASSWORD'); and this connects absolutely fine and can read tables and return data.
The Issue
As soon as I do the same in yii in the config/main.php it does not seem to work and get the error: CDbConnection failed to open the DB connection: could not find driver
Here is the yii connection string
'db'=>array(
                    'connectionString' =>'mysql:host=my.server.ip.address;dbname=my_db_name',
                    'emulatePrepare' => true,
                    'username' => 'my_username',
                    'password' => 'my_passsword',
                    'charset' => 'utf8',
            ),

I've also run the yii requirements script and it all returns as passed for the mysql PDO functions.

Any help would be greatly appreciated.
Thanks,

A: Aha answering my own question:
The server needs to have sqlite PDO extension as well as the MySQL PDO extension. And now all working perfectly!
So it's worthwhile checking you phpinfo for this
You can add it according to this answer: https://superuser.com/a/320914
or via your php.ini uncomment the following:
extension=php_pdo_sqlite.dll

extension=php_sqlite.dll

Hope this helps other people

A: Not sure if this could be related... I had "Permission Denied" issues connecting to Cloud SQL via a CentOS 7 GCE.
Found out it had to do with SELinux and found the following solution: Connect DATABASE Error TYPE: 2002: Permission denied
Basically setsebool -P httpd_can_network_connect_db 1
That solved my problem without disabling SELinux.
Hope it helps whoever reads this.


text:
Q: Uniformly distributed VAE samples I am currently working on a VAE to generate images (for simplicity MNIST).
If I understand the theory correctly, the latent variables follow a gaussian normal distribution in the dimensions of the latent space. To generate images we take a random sample $z$ from a standard normal distribution and feed this to the decoder.
Looking at images that are generated from VAEs (like in this tensorflow tutorial) the distribution of the different generated classes does not match the distribution of classes of training images (in this example 7/16 images are instances of "9"):

If I look at any of the various visualizations of the latent space (e.g. here) it seems like the projections center around 0, so sampling from a gaussian distribution will put more weight on centered projections right? Does this cause the described bias?

For my use-case it is important to sample the trained classes uniformly distributed. I know about the Conditional VAE but I don't know the labels at the time of sampling.
My questions are:

*

*As the distribution for the latent variables is parameterized by the mean and variance generated by the encoder why do we assume this follows a standard normal distribution and use this to generate samples? Also, why do the latent space visualization then not look more like 2-dimensional standard normal distributions?

*Is there a way to sample the latent variables for the different classes uniformly distributed (e.g. generate about the same times "1"s than "5"s)?

*Can the latent space be estimated or known so that a uniform distribution or a gaussian distribution with higher variance could be used to generate $z$ values for the image generation?


text:
Q: Why does my custom DataSource getConnection() throw "SQLException: The url cannot be null"? I am writing a Spring Boot (Batch) application, that should exit with a specific exit code. A requirement is to return an exit code, when the database cannot be connected.
My approach is to handle this exception as early as possible by explicitly creating a DataSource bean, calling getConnection() and catch and throw a custom exception that implements ExitCodeGenerator. The configuration is as follows:
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
...
@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSourceProperties dataSourceProps() {
    return new DataSourceProperties();
}

@Bean
@ConfigurationProperties("spring.datasource")
public DataSource customDataSource(DataSourceProperties props) {

    DataSource ds = props.initializeDataSourceBuilder().create().build();

    try {
        ds.getConnection();

    } catch (SQLException e) {
        throw new DBConnectionException(e); // implements ExitCodeGenerator interface
    }

    return ds;
}
...
}

I want to reuse as much of the Spring Boot Autoconfiguration as possible, thats why I use the @ConfigurationProperties. I do not know if this is the way to go.
A call on DataSourceProperties.getUrl() returns the configured url (from my properties file):
spring.datasource.url=jdbc:oracle:....

But why does Spring Boot throw this exception when I call DataSource.getConnection():
java.sql.SQLException: The url cannot be null
at java.sql.DriverManager.getConnection(DriverManager.java:649) ~[?:1.8.0_141]
at java.sql.DriverManager.getConnection(DriverManager.java:208) ~[?:1.8.0_141]
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:308) ~[tomcat-jdbc-8.5.15.jar:?]
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:203) ~[tomcat-jdbc-8.5.15.jar:?]
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:735) ~[tomcat-jdbc-8.5.15.jar:?]
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:667) ~[tomcat-jdbc-8.5.15.jar:?]
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:482) [tomcat-jdbc-8.5.15.jar:?]
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:154) [tomcat-jdbc-8.5.15.jar:?]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:118) [tomcat-jdbc-8.5.15.jar:?]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:107) [tomcat-jdbc-8.5.15.jar:?]
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:131) [tomcat-jdbc-8.5.15.jar:?]
at com.foo.bar.BatchConfiguration.customDataSource(BatchConfiguration.java:xxx) [main/:?]
...

Or do you know some cleaner way of handling this situation?
Thanks
Edit: Spring Boot version is 1.5.4

A: The error is subtle and lies in the line
DataSource ds = props.initializeDataSourceBuilder().create().build();

The create() creates a new DataSourceBuilder and erases the preconfigured properties.
props.initializeDataSourceBuilder() already returns a DataSourceBuilder with all the properties (url, username etc.) set. So you only have to add new properties or directly build() it. So the solution is removing create():
DataSource ds = props.initializeDataSourceBuilder().build();

In this context the dataSourceProps() method bean can be removed too.

A: It looks like you dont set any value to your Datasource.
props.initializeDataSourceBuilder().create().build(); does not set the values of your properties to your datasource. It just creates and builds one.
Try to set your values manually by using the static DataSourceBuilder. You will get the values from your dataSourceProps bean like that:
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
...
@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSourceProperties dataSourceProps() {
    return new DataSourceProperties();
}

@Bean
@ConfigurationProperties("spring.datasource")
public DataSource customDataSource(DataSourceProperties props) {

      DataSource ds = DataSourceBuilder.create()
            .driverClassName(dataSourceProps().getDriverClassName())
            .url(dataSourceProps().getUrl())
            .username(dataSourceProps().getUsername())
            .password(dataSourceProps().getPassword())
            .build();

    try {
        ds.getConnection();

    } catch (SQLException e) {
        throw new DBConnectionException(e); // implements ExitCodeGenerator interface
    }

    return ds;
}
...
}