text:
Q: How to set default scheme for Openiddict-core tables in EF Core How can I set default scheme for Openiddict-core tables?
Unfortunately EF Core does't have (not that I know) a method that would accept only scheme and (EntityTypeBuilder.ToTable) requires also table name, beside scheme.

A: There's nothing OpenIddict-specific to handle that, but it's easily achievable using the regular EF hooks. Here's an example:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions options)
        : base(options) { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        foreach (var entity in builder.Model.GetEntityTypes())
        {
            for (var type = entity; type != null; type = type.BaseType)
            {
                if (type.ClrType.Assembly == typeof(OpenIddictApplication).Assembly)
                {
                    entity.SqlServer().Schema = "security";

                    break;
                }
            }
        }
    }
}


text:
Q: Extracted pdf text is not getting displayed in console I am trying to extract the pdf text using Tabula. But the code has no errors but when i run the extracted pdf text does not get displayed in console. Could some one help.
I have been using PDFBox and after doing some research, i have found that tabula is new and wanted to try it.
File file = new File(pdfFilePath);
PDDocument document = PDDocument.load(file);
ObjectExtractor oe = new ObjectExtractor(document);
Page page = oe.extract(1) //1st page
TextStripper textStripper = new TextStripper(document,1);
System.out.println(textStripper.getText(document));

output of pdf text

A: You are not using the page variable. Try the following code.
File file = new File(pdfFilePath);
PDDocument document = PDDocument.load(file);
ObjectExtractor oe = new ObjectExtractor(document);
Page page = oe.extract(1); // 1st page

for (TextElement textElement: page.getText()) {
  System.out.print(textElement.getText());
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use useEffect inside a handler or vice versa? I have a function which is handler of onChange and get value of input
and also I have a function for search in an array using searched value coming from that input
and render a component that contains searched array as props.
But I have a problem
when I search it works but after second letter and when the input is empty it shows the last search.
I think it should be handled with useEffect but I dont how to solve or may be I am wrong
I need help to correct that
thanks for your help.
these are my code :
getting search value part and sending as argument :
function BasePage({handleClick, handleSearch }) {

    const [searchValue, setSearchValue] = useState('');

    useEffect(() => {
        function handleChangeSearchInput(e) {
        const newSearchValue = e.target.value;
        setSearchValue(newSearchValue);
        handleSearch(searchValue);
    }
    })

    return (

            <fieldset>
        <legend>Search</legend>
        <input
            value = {searchValue}
            onChange = {handleChangeSearchInput}
            placeholder = "Enter name to search"
            type = "text"
            />
                <button onClick={() => handleClick('add-record-form')}>Add</button>
    </fieldset>

            {searchValue.length > 0 && <SearchRecord record = {searchValue} />}

    );
}

and this filters in parent component :

function handleSearch(searchValue) {
       const searchedTerm = contacts.filter(contact => (contact.name.toLowerCase().includes(searchValue.toLowerCase())));
        setSearchTerms(searchedTerm);
    }

and I use map to show them .

A: You shouldn't need useEffect for this. Just have the handler deal with both the setting of state, and the updating.
function handleChangeSearchInput(e) {
  const newSearchValue = e.target.value;
  setSearchValue(newSearchValue);
  handleSearch(newSearchValue);
}


text:
Q: Why is tape.gradient returning None? I am trying to create an adversarial example using this function:
def create_adversarial_pattern(input_image, input_label):
    input_image = tf.cast(input_image, tf.float32)

    with tf.GradientTape() as tape:
        tape.watch(input_image)
        predcition = model(input_image)
        loss = loss_object(input_label, prediction)

    gradient = tape.gradient(loss, input_image) # <------- this line
    signedgrad = tf.sign(gradient)
    return signed_grad

but the gradient variable has a value of None which is obviously not great. GradientTape.gradient is supposed to return something. This is the implementation of the function
#load image
image = load_img(test_dir + "0/1-30226-A-0.wav.png")
print("Image: " + str(type(image)))

arr = img_to_array(image)
print("Array No. 1: " + str(type(arr)) + " : " + str(arr.shape))

arr /= 255.0

#predict image
arr_ = []
arr_.append(arr)
arr_ = np.array(arr_)
print("Array No. 2: " + str(type(arr_)) + " : " + str(arr_.shape))

prediction = model.predict(arr_)
image_label = prediction.tolist().index(max(prediction.tolist()))

image_label_arr = []
image_label_arr.append(image_label)
image_label_arr = np.array(image_label_arr)

image_label_arr = tf.keras.utils.to_categorical(image_label_arr, len(classes))

print(classes[image_label] + " : " + str(image_label))
print(image_label_arr)

#create example
perturbations = create_adversarial_pattern(arr.reshape((1, 128, 216, 3)), image_label_arr).numpy

this is the model I am using
def create_model():
    model = Sequential()
    model.add(Conv2D(32, (3,3), input_shape = array_image.shape))
    model.add(Activation("relu"))
    model.add(MaxPooling2D())

    model.add(Conv2D(32, (3, 3)))
    model.add(Activation("relu"))
    model.add(MaxPooling2D())

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation("relu"))
    model.add(MaxPooling2D())

    model.add(Flatten())
    model.add(Dense(1024))
    model.add(Activation("relu"))
    model.add(Dropout(0.5))
    model.add(Dense(numberOfClass)) #output
    model.add(Activation("softmax"))
    model.compile(loss = "categorical_crossentropy",
             optimizer = "rmsprop",
             metrics = ["accuracy"])
    return model

A: I've made some fixes to your code (see the comments inside the code). It should work as expected.
import tensorflow as tf
import numpy as np
from tensorflow.keras.utils import img_to_array
from tensorflow import keras
from tensorflow.keras import Sequential
from keras.layers import Conv2D, Dropout, MaxPooling2D, Flatten, Dense, Activation

# using a loss function
loss_fn = tf.keras.losses.CategoricalCrossentropy(from_logits=True)

def create_adversarial_pattern(input_image, input_label):
    input_image = tf.cast(input_image, tf.float32)

    with tf.GradientTape() as tape:
        tape.watch(input_image)
        prediction = model(input_image)  # you had a typo here
        loss = loss_fn(input_label, prediction)

    gradient = tape.gradient(loss, input_image) # <------- this line
    print("grad {}".format(gradient))
    signed_grad = tf.sign(gradient)  # another typo here
    return signed_grad

# dummy image
image = np.ones((960, 640, 3))
print("Image: " + str(type(image)))

arr = img_to_array(image)
print("Array No. 1: " + str(type(arr)) + " : " + str(arr.shape))

arr /= 255.0

#predict image
arr_ = []
arr_.append(arr)
arr_ = np.array(arr_)
print("Array No. 2: " + str(type(arr_)) + " : " + str(arr_.shape))

def create_model():
    model = Sequential()
    model.add(Conv2D(32, (3,3), input_shape = arr.shape))
    model.add(Activation("relu"))
    model.add(MaxPooling2D())

    model.add(Conv2D(32, (3, 3)))
    model.add(Activation("relu"))
    model.add(MaxPooling2D())

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation("relu"))
    model.add(MaxPooling2D())

    model.add(Flatten())
    model.add(Dense(100))
    model.add(Activation("relu"))
    model.add(Dropout(0.5))
    model.add(Dense(3)) #output
    model.add(Activation("softmax"))
    model.compile(loss = "categorical_crossentropy",
             optimizer = "rmsprop",
             metrics = ["accuracy"])
    return model

model = create_model()
prediction = model.predict(arr_)
image_label = prediction.tolist().index(max(prediction.tolist()))

classes = ["0","1","2"]   # I used this classes, you should use yours

image_label_arr = []
image_label_arr.append(image_label)
image_label_arr = np.array(image_label_arr)

image_label_arr = tf.keras.utils.to_categorical(image_label_arr, len(classes))

print(classes[image_label] + " : " + str(image_label))
print(image_label_arr)

#create example

# here I've put arr inside a list, because you have loaded only an image
# and arr has shape (width, height, channels), but model is expecting
# (n_samples_in_batch, width, height, channels)
perturbations = create_adversarial_pattern([arr], image_label_arr).numpy

The line print("grad {}".format(gradient)) gives the following output:
grad [[[[-1.5513586e-05  3.8307126e-06 -5.2626692e-05]
   [-7.3845486e-06 -7.5844241e-06 -1.0758981e-05]
   [ 4.7415083e-06  1.5906917e-06 -2.9444196e-05]
   ...
   [ 0.0000000e+00  0.0000000e+00  0.0000000e+00]
   [ 0.0000000e+00  0.0000000e+00  0.0000000e+00]
   [ 0.0000000e+00  0.0000000e+00  0.0000000e+00]]

  [[ 1.4568100e-06 -5.4016291e-06  6.4816072e-06]
   [-2.6765707e-05 -1.3100296e-05 -1.7976803e-05]
   [-5.2032774e-05 -2.8514034e-05  1.9507925e-05]
   ...
   [ 0.0000000e+00  0.0000000e+00  0.0000000e+00]
   [ 0.0000000e+00  0.0000000e+00  0.0000000e+00]
   [ 0.0000000e+00  0.0000000e+00  0.0000000e+00]]

  [[ 2.9544193e-05 -7.5485059e-06 -6.0243669e-06]
   [ 3.0723353e-05  3.2532912e-06 -4.3765580e-05]
   [-1.6096277e-05  3.5667676e-06  1.3662253e-05]
   ...


text:
Q: Shapes getting distorted while displaying in LCD I am trying to display a circle in my 800*480 LCD (TIANMA). But an oval shape is getting displayed instead of circle.
The length of LCD is 15.5 cm. Assuming square pixels length to breadth ratio should be 800/480. From this I got breadth as 9.3 cm but actual breadth is 8.3 cm.
Is it because of this problem the figure is getting distorted.
I have tried with Ampire LCD (640*480) with length breadth of same ratio.
It is displaying exact dimensions.

A: You need to pay attention to the specs for your two displays. The first is an 800 x 480, while the second (which acts as you expect) is a 640 x 480.
Your problem is not that the display pixels are not square - they are. It's just that you're sending drive signals which only display 640 pixels in a line. The problem child is looking at this signal and modifying the signal so that a line of 640 pixels is mapped onto 800 pixels, and the original pixels are getting stretched to fit in the display.
The display has no way of knowing what aspect ratio you want, and it's assuming you want to use the entire width of the display. Since you're smarter than an LCD display, it's up to you to cater to its limitations, not the other way around. Reformat your display driver to provide an 800 x 480 display and you'll be fine. Of course, you'll probably give your 640 x 480 display heartburn, but that can't be helped.

A: https://msdn.microsoft.com/en-us/library/cc294571.aspx
I got this link which explains my problem. But don't know how to overcome this .
I may have to change my pixel ratio of each picture I am using and scale each shape proportionately. I would rather prefer to use a different LCD with pixel aspect ratio 1:1.
https://helpx.adobe.com/photoshop/using/creating-images-video.html


text:
Q: Magento 2 Category page add custom view mode On category page I want to add addition view mode as "expand" with "grid" and "list" mode.

If any one has created custom view mode for category page then help.

A: I have tried to find solution to create custom view mode on category page. But no luck :(
So, I have check core files of magento 2. From where the view mode add, and I got idea how to create new mode. Below are the steps I have performed to create module.

Step #1: Created a module registration file
  app/code/Darsh/Expandmode/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Darsh_Expandmode', __DIR__
);

Step #2: Created a composer.json file
  app/code/Darsh/Expandmode/composer.json

{
    "name": "darsh/magento2-expandmode",
    "description": "Category page custom view mode",
    "version": "1.0.0",
    "require": {
        "magento/module-backend": "~100.0.0"
    },
    "type": "magento2-module",
    "extra": {
        "map": [
            [
                "*",
                "Darsh/Expandmode"
            ]
        ]
    }
}

Step #3: Created a module.xml file
  app/code/Darsh/Expandmode/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Darsh_Expandmode" setup_version="1.0.0" >
    </module>
</config>

Step #4: Created a di.xml file to overwrite core magento
  functionality. app/code/Darsh/Expandmode/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Model\Config\Source\ListMode" type="Darsh\Expandmode\Model\Config\Source\ListMode" />
    <preference for="Magento\Catalog\Helper\Product\ProductList" type="Darsh\Expandmode\Helper\Product\ProductList" />
</config>

Step #5: Created a ListMode.php file to overwrite core magento
  functionality.
  app/code/Darsh/Expandmode/Model/Config/Source/ListMode.php

<?php
namespace Darsh\Expandmode\Model\Config\Source;

class ListMode extends \Magento\Catalog\Model\Config\Source\ListMode
{
    /**
     * {@inheritdoc}
     *
     * @codeCoverageIgnore
     */
    public function toOptionArray()
    {
        return [
            ['value' => 'grid', 'label' => __('Grid Only')],
            ['value' => 'list', 'label' => __('List Only')],
            ['value' => 'grid-list', 'label' => __('Grid (default) / List')],
            ['value' => 'list-grid', 'label' => __('List (default) / Grid')],
            ['value' => 'list-grid-expand', 'label' => __('Expand (default) / List / Grid')]
        ];
    }

}

Step #6: Created a ProductList.php file to overwrite core magento
  functionality.
  app/code/Darsh/Expandmode/Helper/Product/ProductList.php

<?php
namespace Darsh\Expandmode\Helper\Product;

class ProductList extends \Magento\Catalog\Helper\Product\ProductList
{
     /**
     * List mode configuration path
     */
    const XML_PATH_LIST_MODE = 'catalog/frontend/list_mode';

    const VIEW_MODE_LIST = 'list';
    const VIEW_MODE_GRID = 'grid';

    const DEFAULT_SORT_DIRECTION = 'asc';
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * @var \Magento\Framework\Registry
     */
    private $coreRegistry;

    /**
     * Default limits per page
     *
     * @var array
     */
    protected $_defaultAvailableLimit  = [10 => 10,20 => 20,50 => 50];

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Registry $coreRegistry = null
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->coreRegistry = $coreRegistry ?: \Magento\Framework\App\ObjectManager::getInstance()->get(
            \Magento\Framework\Registry::class
        );
    }

    /**
     * Returns available mode for view
     *
     * @return array|null
     */
    public function getAvailableViewMode()
    {
        $value = $this->scopeConfig->getValue(
            self::XML_PATH_LIST_MODE,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        switch ($value) {
            case 'grid':
                $availableMode = ['grid' => __('Grid')];
                break;

            case 'list':
                $availableMode = ['list' => __('List')];
                break;

            case 'grid-list':
                $availableMode = ['grid' => __('Grid'), 'list' =>  __('List')];
                break;

            case 'list-grid':
                $availableMode = ['list' => __('List'), 'grid' => __('Grid')];
                break;

            case 'list-grid-expand':
                $availableMode = ['expand' => __('Expand'), 'list' => __('List'), 'grid' => __('Grid')];
                break;
            default:
                $availableMode = null;
                break;
        }
        return $availableMode;
    }

    /**
     * Returns default view mode
     *
     * @param array $options
     * @return string
     */
    public function getDefaultViewMode($options = [])
    {
        if (empty($options)) {
            $options = $this->getAvailableViewMode();
        }
        return current(array_keys($options));
    }

    /**
     * Get default sort field
     *
     * @return null|string
     */
    public function getDefaultSortField()
    {
        $currentCategory = $this->coreRegistry->registry('current_category');
        if ($currentCategory) {
            return $currentCategory->getDefaultSortBy();
        }

        return $this->scopeConfig->getValue(
            \Magento\Catalog\Model\Config::XML_PATH_LIST_DEFAULT_SORT_BY,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    /**
     * Retrieve available limits for specified view mode
     *
     * @param string $mode
     * @return array
     */
    public function getAvailableLimit($mode)
    {
        if (!in_array($mode, [self::VIEW_MODE_GRID, self::VIEW_MODE_LIST])) {
            return $this->_defaultAvailableLimit;
        }
        $perPageConfigKey = 'catalog/frontend/' . $mode . '_per_page_values';
        $perPageValues = (string)$this->scopeConfig->getValue(
            $perPageConfigKey,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $perPageValues = explode(',', $perPageValues);
        $perPageValues = array_combine($perPageValues, $perPageValues);
        if ($this->scopeConfig->isSetFlag(
            'catalog/frontend/list_allow_all',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        )) {
            return ($perPageValues + ['all' => __('All')]);
        } else {
            return $perPageValues;
        }
    }

    /**
     * Retrieve default per page values
     *
     * @param string $viewMode
     * @return string (comma separated)
     */
    public function getDefaultLimitPerPageValue($viewMode)
    {
        if ($viewMode == self::VIEW_MODE_LIST) {
            return $this->scopeConfig->getValue(
                'catalog/frontend/list_per_page',
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            );
        } elseif ($viewMode == self::VIEW_MODE_GRID) {
            return $this->scopeConfig->getValue(
                'catalog/frontend/grid_per_page',
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            );
        }
        return 0;
    }

}

Step #7: Applied changes in layout section
  app/code/Darsh/Expandmode/view/frontend/layout/catalog_category_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <referenceBlock name="category.products.list" template="Darsh_Expandmode::product/list.phtml" />

</page>

Step #8: Applied changes in layout section
  app/code/Darsh/Expandmode/view/frontend/templates/product/list.phtml

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
use Magento\Framework\App\Action\Action;

// @codingStandardsIgnoreFile

?>
<?php
/**
 * Product list template
 *
 * @var $block \Magento\Catalog\Block\Product\ListProduct
 */
?>
<?php
$_productCollection = $block->getLoadedProductCollection();
$_helper = $this->helper('Magento\Catalog\Helper\Output');
?>
<?php if (!$_productCollection->count()): ?>

<?= /* @escapeNotVerified */ __('We can\'t find products matching the selection.') ?>

<?php else: ?>
    <?= $block->getToolbarHtml() ?>
    <?= $block->getAdditionalHtml() ?>
    <?php
    if ($block->getMode() == 'grid') {
        $viewMode = 'grid';
        $imageDisplayArea = 'category_page_grid';
        $showDescription = false;
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
    } elseif ($block->getMode() == 'expand') {
        $viewMode = 'expand';
        $imageDisplayArea = 'category_page_list';
        $showDescription = true;
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::FULL_VIEW;
    }else{
        $viewMode = 'list';
        $imageDisplayArea = 'category_page_list';
        $showDescription = true;
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::FULL_VIEW;
    }
    /**
     * Position for actions regarding image size changing in vde if needed
     */
    $pos = $block->getPositioned();
    ?>
    <div class="products wrapper <?= /* @escapeNotVerified */ $viewMode ?> products-<?= /* @escapeNotVerified */ $viewMode ?>">

            <?php /** @var $_product \Magento\Catalog\Model\Product */ ?>
            <?php foreach ($_productCollection as $_product): ?>

                <div class="product-item-info" data-container="product-<?= /* @escapeNotVerified */ $viewMode ?>">
                    <?php
                    $productImage = $block->getImage($_product, $imageDisplayArea);
                    if ($pos != null) {
                        $position = ' style="left:' . $productImage->getWidth() . 'px;'
                            . 'top:' . $productImage->getHeight() . 'px;"';
                    }
                    ?>
                    <?php // Product Image ?>
                    <a href="<?= /* @escapeNotVerified */ $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
                        <?= $productImage->toHtml() ?>

                        <?php
                            $_productNameStripped = $block->stripTags($_product->getName(), null, true);
                        ?>

                            <a class="product-item-link"
                               href="<?= /* @escapeNotVerified */ $_product->getProductUrl() ?>">
                                <?= /* @escapeNotVerified */ $_helper->productAttribute($_product, $_product->getName(), 'name') ?>

                        <?= $block->getReviewsSummaryHtml($_product, $templateType) ?>
                        <?= /* @escapeNotVerified */ $block->getProductPrice($_product) ?>
                        <?= $block->getProductDetailsHtml($_product) ?>

                            <div class="product actions product-item-actions"<?= strpos($pos, $viewMode . '-actions') ? $position : '' ?>>
                                <div class="actions-primary"<?= strpos($pos, $viewMode . '-primary') ? $position : '' ?>>
                                    <?php if ($_product->isSaleable()): ?>
                                        <?php $postParams = $block->getAddToCartPostParams($_product); ?>
                                        <form data-role="tocart-form" data-product-sku="<?= $block->escapeHtml($_product->getSku()) ?>" action="<?= /* @NoEscape */ $postParams['action'] ?>" method="post">
                                            <input type="hidden" name="product" value="<?= /* @escapeNotVerified */ $postParams['data']['product'] ?>">
                                            <input type="hidden" name="<?= /* @escapeNotVerified */ Action::PARAM_NAME_URL_ENCODED ?>" value="<?= /* @escapeNotVerified */ $postParams['data'][Action::PARAM_NAME_URL_ENCODED] ?>">
                                            <?= $block->getBlockHtml('formkey') ?>
                                            <button type="submit"
                                                    title="<?= $block->escapeHtml(__('Add to Cart')) ?>"
                                                    class="action tocart primary">
                                                <?= /* @escapeNotVerified */ __('Add to Cart') ?>
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <?php if ($_product->isAvailable()): ?>

<?= /* @escapeNotVerified */ __('In stock') ?>

                                        <?php else: ?>

<?= /* @escapeNotVerified */ __('Out of stock') ?>

                                        <?php endif; ?>
                                    <?php endif; ?>

                                <div data-role="add-to-links" class="actions-secondary"<?= strpos($pos, $viewMode . '-secondary') ? $position : '' ?>>
                                    <?php if ($addToBlock = $block->getChildBlock('addto')): ?>
                                        <?= $addToBlock->setProduct($_product)->getChildHtml() ?>
                                    <?php endif; ?>

                            <?php if ($showDescription):?>

                                    <?= /* @escapeNotVerified */ $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                                    <a href="<?= /* @escapeNotVerified */ $_product->getProductUrl() ?>" title="<?= /* @escapeNotVerified */ $_productNameStripped ?>"
                                       class="action more"><?= /* @escapeNotVerified */ __('Learn More') ?>

                            <?php endif; ?>

            <?php endforeach; ?>

    <?= $block->getToolbarHtml() ?>
    <?php if (!$block->isRedirectToCartEnabled()) : ?>

    <?php endif; ?>
<?php endif; ?>

As per my requirment I have made changes on above files, but basic idea you will get to create new custom view mode on category page.
Thanks :)


text:
Q: class.getResource returns a wrong path of my file I want to use Velocity to template my emails, but i struggled to give the right path of my template : "template.vm" that in my resource folder created by maven.
I used : class.getResource("template.vm").getPath => but getResource retruns null wich is logique cause as i know template.vm in that case should be in the same package of the class, and my template.vm is on WEB-INF/classes
So i used : class.getResource("/template.vm").getPath, but it returns a wrong path, in my case  the path of template.vm is : D:/folderOne/FolderTwo/WEB-INF/classes/template.vm   and getResource retruns : /D:/folderOne/FolderTwo/WEB-INF/classes/template.vm   what makes velocity class to throw : Unable to find resource with the given path : /D:/folderOne/FolderTwo/WEB-INF/classes/template.vm
I am struggling with this little probleme more then a day now, please help.

A: You should use ClassPathResourceLoader instead of FileResourceLoader for your Velocity. If you use it, you can simply call VelocityEngine.getTemplate("template.vm").


text:
Q: Access the Related List Label for a Lookup relationship I've searched high and low, and I can't seem to figure out the Apex syntax I need to use to access the Related List Label for a Lookup relationship.
It shows up in the objectTranslation XML as relationshipLabel, but that text doesn't appear anywhere in the Apex documentation.
I had hoped that the following syntax would work:
Schema.SObjectType.Custom_Object__c.Fields.Custom_Field__c.relationshipLabel

But no luck:
Expression of type Schema.DescribeFieldResult has no member named relationshiplabel

Is that label accessible from Apex?  I worry that it isn't, because I couldn't find it when browsing salesforce.schema in the Force.com IDE.
Update:
Someone has created an Idea to expose relationshipLabel in the WSDL, and I would expect it to extend to Apex as well.

A: I think we can get only API Names of the relationships...
Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
List<Schema.ChildRelationship> C = R.getChildRelationships();

List<String> prettyPrint = new List<String>{''};
for(Schema.ChildRelationship cr : C){
    prettyPrint.add(cr.getChildSobject() + '.'+ cr.getField() + ' => Account.' + cr.getRelationshipName());
}

System.debug(String.join(prettyPrint, '\n'));

Account.ParentId => Account.null
AccountContactRole.AccountId => Account.AccountContactRoles
AccountFeed.ParentId => Account.Feeds
AccountHistory.AccountId => Account.Histories
(...)


text:
Q: node_modules/@types/node/globals.d.ts: error TS2451: Cannot redeclare block-scoped variable 'console' I just followed the instructions on the link below in order to create a React Native app with TypeScript support.
https://github.com/mathieudutour/create-react-native-app-typescript
My problem is that when I run: $ tsc I get the following error:
$ tsc

> react-native-typescript@0.1.0 tsc D:\react-native-typescript
> tsc

node_modules/@types/node/globals.d.ts(164,13): error TS2451: Cannot redeclare block-scoped variable 'console'.
node_modules/@types/node/globals.d.ts(217,13): error TS2300: Duplicate identifier 'require'.
node_modules/@types/react-native/globals.d.ts(92,14): error TS2300: Duplicate identifier 'RequestInfo'.
node_modules/@types/react-native/index.d.ts(8885,14): error TS2300: Duplicate identifier 'require'.
node_modules/@types/react-native/index.d.ts(8903,11): error TS2451: Cannot redeclare block-scoped variable 'console'.
node_modules/@types/react-native/index.d.ts(8911,18): error TS2717: Subsequent property declarations must have the same type.  Property 'geolocation' must be of type 'Geolocation', but here has type 'GeolocationStatic'.
node_modules/@types/react-native/index.d.ts(8914,11): error TS2451: Cannot redeclare block-scoped variable 'navigator'.
node_modules/typescript/lib/lib.dom.d.ts(15764,13): error TS2451: Cannot redeclare block-scoped variable 'navigator'.
node_modules/typescript/lib/lib.dom.d.ts(15940,13): error TS2451: Cannot redeclare block-scoped variable 'console'.
node_modules/typescript/lib/lib.dom.d.ts(15997,6): error TS2300: Duplicate identifier 'RequestInfo'.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! react-native-typescript@0.1.0 tsc: `tsc`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the react-native-typescript@0.1.0 tsc script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Bill\AppData\Roaming\npm-cache\_logs\2019-02-17T17_20_46_096Z-debug.log

It seems that the problems are on packages inside the node_modules directory and not on my actual code.
Any idea on how to get the result of $ tsc to be clean?
Thanks!


text:
Q: Bitblt blackness I am running this following code,
HDC hdc;
HDC hdcMem;
HBITMAP bitmap;
RECT c;
GetClientRect(viewHandle, &c);
// instead of BeginPaint use GetDC or GetWindowDC
hdc = GetDC(viewHandle);
hdcMem = CreateCompatibleDC(hdc);
// always create the bitmap for the memdc from the window dc
bitmap = CreateCompatibleBitmap(hdc,c.right-c.left,200);

SelectObject(hdcMem, bitmap);

// only execute the code up to this point one time
// that is, you only need to create the back buffer once
// you can reuse it over and over again after that

// draw on hdcMem
// for example  ...
Rectangle(hdcMem, 126, 0, 624, 400);

// when finished drawing blit the hdcMem to the hdc
BitBlt(hdc, 0, 0, c.right-c.left,200, hdcMem, 0, 0, SRCCOPY);

// note, height is not spelled i before e

// Clean up - only need to do this one time as well
DeleteDC(hdcMem);
DeleteObject(bitmap);
ReleaseDC(viewHandle, hdc);

The code is just fine. But I am seeing black color around this rectangle. Why is that? Here is an example image.

A: The bitmap is most likely initialized to be all black. You are then drawing a white rectangle that between x-coordinates 126 and 624. Hence, everything to the left of x=126 and to the right of x=624 stays black.
Edit: The documentation for CreateCompatibleBitmap doesn't state how the bitmap will be initialized, so you should explicitly initialize the bitmap with a specific colour, as Goz suggests, using FillRect:
RECT rc;

rc.left=0;
rc.top=0;
rc.right=c.right-c.left;
rc.bottom=200;

FillRect(hdcMem, &rc, (HBRUSH)GetStockObject(GRAY_BRUSH));

This example fills the bitmap in gray -- you may need to CreateSolidBrush your own brush if you need a different colour. (Don't forget to call DeleteObject when you're done.)
As a side note, I find it a bit strange that your bitmap is being set to a constant height of 200 -- the normal thing would be to make the height of the bitmap equal to the height of the window (as is done for the width).

A: Might it be because you haven't initialised the memory bitmap area to a given colour?  Try FillRect'ing the background to a different colour then draw your white rectangle over it and see what happens.

A: Per MSDN http://msdn.microsoft.com/en-us/library/dd162898.aspx:

The rectangle is outlined by using the current pen and filled by using the current brush.

Consider calling FillRect instead, or select an appropriate pen prior to calling Rectangle'.

A: I used:
    // Fill the background
    hdcMem->FillSolidRect(c, hdcMem->GetBkColor());

Just as a note.


text:
Q: balloonAutoPan в скрытом контейнере не правильно позиционирует при Placemark.balloon.open() На сайте несколько карт которые переключаются табами. На каждую добавил по 1 метке с балуном, который имеет кастомный макет, хочу чтобы при переключении между табами балун был по умолчанию открыт.
При использовании метода Placemark.balloon.open();
первый экран который был открыт при загрузке страницы открывается нормально,
последующие позиционируются в координатах первой метки.
UPD.
Вопрос решен вот полный код:
var myMap0;
var myMap1;
// Дождёмся загрузки API и готовности DOM.

ymaps.ready(init);

function init () {
  // Создание экземпляра карты и его привязка к контейнеру с
  // заданным id ("map").

  myMap0 = new ymaps.Map('map', {
     // При инициализации карты обязательно нужно указать
     // её центр и коэффициент масштабирования.
     center: [45.013479, 38.995166], // краснодар
     zoom: 16,
     controls: ['zoomControl']
  });

  myMap0.behaviors.disable('scrollZoom');

  myMap1 = new ymaps.Map('map1', {
    // При инициализации карты обязательно нужно указать
    // её центр и коэффициент масштабирования.
    center: [55.753215, 37.622504], // Москва
    zoom: 10,
   controls: ['zoomControl']
 });

myMap1.behaviors.disable('scrollZoom');

// Создание макета балуна на основе Twitter Bootstrap.
  MyBalloonLayout = ymaps.templateLayoutFactory.createClass(
    '
' +
    '×' +
    '

' +
    '
' +
    '$[[options.contentLayout observeSize minWidth=280 maxWidth=280 maxHeight=200]]' +
    '
' +
    '
', {
    / * Строит экземпляр макета на основе шаблона и добавляет его в родительский HTML-элемент. */
     build: function () {
       this.constructor.superclass.build.call(this);
       this._$element = $('.popover', this.getParentElement());
       this.applyElementOffset();
       this._$element.find('.close').on('click', $.proxy(this.onCloseClick, this));
     },

     /*Удаляет содержимое макета из DOM. */
    clear: function () {
      this._$element.find('.close').off('click');
      this.constructor.superclass.clear.call(this);
    },

    /* Метод будет вызван системой шаблонов АПИ при изменении размеров вложенного макета. */
   onSublayoutSizeChange: function () {
     MyBalloonLayout.superclass.onSublayoutSizeChange.apply(this, arguments);
     if(!this._isElement(this._$element)) {
       return;
     }

    this.applyElementOffset();
    this.events.fire('shapechange');
  },

  /* Сдвигаем балун, чтобы "хвостик" указывал на точку привязки. */
  applyElementOffset: function () {
    this._$element.css({
      left: -(this._$element[0].offsetWidth / 2),
      top: -(this._$element[0].offsetHeight + this._$element.find('.arrow')[0].offsetHeight)
    });
  },

  /*Закрывает балун при клике на крестик, кидая событие "userclose" на макете.*/
 onCloseClick: function (e) {
  e.preventDefault();
    this.events.fire('userclose');
  },

  /*Используется для автопозиционирования (balloonAutoPan). */
  getShape: function () {
    if(!this._isElement(this._$element)) {
      return MyBalloonLayout.superclass.getShape.call(this);
    }
    var position = this._$element.position();
    return new ymaps.shape.Rectangle(new ymaps.geometry.pixel.Rectangle([
      [position.left, position.top], [position.left + this._$element[0].offsetWidth,
      position.top + this._$element[0].offsetHeight + this._$element.find('.arrow')[0].offsetHeight]
    ]));
  },
  /*Проверяем наличие элемента (в ИЕ и Опере его еще может не быть).*/
  _isElement: function (element) {
    return element && element[0] && element.find('.arrow')[0];
  }
});

// Создание вложенного макета содержимого балуна.
MyBalloonContentLayout = ymaps.templateLayoutFactory.createClass(
  '
$[properties.balloonHeader]
' +
  '
$[properties.balloonContent]
'
);

myPlacemark0 = new ymaps.Placemark(myMap0.getCenter(), {
  balloonHeader: "Наш адрес:",
  balloonContent: "г.Краснодар",
},
{
  iconLayout: 'default#image',
  iconImageHref: 'images/map.png', // картинка иконки
  iconImageSize: [64, 100], // размер иконки
  iconImageOffset: [-32, -100], // позиция иконки

  balloonShadow: false,
  balloonLayout: MyBalloonLayout,
  balloonContentLayout: MyBalloonContentLayout,
  balloonPanelMaxMapArea: 0,
  balloonOffset: [0, -10]
});

myPlacemark1 = new ymaps.Placemark(myMap1.getCenter(), {
  balloonHeader: "Наш адрес:",
  balloonContent: "г.Москва",
},
{
  iconLayout: 'default#image',
  iconImageHref: 'images/map.png', // картинка иконки
  iconImageSize: [64, 100], // размер иконки
  iconImageOffset: [-32, -100], // позиция иконки

  balloonShadow: false,
  balloonLayout: MyBalloonLayout,
  balloonContentLayout: MyBalloonContentLayout,
  balloonPanelMaxMapArea: 0,
  balloonOffset: [0, -10]
});

/* Добавляем метки на карту */
myMap0.geoObjects.add(myPlacemark0);
myPlacemark0.balloon.open();

myMap1.geoObjects.add(myPlacemark1);

$('#tabs').on('tabsactivate',function (event, ui) {
  window['myMap'+ui.newTab.index()].container.fitToViewport();
  window['myPlacemark'+ui.newTab.index()].balloon.open();
});


text:
Q: How can I assign event handler to event known from EventInfo? I would like to iterate over all events which a control (e.g. TextBox) supports and programmatically assign the same diagnostic event handler to each.
It is clear I cannot use C# += or VB AddHandler command. How can I assign event handler to each event known from GetType(TextBox).GetEvents()?
Imports System.Reflection

Public Class Form1

    Public Sub New()
        InitializeComponent()

        For Each ei As EventInfo In GetType(TextBox).GetEvents()
            'AddHandler TextBox1.ei, AddressOf DiagnosticHandler - PLEASE HELP ME HERE
        Next
    End Sub

    Private Sub DiagnosticHandler(sender As Object, e As EventArgs)
        'whatever
    End Sub

End Class

(C# or VB - whatever you prefer.)

A: EventInfo type has AddEventHandler() method exactly for this purpose.
Compatibility: .NET 3.5 and higher (Tested.)
Minimal valid code:
Public Sub New()
    InitializeComponent() ' needed only in Form class
    BindHandlers(TextBox1) ' this is our binding
End Sub

Public Sub BindHandlers(c As Control)
    Dim handler As MethodInfo = Me.GetType().GetMethod(NameOf(DiagnosticEventHandler))
    For Each ei In c.GetType().GetEvents()
        ei.AddEventHandler(c, [Delegate].CreateDelegate(ei.EventHandlerType, handler))
    Next
End Sub

Public Shared Sub DiagnosticEventHandler(sender As Object, e As EventArgs)
    'whatever
End Sub

Note: I only succeeded with Public Shared handler method. With Private and non-shared method I was getting signature compatibility errors which I was lazy to resolve.
Bonus for those who kept reading until this point:
Public Shared Sub DiagnosticEventHandler(sender As Object, e As EventArgs)
    'heuristic disclosing of method related to event name
    Dim maxAttempts As Integer = 15
    Dim attempt As Integer = 1
    Dim stackTrace As New StackTrace()
    Do While attempt <= maxAttempts
        Dim methodName As String = stackTrace.GetFrame(attempt).GetMethod().Name
        attempt += 1
        If methodName.StartsWith("On") Then
            Debug.Print(String.Join(" > ", stackTrace.GetFrames().Take(attempt).Skip(1).Select(Of String)(Function(sf) sf.GetMethod.Name).Reverse().ToArray()))
            Return
        End If
    Loop
    Debug.Print(String.Join(" > ", stackTrace.GetFrames().Take(maxAttempts).Select(Of String)(Function(sf) sf.GetMethod.Name).Reverse().ToArray()))
End Sub

A: Just in case someone need it, here is the code to accomplish that (assuming you have a TextBox called textBox1 in the form).
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        MethodInfo miHandler = typeof(Form1).GetMethod("DiagnosticHandler", BindingFlags.NonPublic | BindingFlags.Instance);

        EventInfo[] events = typeof(TextBox).GetEvents();

        foreach (EventInfo ei in events)
        {
            Type tDelegate = ei.EventHandlerType;
            Delegate d = Delegate.CreateDelegate(tDelegate, this, miHandler);
            MethodInfo addHandler = ei.GetAddMethod();
            Object[] addHandlerArgs = { d };
            addHandler.Invoke(this.textBox1, addHandlerArgs);
        }

    }

    private void DiagnosticHandler(object sender, EventArgs e)
    {
        //whatever
    }
}

more info here


text:
Q: How to get host app screen geometry for iOS 8 custom keyboard inside iPhone app running on iPad? My Custom keyboard has presets for each screen resolution of all Apple devices. So I have iphone, iphon5, iphone6, iphone6plus and ipad presets.
But in case user runs iPhone app (like instagram) on iPad, I need to load iphone keyboard preset and use its geometry.
Also iPhone 6 and 6+ can use stretched mode, when apps run like iPhone 5 app being stretched.
So determining UI_USER_INTERFACE_IDIOM is not a solution.
Keyboard extension and host app can see screen geometry in different ways, so I am stuck here. Need to get at least application frame for host app or any other explicit way to get that geometry.
App and keyboard extension see geometry different ways:

Also Swift key seems to have same bug while running hosted inside of iphone app on ipad screen.
Swiftkey inside iphone app on ipad:

A: I just found a way to check isPad on keyboard extension but I cannot make sure it is best way.
UI_USER_INTERFACE_IDIOM() && YourKeyboardViewController.instance.view.bounds.size.width == UIScreen.mainScreen.bounds.size.width
You should do this after YourKeyboardViewController.instance did called viewWillAppear(), after that the view.bounds did changed to 320x480 from 768x1024.


text:
Q: Is there a way to just highlight specific words in node.js console? I'd like to get a very special console output for my node.js console...
I'd like to highlight just specific words e.g. ('ERROR', 'SUCCESS', ...) in specific colors (red,green,...).
Is there an easy way to achieve this or do I have to check the console output every time & test if the output includes my word ('error') to laterone color it??
BTW thats how I've catched the console output:
console.log = function(d) {
  process.stdout.write(d + '\n');
}

Thanks in advance :)


text:
Q: What's a good tool/method to find which files on disk have been changed after a program has been run? I'm experiencing a strange issue where my Visual Studio 2005 C++ program crashes the first time it runs after a new build.  I'm having a difficult time debugging this intermittent issue and I suspect it's somehow related to a file somewhere on my hard drive that is being changed.  If I can find the file(s), that might provide some more insight into this issue.  Are there any good tools for observing which files are being created/deleted/modified when a specific program is run?
Thanks in advance!

A: You can use Process Monitor tool. Set "Show File System Activity" to ON and set a filter on the process name to get only the traces you need.

A: SysInternals (now Microsoft) FileMon
http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx

A: Use find.
touch ~/test-marker
# run your program
find <directory> -newer ~/test-marker


text:
Q: Given $0When $r$ is a rational number $p/q$ with $q$ odd, for example, the answer is affirmative using bump functions such that $f^{(n)}(0)=0$ for all $n\in\mathbb{N}$ (vanishing the distinct lateral derivatives of $|\cdot|$ at $0$ by chain rule), as with the $C^\infty$-homeomorphism $f\colon\left(-\sqrt{-1/\ln\varepsilon},\sqrt{-1/\ln\varepsilon}\right)\to(-\varepsilon,\varepsilon)$ definded by
$$f(x)=\begin{cases}e^{-q/x^2}& \text{ if }x>0,\\
              0 &\text{ if }x=0, \\
              -e^{-q/x^2}&\text{ if }x<0\end{cases}.$$
But I'm stuck when q is even, or the main case when r is irrational (and more difficult). I would appreciate any hint.

A: The function \begin{align}&f:(-a,a)\to (-\varepsilon,\varepsilon)\\ &f(x)=\begin{cases}\varepsilon e^{a^{-2}}\cdot e^{-x^{-2}}&\text{if }x>0\\ -\varepsilon e^{a^{-2}}\cdot e^{-x^{-2}}&\text{if }x<0\\ 0&\text{if }x=0\end{cases}\end{align}
is a $C^\infty$ homeomorphism, and $\lvert f(x)\rvert^r=\begin{cases}\varepsilon^re^{ra^{-2}}\cdot e^{-rx^{-2}}&\text{if }x\ne 0\\ 0&\text{if }x=0\end{cases}$ is $C^\infty$ for all $r>0$. The proof is the same as proving that $e^{-x^{-2}}$ is $C^\infty$: you prove that for all $n$ there is a rational function $g_n$ such that the denominator of $g_n$ is a power of $x$ and such that $(\lvert f\rvert^r)^{(n)}(x)=\begin{cases}g_n(x)e^{-rx^{-2}}&\text{if }x\ne0\\ 0&\text{if }x=0\end{cases}$. In order to do that, you can proceed iteratively by proving at each step that $(\lvert f\rvert^r)^{(n)}$ is continuous at $0$ and $C^1$ on $\Bbb R\setminus\{0\}$, and then that $\lim_{x\to 0} (\lvert f\rvert^r)^{(n+1)}(x)=0$.
You can obtain a $C^\infty$ homeomorphism $(a,b)\to(-\varepsilon,\varepsilon)$ by using $f(x-(b+a)/2)$, where $f:\left(\frac{a-b}2,\frac{b-a}2\right)\to(-\varepsilon,\varepsilon)$.


text:
Q: Get text from Web page via PHP I'm trying to get the text from a certain URL, this text is located between two texts.
For example :
Item number:	**GX12033111**

I need to get the GX12033111 part,
I've tried this :
<?php
$file_string = file_get_contents('LINK GOES HERE');
preg_match('/Item number:	(.*)<\/td><\/tr>/i', $file_string, $title);
$title_out = $title[1];
echo $title_out ;
?>

But it doesn't work.

A: You'll want to use PHP's DOM document http://php.net/manual/en/book.dom.php
With this you can
DOM::loadHTML(file_get_contents("URL"));

and then you can
DOM::getElementsByTagName("td");

A: Try using:
preg_match('@Item number:	([^<]+)
@i', $file_string, $title);


text:
Q: How to handle transitive ES module dependencies with Node.js and Next? I have a node module A published as ES only module. There is another module B that has peer dependency on module A and it is published as CommonJS module. Now, I have a next.js application C which is using both A and B.
Now the problem starts when I try to compile C and get following error:
Error [ERR_REQUIRE_ESM]: require() of ES Module <file-name> not supported

This error is obvious as module B is trying to import A using require('A') which is not allowed as per Node.js rules. So, how do I fix this?
The module C is a Next.js - 12 application and using Webpack as a bundler and Babel as transpiler using project-wide configuration file babel.config.js.


text:
Q: Cuda out of memory despite consuming only 60% memory I'm getting cuda out of memory error. The error is shown below

RuntimeError: CUDA out of memory. Tried to allocate 256.00 MiB (GPU 0;
23.65 GiB total capacity; 21.65 GiB already allocated; 242.88 MiB free; 22.55 GiB reserved in total by PyTorch)

I'm able to train the model after I reduce the batch_size. When I checked the output of nvidia-smi, I see a 40% of memory is still free. Here is the output.

What could be possible reason for this?
pytorch: 1.4
cuda: 10.2
input_size: (512, 512, 4)
using half-precision
More information:
The plot of gpu-utilization is shown below

The numbers at each peak represent the batch_size. It seems the initial memory requirement is much higher than memory needed afterward. Can someone explain?


text:
Q: Error Java Heap size in Android Studio 1.3.1 I recently updated Android Studio from 1.2 to 1.3.1.
After updating Gradle Sync failed message is started showing up to increase Java heap size.
Following is the screenshot of error.
TIA

A: Go to your Android Studio Folder Where it is installed. There is File stduio.exe and studio64.exe with file type of VMOPTIONS, open it in notepad you will see Something like this:
-Xms512m
-Xmx1280m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=225m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-ea
-Djna.nosys=true
-Djna.boot.library.path=

-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Didea.paths.selector=AndroidStudio1.3
-Didea.platform.prefix=AndroidStudio

According to error you may need to change 2 values in it.
-Xms512m
-Xmx1280m

check this value and change it.

A: On Windows 7, what worked for me was to point the Android Studio JDK location to where the system JDK (latest) was located.
In the following images, I've marked in red the bits that should be the same.
Android Studio project, File > Project Structure > SDK Location > JDK Location:

Command line, java -version:

A: open your projects gradle.properties file and paste it.
org.gradle.jvmargs=-XX\:MaxHeapSize\=512m -Xmx512m

A: Just open the gradle.properties file in your projects and add:
org.gradle.jvmargs=-Xmx1024m

I met this problem when I upgraded my system to win10

A: In Android Studio go to Help-> Edit Custom VM Options. Hit yes button and then change 1st two values.
More Info - https://developer.android.com/studio/intro/studio-config.html

A: I had the same problem as you had. But now I have solve it just Updating my JDK version 1.7 to 1.8. Now it's working fine for me. And configure the Environment Variable with JAVA_HOME and Android Studio ->Project Structure->SDK Location=>JDK Location.


text:
Q: Voice Over Does Not Read Aria-label on iOS Safari but Screen Reader Reads on Chrome I have a play icon that I want to be announced when it's focused. But interestingly, screen reader reads the aria-label. However, for iOS safari, using swiping gesture to the play icon does not announce the aria-label at all, and it only announce "link"
Here's the simplified HTML code:

Does anyone know why?

A: First, I don't really think  is the correct choice here. That element is intended for idiomatic text such as technical jargon or special terminology. That's not the case here, and besides your  contains no text nodes. I gather it appears on screen as a CSS icon.  could handle that just as well, but it wont get you much closer to your intended (screen reader) results.
Second, according to this useful reference about aria-label,  does not support aria-label because it maps to role="generic", which means naming is not allowed. This is true for almost all inline elements, including , with  as the most obvious exception.
So, if your simplified snippet is representative, then this is not a bug. The iOS behavior is correct according to the spec, and Chrome is doing the 'wrong' thing.
If your play icon is an operable element (i.e. it does something when you 'click' it or 'touch' it) then you should use an explicitly operable element or ARIA role.
The compellingly correct thing to use here would be <button>, but  (or role="link") might also be appropriate. If you decide to use an ARIA role, be sure to add tabindex="0" because you don't get tab focus 'for free' with ARIA.
The markup might look like this:

or
<button class="c-glyph" aria-label="there is video inside"></button>
or (using an ARIA role)

or (another ARIA role)

If you decide to use a <button> element you can style it however you like, but you probably want to begin by removing the default button styles provided by the user agent (browser), so in CSS you might have.
button.c-glyph {
    background: none; /* css icon will override or replace this */
    color: inherit;
    border: none;
    padding: 0;
    font: inherit;
    cursor: pointer;
    outline: inherit;
}

And then you can specify whatever icon background is in the rule for your .c-glyph class.


text:
Q: flutter firebase firestore Remove duplicate values I want to know how to remove duplicate values in firestore

A: Remove the duplicates before updating it to firestore
final Map<String, Movie> moviesMap = new Map();
moviesWithDuplicates.forEach((movie) {
  moviesMap[movie.id] = movie;
});
moviesWithoutDuplicates = moviesMap.values.toList();

// send moviesWithoutDuplicates to firestore


text:
Q: Unexpected method call while using PowerMock- EasyMock My problem seems to be with some misconception with mocking. The code for test.
public class CallHandler {
    private SqlSessionFactory sessionFactory;
    public CallHandler() {
        String resource = "mybatis/mybatis-config.xml";
        Reader reader;
        try {
            reader = Resources.getResourceAsReader(resource);
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String handleRequest(Call call) {
        // Some Implementation
    }
}

The test class
// I have excluded few unnecessary classes from @PrepareForTest for the post.

@RunWith(PowerMockRunner.class)
@PrepareForTest({SqlSessionFactoryBuilder.class, Resources.class, SqlSessionFactory.class, SqlSession.class})
public class TestCase0 extends TestCase{
    private SqlSessionFactory mockedSessionFactory = PowerMock.createMock(SqlSessionFactory.class);
    private SqlSession mockedSession = PowerMock.createMock(SqlSession.class);
    private CallMapper mockedMapper = PowerMock.createMock(CallMapper.class);
    private SqlSessionFactoryBuilder mockedSqlSessionFactoryBuilder= PowerMock.createMock(SqlSessionFactoryBuilder.class);
    // Others

    @Before
    public void setUp() {
    }

    @Test
    public void test0 () throws Exception {
        mockStatic(CallMapper.class);
        mockStatic(SqlSessionFactoryBuilder.class);
        mockStatic(Resources.class);
        expect(Resources.getResourceAsReader("mybatis/mybatis-config.xml")).andReturn(mockedReader);      expectNew(SqlSessionFactoryBuilder.class).andReturn(mockedSqlSessionFactoryBuilder);  expect(mockedSqlSessionFactoryBuilder.build(mockedReader)).andReturn(mockedSessionFactory);
        expect(mockedSessionFactory.openSession()).andReturn(mockedSession);
        // Few more expectations
        replayAll();
        assertThat(RESULT0).isEqualTo((new CallHandler()).handleRequest(call));
        verifyAll();
    }
}

This mocking of call of build on the new SqlSessionFactoryBuilder does not seem to be taking effect because of which the original build() is being called and hence the error. The stack trace
java.lang.AssertionError:
Unexpected method call Reader.close();
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl.invoke(EasyMockMethodInvocationControl.java:91)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:105)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:168)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:58)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:38)
at com.kwench.integration.ivr.CallHandler.<init>(CallHandler.java:48)
at in.kwench.integration.ivr.TestCase0.test0(TestCase0.java:131)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)

A: Without the full example of the code you're testing and the test class itself, it's difficult to say where you issues could be arising.
Having said that, I'm guessing your issue is that you haven't prepared the classes with the static methods. These need to be provided in the @PrepareForTest annotation at the start of your test class.
The documentation for PowerMock provides the following tips for mocking static methods. I'm guessing you've missed out point 2. Here is the source for this documentation

Mocking static methods
Quick summary

*

*Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.

*Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case.

*Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class.

*Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class to replay mode.

*Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class to verify mode.

You are also mocking the constructor call for SqlSessionFactoryBuilder so you'll need to consider the tips for that too. Here is the documentation for this

Mock construction of new objects
Quick summary

*

*Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.

*Use the @PrepareForTest(ClassThatCreatesTheNewInstance.class) annotation at the class-level of the test case.

*Use PowerMock.createMock(NewInstanceClass.class) to create a mock object of the class that should be constructed (let's call it mockObject).

*Use PowerMock.expectNew(NewInstanceClass.class).andReturn(mockObject) to expect a new construction of an object of type NewInstanceClass.class but instead return the mock object.

*Use PowerMock.replay(mockObject, NewInstanceClass.class) to change the mock object and class to replay mode, alternatively use the PowerMock.replayAll() method.

*Use PowerMock.verify(mockObject, NewInstanceClass.class) to change the mock object and class to verify mode, alternatively use the PowerMock.verifyAll() method.

With those tips in mind, I produced the following test method for the method you provided that you are trying to test. This test passes fine.
@RunWith(PowerMockRunner.class)
@PrepareForTest({CallHandler.class, SqlSessionFactoryBuilder.class, Resources.class})
public class CallHandlerTest {

    private static final String RESULT0 = "";

    @Test
    public void test0 () throws Exception {
        final Reader mockedReader = EasyMock.createMock(Reader.class);
        final SqlSessionFactoryBuilder mockedSqlSessionFactoryBuilder = EasyMock.createMock(SqlSessionFactoryBuilder.class);
        final SqlSessionFactory mockedSessionFactory = EasyMock.createMock(SqlSessionFactory.class);

        PowerMock.mockStatic(SqlSessionFactoryBuilder.class);
        PowerMock.mockStatic(Resources.class);

        PowerMock.expectNew(SqlSessionFactoryBuilder.class).andReturn(mockedSqlSessionFactoryBuilder);
        EasyMock.expect(Resources.getResourceAsReader("mybatis/mybatis-config.xml")).andReturn(mockedReader);
        EasyMock.expect(mockedSqlSessionFactoryBuilder.build(mockedReader)).andReturn(mockedSessionFactory);

        PowerMock.replayAll();
        assertThat(RESULT0).isEqualTo((new CallHandler()).handleRequest(new Call()));
        PowerMock.verifyAll();
    }
}

A: It's the conflict between code coverage and powermock.mockStatic.
Code coverage instruments $jacocoInit static method into all the class to collect the code coverage.  When running the testcase, mockStatic mock the $jacocoInit static method which leads to an expected static method call.
You can bypass the problem with creating partial mock on static method, e.g. PowerMock.mockStaticPartial(TheClass.class, "theStaticMethod") so that power mock won't touch the $jacocoInit method.


text:
Q: Audio file share on Facebook using my app Am also having some problem with sharing audio/video,
I tried this code block to share audio file.
me = FbGraph::User.me(ACCESS_TOKEN)
me.feed!(
        :message => 'Updating via FbGraph',
        :source => 'http://s3.amazonaws.com/derbywire_development/system/audios/21/original/ROJA.mp3?1376993284',
        :description => 'A Ruby wrapper for Facebook Graph API',
        :name => 'FbGraph',
        :type => 'mp3'
    )

Its sharing the post the but the player is not coming for me. its simply showing the link.

Can anyone help me out this problem?


text:
Q: Glide load an image from an URl I'm trying to use Glide to load an image from an Url:
Glide.with(getContext()).load(urlImage).error(R.drawable.ic_profile_default).into(imgUser);

This is the error I get:
W/Glide: Load failed for https:www.cerberusenlinea.com/images/profile/16/13/HOLCIM.jpeg with size [204x204]
    class com.bumptech.glide.load.engine.GlideException: Failed to load resource
    There was 1 cause:
    javax.net.ssl.SSLHandshakeException(java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.)
     call GlideException#logRootCauses(String) for more detail

A: The problem is that you are trying to take the image from a not secure website, so glide blocks you.
To solve this issue you can create a custom trust manager but is very dangerous because you get exposed to man in the middle attack.
If you want to follow this route i suggest you to read this
Trust Anchor not found for Android SSL Connection
Another work around solution, that i suggest could be download the image and host it on
 your server or on a free service (you can found a lot of them) like https://imgur.com/upload or everyone else

A: The HTTPS configuration for the site www.cerberusenlinea.com has chain issues.
You can verify it in the Qualys Free Scanner: https://www.ssllabs.com/ssltest/analyze.html?d=www.cerberusenlinea.com

Android requires the full certificate chain in order to consume the content.
The official documentation says:

Most public CAs don't sign server certificates directly. Instead, they
  use their main CA certificate, referred to as the root CA, to sign
  intermediate CAs. They do this so the root CA can be stored offline to
  reduce risk of compromise. However, operating systems like Android
  typically trust only root CAs directly, which leaves a short gap of
  trust between the server certificate—signed by the intermediate CA—and
  the certificate verifier, which knows the root CA. To solve this, the
  server doesn't send the client only it's certificate during the SSL
  handshake, but a chain of certificates from the server CA through any
  intermediates necessary to reach a trusted root CA.

The documentation mention some alternatives in order to address the problem from the application side.


text:
Q: Can I place system.web.webPages.razor in my top level web.config when using areas? I am using MVC Areas.  Within each area I have a views section and in that a web config that contains the following:
<configSections>
  <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

  </sectionGroup>
</configSections>

<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" /> ... more namespaces common to all views ...
    </namespaces>
  </pages>
</system.web.webPages.razor>

I always try to not repeat my code so I am wondering. Can I take the above out of the web.configs in each area and add to the top level web.config. I tried and it seems to work. But is it an okay thing to do?

A: Yes, you can.
However, it will break any non-MVC Razor pages in your site.


text:
Q: Python: Class are linked after instantiation but should not I am currently working on a connect4 game and so coded a class for the game. When I instantiate 2 class/game, whatever I do to the first class is copied on the second. How can I have two distinct instance? Here is the code (I work on jupyter notebook):
import numpy as np

class Connect4:
    def __init__(self, board = np.zeros((6, 7))):
        if(board.shape != (6, 7)):
            raise Exception("board is invalid")
        if(np.sum(board) == 0):
            self.player = 1
        elif(np.sum(board) == 1):
            self.player = -1
        else:
            raise Exception("board is invalid")
        self.board = board

    def play(self, move):
        if(move not in self.getLegalActions()):
            return True, -self.player
        for row in range(6):

            if(self.board[row][move] == 0):
                self.board[row][move] = self.player
                self.player = -self.player
                return self.checkWin()

            else:
                continue

        return(self.checkWin())

game1 = Connect4()
game2 = Connect4()

game1 == game2 returns false but when I play on game1 and then check game2's board, they are always the same.
The bug goes away when I call instead
game1 = Connect4(np.zeros((6, 7)))
game2 = Connect4(np.zeros((6, 7)))

but it does not make sense to me why just calling game1 = Connect4() doesn't work.
If anyone knows what is the difference.


text:
Q: Google Script to copy non blank rows and append to another sheet Looking to copy and append all non-blank rows from a sheet tab "Form" to another sheet tab "Hold" and then delete the data from "Form".
I've tried this.:
// form copy
  function formcopy(){
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheet = ss.getSheetByName("Form");
   var data = sheet.getDataRange().getValues();
  for (var i = 2; i < data.length; i++) {
    Logger.log('Timestamp: ' + data[i][0]);
    Logger.log('Teacher Email: ' + data[i][1]);
    Logger.log('Teacher Requesting: ' + data[i][2]);
    Logger.log('Student: ' + data[i][3]);
    Logger.log('Purpose: ' + data[i][4]);
    Logger.log('Email: ' + data[i][5]);
    Logger.log('Date: ' + data[i][6]);
    Logger.log('Advisor: ' + data[i][7]);
    Logger.log('Time: ' + data[i][8]);
    Logger.log('Message: ' + data[i][9]);
    Logger.log('Merge Status: ' + data[i][10]);

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName("Hold");
    sheet.appendRow([data[i][0], data[i][1], data[i][2], data[i][3],
data[i][4], data[i][5], data[i][6], data[i][7], data[i][8], data[i][9],
data[i][10]]);
  }}

 //Deletes Data

   function deletedata(){
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName("Form");
    sheet.activate();
    sheet.deleteRows(3,200);
    sheet.insertRowsAfter(2, 200);
    sheet.deleteRows(3);
 }

It does copy the data, but it copies the blank rows as well. Also, if there is a lot of data in "Form", it times out.


text:
Q: Using a dependent project for test objects Assume that I have multiple java projects, all of them use maven: Project A and Project B

*

*Project A is a library

*Project B is an application which uses Project A
Both projects are developed simultaneously. New requirements from Project A are fulfilled with a new release of Project B.
I mostly tested my code manually which - as expected - yielded less than optimal code coverage and therefore quality.
I'm therefore currently looking into using Junit to write tests for my projects. Since Project A mostly defines interfaces, I would have to - at least I believe so - write implementations of these classes in the test code.
As I already have implementations of those interfaces defined in Project B I figured I could use Project B as test dependency in Project A, which at first glance would make perfect sense as nearly all features of Project A are used in those implementations, as I would (at least for now) not develop a feature in Project A that is not used in Project B (Keep in mind: this might change for future projects e.g. a newly created Project C, which might also depend on Project A).
On the other hand this would create some sort of circular dependencies. In Project B's pom.xml I would define a regular dependency on Project A, while Project A would have a dependency on Project B in the test-scope.
Therefore the following questions:

*

*Is this even technically possible or would I run into issues with the circular dependencies right from the start or at a later point in time? (I believe I've seen someone doing something similar, where they had to define the correct version of Project A in Project A's <dependencyManagement> section to make sure the current code is used while testing and not the version defined in Project B. I can't find it anymore though, so I can't verify this, but I remember being confused on why they would define their own projects version in that section. Edit: I believe I found it again, but it seems to be something else, I was propably just kind of confused while researching junit and testing ;) )

*Is it desirable to use a downstream project for classes for a test case or are there issues I could face at a later point in time? (My first thought would be that I'd run into a problem as soon as I replace Project A with a third party dependency in Project B, therefore loosing all my test cases for Project A)

A: No, this is not a good idea.
First of all, you create circular dependencies. Secondly, you don't test what you want to test, namely project A (not project B).
So, what you gonna do instead?
Firstly, think whether it is really sensible to have two separate projects A and B if they are developed simultaneously. You could put them into a multi-module project instead.
Secondly, if A are mainly interfaces, it may be more sensible to test B (in integration with A), instead of A alone. If you find that there are things in A which are worth testing, you can use mocking (like mockito) to mock the interfaces that appear in your tests.


text:
Q: Chage focus javaw window in TestComplete I have a java application called App 1.4 () (which I have no access to the code) that, while running up another java application App2 (and a host of other applications). The application App2 is shot from within the App and you can not run your jar. I wonder how do I put App2 in focus and click a button on it.
I did the following code:
setPropertieWithClickOnBoxApp2 function ()
{
  Aliases.Explorer.wndShell_TrayWnd.ReBarWindow32.MSTaskSwWClass.ToolbarWindow32.CheckItem ("App2", true, false);
  Aliases.javaw1.frame01.RootPane.null_layeredPane.null_contentPane.Panel.Panel.Panel.RadioButton.ClickButton();
}

But it is not working.

A: I solved the problem.
It is necessary to set the next context into the previous context routine code.


text:
Q: How to find all the possible k integers which sum of them equals to a certain number in R suppose I have a integer n and k, I need find all the possible combinations of k integers which sum to n. I was wondering to how do I implement this efficiently.
right now, what I am doing is super slow, I created kth cartesian product of a sequence from 1 to n. And then loop over all the possible combinations to check if it satisfy the sum.Below is my code.
first get k cartesian product
cart = function(v,k){
  x = v
  f = v
  for(i in 1:(k-1)){
    f = merge(f,x,all=T)
    f = as.matrix(f)
    colnames(f) = NULL
  }
  return(f)
}

v is the sequence from 1 to n and k is the integer
then loop over
combine = cart(v=seq(1,n),k=k)
sum = 0
for(i in 1:dim(combine)[1]){
  if(sum(combine[i,])==n){
    sum = sum + sum(combine[i,])
  }
}

this is super slow and I was wondering is there any faster way to implement this?

A: Edited based on clarification of question in comments:
Sounds like you are wanting all compositions, rather than all partitions of the integer n. (Two sequences differing only in the order of their terms are considered to be the same partition, but different compositions.)
To get compositions, use the compositions() function from the partitions package:
library(partitions)
compositions(4, 3, include.zero=FALSE)
#
# [1,] 2 1 1
# [2,] 1 2 1
# [3,] 1 1 2

Original answer, left in place until the package author has had a chance to see it:
If I correctly understand your question, you could use restrictedparts() from the partitions package.
For example:
library(partitions)

restrictedparts(9,4)
#
# [1,] 9 8 7 6 5 7 6 5 4 5 4 3 6 5 4 4 3 3
# [2,] 0 1 2 3 4 1 2 3 4 2 3 3 1 2 3 2 3 2
# [3,] 0 0 0 0 0 1 1 1 1 2 2 3 1 1 1 2 2 2
# [4,] 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 2

## Or, for partitions employing only non-zero integers
restrictedparts(9,4,include.zero=FALSE)
#
# [1,] 6 5 4 4 3 3
# [2,] 1 2 3 2 3 2
# [3,] 1 1 1 2 2 2
# [4,] 1 1 1 1 1 2

Due to a minor bug in the second to last line of restrictedparts, it can throw an error when the given restriction allows just one partition. I've sent a proposed fix to the package author, but in the meantime you can get around this by setting the function argument decreasing=FALSE:
## Throws an error
restrictedparts(4,3,include.zero=FALSE)
# Error in class(x) <- "matrix" :
# invalid to set the class to matrix unless the dimension attribute is of # length 2 (was 0)

## Works just fine
restrictedparts(4,3,include.zero=FALSE,decreasing=FALSE)
#
# [1,] 1
# [2,] 1
# [3,] 2

A: Here is a base R method using combn. Lets say you have the integers 1 through 12 and you want to find all of the sets of 5 numbers that sum to 20.
myGroups <- combn(1:12, 5)
mysums <- combn(1:12, 5, FUN=sum, simplify=TRUE)

myAnswers <- myGroups[, mysums == 20]

This returns a matrix where the columns are the sets of numbers:
myAnswers
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    1    1    1    1    1    2
[2,]    2    2    2    2    2    3    3
[3,]    3    3    3    4    4    4    4
[4,]    4    5    6    5    6    5    5
[5,]   10    9    8    8    7    7    6

This will be easy to wrap up in a function. In the function below, x is the input vector, which I set as 1:12 in the example above, and k and n are defined in the OP's question.
myfunction <- function(x, k, n) {
  myGroups <- combn(x, k)
  mysums <- combn(x, k, FUN=sum, simplify=TRUE)

  myGroups[, mysums == n]
}

Note
This method assumes that each entry in x will be used once in the calculation, so on the integers 0:9 that add up to 9 using 4 of them, myfunction returns:
myfunction(0:9, 4, 9)
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    1    1    2
[3,]    2    3    3
[4,]    6    5    4

Note
If the goal is the allow for repeated use of these integers, we simply must adjust what we feed to myfunction. Note that this will result in duplicated output of sets, since order matters to combn.

If repeated integers will be involved, the use of combn has to be modified to return a list so we can use unique to drop duplicate sets:
myfunctionDupes <- function(x, k, n) {
  # return list instead of matrix, with elements sorted
  myGroups <- lapply(combn(x, k, simplify=FALSE), sort)
  # find duplicates
  dupes <- duplicated(myGroups)
  # subset summations to those where myGroups is not a duplicate
  mysums <- combn(x, k, FUN=sum, simplify=TRUE)[!dupes]
  # subset myGroups to the unique values then those with sums == n
  myGroups <- (myGroups[!dupes])[mysums == n]
  # return a matrix
  do.call(cbind, myGroups)
}

This takes a little while to run on @josh-obrien's example, but it produces the same result:
myfunctionDupes(rep(0:9, 4), 4, 9)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18]
[1,]    0    0    0    0    0    0    0    0    0     0     0     0     1     1     1     1     1     2
[2,]    1    1    1    1    0    2    2    0    0     3     0     0     2     2     1     1     1     2
[3,]    2    3    4    1    1    3    2    2    3     3     4     0     3     2     2     3     1     2
[4,]    6    5    4    7    8    4    5    7    6     3     5     9     3     4     5     4     6     3


text:
Q: Chrome auto completando input, autocomplete="off" não funciona Ao entrar na pagina de busca "http://conteumahistoria.com/autor/monychan" o input fica se completando sozinho, coloquei autocomplete="off" e não adiantou, o que posso fazer?
<input type="text" id="pesquisa" onkeyup="pesquisar()" class="form-control" Autocomplete="off" placeholder="Pesquisa por categoria, nome do livro, descrição do livro, etc">

A: Tente colocar um autocomplete="random-string".


text:
Q: Scrapy forum crawler starting but not returning any scraped data Here is my code, can someone please help, for some reason the spider runs but does not actually crawl the forum threads. I am trying to extract all the text in the forum threads for the specific forum in my start url.
from scrapy.spider import BaseSpider

from scrapy.contrib.spiders import CrawlSpider, Rule

from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor

from scrapy.selector import HtmlXPathSelector

from xbox.items import xboxItem

from scrapy.item import Item
from scrapy.conf import settings

class xboxSpider(CrawlSpider):
    name = "xbox"
    allowed_domains = ["forums.xbox.com"]
    start_urls= [
    "http://forums.xbox.com/xbox_forums/xbox_360_games/e_k/gearsofwar3/default.aspx",
    ]
    rules= [
        Rule(SgmlLinkExtractor(allow=['/t/\d+']),callback='parse_thread'),
        Rule(SgmlLinkExtractor(allow=('/t/new\?new_start=\d+',)))
            ]

    def parse_thread(self, response):
        hxs=HtmlXPathSelector(response)

        item=xboxItem()
        item['content']=hxs.selec("//div[@class='post-content user-defined-markup']/p/text()").extract()
        item['date']=hxs.select("//span[@class='value']/text()").extract()
        return item

Log output:
2013-03-13 11:22:18-0400 [scrapy] DEBUG: Enabled item pipelines:
2013-03-13 11:22:18-0400 [xbox] INFO: Spider opened
2013-03-13 11:22:18-0400 [xbox] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2013-03-13 11:22:18-0400 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:6023
2013-03-13 11:22:18-0400 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080
2013-03-13 11:22:20-0400 [xbox] DEBUG: Crawled (200) <GET forums.xbox.com/xbox_forums/xbox_360_games/e_k/gearsofwar3/f/…; (referer: None)
2013-03-13 11:22:20-0400 [xbox] DEBUG: Filtered offsite request to 'forums.xbox.com': <GET forums.xbox.com/xbox_forums/xbox_360_games/e_k/gearsofwar3/f/…;
2013-03-13 11:22:20-0400 [xbox] INFO: Closing spider (finished)
2013-03-13 11:22:20-0400 [xbox] INFO: Dumping spider stats

A: As a first tweak, you need to modify your first rule by putting a "." at the start of the regex, as follows. I also changed the start url to the actual first page of the forum.
start_urls= [
"http://forums.xbox.com/xbox_forums/xbox_360_games/e_k/gearsofwar3/f/310.aspx",
]
rules = (
    Rule(SgmlLinkExtractor(allow=('./t/\d+')), callback="parse_thread", follow=True),
    Rule(SgmlLinkExtractor(allow=('./310.aspx?PageIndex=\d+')), ),
    )

I've updated the rules so that the spider now crawls all of the pages in the thread.
EDIT: I've found a typo that may be causing an issue, and I've fixed the date xpath.
 item['content']=hxs.selec("//div[@class='post-content user-defined-markup']/p/text()").extract()
 item['date']=hxs.select("(//div[@class='post-author'])[1]//a[@class='internal-link view-post']/text()").extract()

The line above says "hxs.selec" and should be "hxs.select". I changed that and could now see content being scraped. Through trial and error (I'm a bit rubbish with xpaths), I've managed to get the date of the first post (ie the date the thread was created) so this should all work now.


text:
Q: While saving Excel sheet as html, how to add descriptive tags such as "title"? I am in the middle of a project to publish in the internet a table (with some content the nature of which is not important here) in form of a simple html page.
The table is derived from an Excel sheet via saving the sheet as html, then sending the html (plus a folder of accompanying picture and style files) onto the server.
Problem: the html created by Excel (I use currently Excel 2010) does not have a "title" tag in the head section. I should, however, have such a title tag, for improving the chance this page being found by search engines.
Of course I could add a title tag manually to the output html. However, as this is a complex project with several updates per day in the Excel table, I want this title tag to be there automatically, i.e. from the point where I save the Excel sheet as html (for which, by the way, I made a macro procedure enabling me to publish the latest content by just pressing a button).
How can I make Excel include my desired
<title>Something that makes really sense</title>

line into the head section of the html?

A: Excel (as well as LibreOffice) has a Header and Footer that can be defined.
In libreoffice it is Menu:Format > Page > Header  (and Footer) > Edit
As I have no Excel available I can only guess:
It might be in Menu: File > Page format > ... or the corresponding Ribbon entry.
NOW: I would expect the Header content to appear in the HTML, e.g. in  <HEAD>'s <TITLE> subitem

A: *

*Click on Save As, then select Web page on the Save As type box

*Click on Publish, then click on Change button. You should be able to enter a title


text:
Q: Add static image to django Updated  my folder structure is as below:
    After run manage.py collectstatic coomand, the django's static files are copied to my project folder as below, then i put my logo.png to its img/
 mysite_new/

      manage.py
      mysite/
      ------ __init__.py
             urls.py
             setting.py
             wsgi.py
             templates/
                      default.html
             static/
                     img/
                          logo.png
                          .....
      ticket/
      ------__init__.py
            models.py
            view.py
            urls.py
            ......

In setting.py, i set
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_URL = ''
MEDIA_ROOT = ''
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_PATH,'static')
STATICFILES_DIRS = (
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

and in mysite/urls.py i set
        urlpatterns = patterns('',
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/', hello),
    url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT },name="media"),

)

default.html
<!DOCTYPE html>

<meta charset=utf-8>
<title>staitc sample</title>

In ticket/view.py
def hello(request):
     return render_to_response( 'admin/default.html')

Then in web browser, in input http://127.0.0.1:8000/hello, it show
Then i load the image from the "hahhaa", it link to

No picture shown, so maybe the image path is incorrect and the image is not loaded successfull.
  Who can help me to make thie image picture show in my hello method of view.py ?
  This question confused me for a long time, thanks for your help in advance.
  My django version is 1.4.
I have already found the solution, no need to move my static folder, just keep it the same level with ticket/ , and then add ADMIN_MEDIA_PREFIX = '/static/admin/' in setting.py

A: You should move static directory to mysite. The url to logo will be 127.0.0.1:8000/static/images/logo.png
And set STATIC_ROOT one level up:
STATIC_ROOT = os.path.join(PROJECT_ROOT, '..', 'static')

This is where collectstatic command will copy static files of the project and apps.
UPD:
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT },name="media"),

Here should be settings.STATIC_ROOT. For development you can also use:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()

https://docs.djangoproject.com/en/dev/howto/static-files/#staticfiles-development

A: Try the following in urls.py
from django.conf import settings
from django.conf.urls.static import static

And at the bottom of the file
if settings.DEBUG and settings.MEDIA_ROOT:
    urlpatterns += static(settings.MEDIA_URL,
        document_root=settings.MEDIA_ROOT)

A: The problem is in your urls files. You take to django serve function path to media root not your static.
try it:
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/', hello),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT },name="media"),

)

A: Syntax is wrong

Correct syntax-

or


text:
Q: Python Function to use row numbers in a function df['New Column'][0] = chi2_contingency([[df['A'][0],df['B'][0]],[df['C'][0],df['D'][0]]])
df['New Column'][1] = chi2_contingency([[df['A'][1],df['B'][1]],[df['C'][1],df['D'][1]]])
df['New Column'][2] = chi2_contingency([[df['A'][2],df['B'][2]],[df['C'][2],df['D'][2]]])
df['New Column'][3] = chi2_contingency([[df['A'][3],df['B'][3]],[df['C'][3],df['D'][3]]])

Guys, how can I write a function which replaces the code above? I need to update row numbers (range is 0 - 50)?

A: I think you mean that
for x in range(50):
    df['New Column'][x] = chi2_contingency([[df['A'][x],df['B'][x]],[df['C'][x],df['D'][x]]])


text:
Q: Checking permission for another user on Linux Is there a way to know the permissions for a given user (which is not the current user) for a specific file on Linux?
My question assume not switching user with su.

A: This commands return 0, if youruser can read (-r), write (-w) or execute (-x) file or it returns 1 if youruser can't read, write or execute.
sudo -u youruser test -r /path/to/file
sudo -u youruser test -w /path/to/file
sudo -u youruser test -x /path/to/file


text:
Q: CoffeeScript with Node.js not working with classes I've a person.coffee file that contains the following code
class Person
  constructor: (@name) ->
  talk: ->
    "hello"

module.exports = Person

Now I am trying to use it in app.js
Person = require "./person"
p = new Person "Emma"
console.log p.talk

It prints [Function] in the console. Any idea that what is wrong
Note: I've updated the spaces.
Solution: I changed p.talk to p.talk() in app.js and its fixed now.

A: seems like your indent is broken, your code will compile to
var Person;

Person = (function() {

  Person.name = 'Person';

  function Person(name) {
    this.name = name;
    ({
      talk: function() {
        return "hello";
      }
    });
  }

  return Person;

})();

while you want something like this
class Person
  constructor: (@name) ->

  talk: -> "hello"

which will be compiled into
var Person;

Person = (function() {

  Person.name = 'Person';

  function Person(name) {
    this.name = name;
  }

  Person.prototype.talk = function() {
    return "hello";
  };

  return Person;

})();


text:
Q: How can I check that two lines are perpendicular and parallel in polar coordinates? Given two lines $r\cos(\theta-\alpha_1)=k_1$ and $r\cos(\theta-\alpha_2)=k_2$, how can I prove that they are:

*

*Perpendicular $\iff$ $\sin\alpha_1\sin\alpha_2+\cos\alpha_1\cos\alpha_2=0$

*Parallel $\iff$ $\sin\alpha_1\cos\alpha_2-\cos\alpha_1\sin\alpha_2=0$
I know that $r=\pm\sqrt{x^2+y^2}$ and $x=r\cos\theta$, $y=r\sin\theta$
Also, in eucledian coordinates, two lines are perpendicular if $m_1\cdot m_2=-1$ and parallel if $m_1=m_2$
How can I find $m_1$ and $m_2?$

A: The equation of a straight line in polar coordinates is given by $$r=\frac{k}{\sin(\alpha-\theta)}$$ where $k$ is perpendicular distance from the origin to the line and $\alpha$ is the angle made by the line with the polar axis.
Now, for two lines to be perpendicular, we have $$\alpha_2=\alpha_1\pm(2n+1)\frac{π}{2}$$ $$ \implies \alpha_2-\alpha_1=\pm(2n+1)\frac{π}{2}\tag 1$$
For the first part, we have $$\begin{align}LHS&=\sin\alpha_1\sin\alpha_2+\cos\alpha_1\cos\alpha_2\\&=\cos(\alpha_2-\alpha_1)\\ &=0=RHS\end{align}$$
Similarly you can proceed for the second part.

A: $r\cos (\theta + \alpha_1) = k_1$
By angle addition identities.
$r\cos \theta\cos \alpha_1 - r\sin\theta\sin \alpha_1 = k_1$
$r\cos\theta = x\\
r\sin\theta = y$
$x\cos \alpha_1 - y\sin \alpha_1 = k_1\\
y = \cot \alpha_1 - k_1\csc \alpha_1\\
y = m_1 x + b_1$
$m_1 = \cot \alpha_1.$ Similarly, $m_2 = \cot \alpha_2.$
$m_1 = m_2 \implies  \frac {\sin \alpha_1}{\cos\alpha_1} = \frac {\sin \alpha_2}{\cos\alpha_2}$
$m_1m_2 = 1 \implies  \frac {\sin \alpha_1}{\cos\alpha_1} \frac {\sin \alpha_2}{\cos\alpha_2} = 1$
Cross multiply and simplify.


text:
Q: Customize Android Talkback in Toast I've checked with all default Toast message via Android TalkBack. Default Android Talkback behavior is that it reads all contents(non stop) in Toast. Is there any way I can customize it according to my need. For example :
Toast.makeText(getApplicationContext(), "Hello world! Welcome to Android. This is Stackoverflow.", Toast.LENGTH_SHORT).show();

When Toast appears, it reads automatically "Hello world! Welcome to Android. This is Stackoverflow." But I want to control it, like it should read only "Hello world" or "Welcome to Android" or "This is Stackoverflow" etc.

A: I can't think of a reason to do this - typically, you want to have some kind of parity between the information given to your users, regardless of the way they consume the information.
If you're just looking for TalkBack to read aloud text, perhaps you could use the View.announceForAccessibility API directly. That said...

Yes, it's possible to have something different read aloud by the spoken feedback accessibility service than that which is rendered visibly.
Toast toast = Toast.makeText(this, "visible text", Toast.LENGTH_SHORT);
View.AccessibilityDelegate delegate = new View.AccessibilityDelegate() {
    @Override
    public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
        super.onPopulateAccessibilityEvent(host, event);
        event.setContentDescription("audible text");
    }
};
((ViewGroup) toast.getView()).getChildAt(0).setAccessibilityDelegate(delegate);
toast.show();

Note the super hacky way to get a reference to the TextView. This is dangerous because it could break on different implementations of Android.
You can instead set your own view on the Toast directly:
Toast toast = new Toast(this);
TextView messageView = new TextView(this);
messageView.setText("visible text");
View.AccessibilityDelegate delegate = new View.AccessibilityDelegate() {
    @Override
    public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
        super.onPopulateAccessibilityEvent(host, event);
        event.setContentDescription("audible text");
    }
};
messageView.setAccessibilityDelegate(delegate);
toast.setView(messageView);
toast.show();


text:
Q: Prove that every graph has two vertices that are endpoints of the same number of edges
Prove that every graph has two vertices that are endpoints of the same number of edges.

My proof was that in any graph with $n$ vertices, each vertex $v$ has have $1 \leq \deg(v) \leq n-1$. By a simple argument with pigeonhole it is seen that since there are $n$ vertices at least $2$ of them must have the same degree.
This proof seemed to easy to me, so I wanted to know if I made a mistake.

A: That is the main idea of the proof.  However, in principle, the $n$ degrees could be $0,1,2,\ldots,n-1$, which are all different.  If you can explain why this case is impossible, you will have completed the proof.
Good luck!


text:
Q: Multi-Level Includes in CodeFirst - EntityFrameWork It is working code;
IQueryable<Product> productQuery = ctx.Set<Product>().Where(p => p.Id == id).(Include"Contexts.AdditionalProperties.Field");

But you know that it could not produce compile time error if we made mistake in string statement in "Contexts.AdditionalProperties.Field"
I would like to write code below;
IQueryable<Product> productQuery = ctx.Set<Product>().Where(p => p.Id == id).Include(p => p.Contexts);

But above statement could not give chance to define AdditionalProperties and Field.
What should we do?
I would like to write as  more than one include for build query.
Thanks.

A: If AdditionalProperties is a single reference to another object:
using System.Data.Entity;
...
IQueryable<Product> productQuery = ctx.Set<Product>()
        .Include(p => p.Contexts.AdditionalProperties.Field)
        .Where(p => p.Id == id);

If AdditionalProperties is a collection then you can use the Select method:
IQueryable<Product> productQuery = ctx.Set<Product>()
        .Include(p => p.Contexts.AdditionalProperties.Select(a => a.Field))
        .Where(p => p.Id == id);

Don't forget to import System.Data.Entity namespace in your class file!


text:
Q: Youtube Data API Python call via API KEY causes server timeout I want to start working with the Youtube Data API by calling simple search list calls on a local server via the Python implementation. I am only reading data and I want to use the API KEY only to avoid any pop-ups etc.
The sample codes and tutorials usually go with oAuth but it is my understanding that I can go with API KEY only, as long as it is not personal data I am getting.
I have a registered, unrestricted API KEY. The calls work using URLs in the browser. But even a simple python code remains stuck in the execution of the call and I receive a timeout without any response from the server, not a "request denied" though.
Are you able to point me into the right direction to solve this hurdle. The code is:
import os
import googleapiclient.discovery
import googleapiclient.errors

os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

api_service_name = "youtube"
api_version = "v3"
youtube = googleapiclient.discovery.build(
        api_service_name,
        api_version,
        developerKey='my-api-key')

request = youtube.search().list(
        part="snippet")

response = request.execute()
#Never gets past this line

I added os.environ["GOOGLE_APPLICATION_CREDENTIALS"] as was suggested somewhere with a service account file. I played around with different scopes. I used different searches, like channel or video.
I would like to avoid using classic GET and call the URL as used in the browser.
A few posts with issues revolving the API KEY are out there but they typically point at the code I have used above.
UPDATE:
I went through is during the night. Without changing anything, the function worked as expected the next morning. Now in the next night, again the connection issues arise. Is this possibly google disabling the API access during a certain timeframe? I have no network issues otherwise and hence not sure what else could be causing it.


text:
Q: Url rewriting for my website I have try following code to rewrite the url on my website but its not working properly
RewriteEngine on
RewriteRule about/page_id/(.*)/ productlist.php?page_id=$1

Not working properly
but following code working fine..
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php
RewriteRule ^index\.php$ / [L,R=301]
RewriteCond %{HTTP_HOST} !^floratonic\.com
RewriteRule (.*) http://floratonic.com/$1 [R=301,L]

I need suggestion for rewriting for this url
http://floratonic.com/productlist.php?page_id=44

to
http://floratonic.com/productlist.php/44/

OR
http://floratonic.com/productlist.php/PAGENAME/

A: Try:
RewriteCond %{REQUEST_URI} !^/about/page_id/(.*)$ [NC]

RewriteRule  ^about/page_id/(.*)/ productlist.php?page_id=$1

A: You can try simply:
RewriteEngine on
RewriteRule ^about/page_id/(.*)/ productlist.php?page_id=$1 [NC, L]