text:
Q: Image is uploaded but unable getting entry in database Magento 2 I am performing image uploading task in admin form Magento 2. I can choose the image and also can upload it in my module but I'm not getting the entry of that image into my database's table field.

This is my controller.
<?php
namespace Webkul\Grid\Controller\Adminhtml\Grid;

class Save extends \Magento\Backend\App\Action

{

protected $_mediaDirectory;
protected $_fileUploaderFactory;

public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Framework\Filesystem $filesystem,
    \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
)
{
    $this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $this->_fileUploaderFactory = $fileUploaderFactory;
    parent::__construct($context);
}

public function execute()
{
    /*For Image Upload*/

    /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();

    try{
        $target = $this->_mediaDirectory->getAbsolutePath('mycustomfolder/');
        /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
        $uploader = $this->_fileUploaderFactory->create(['fileId' => 'content']);
        /** Allowed extension types */
        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'zip', 'doc']);
        /** rename file name if already exists */
        $uploader->setAllowRenameFiles(true);
        /** upload file in folder "mycustomfolder" */
        $result = $uploader->save($target);

        if ($result['file'])
        {
            $this->messageManager->addSuccess(__('File has been successfully uploaded'));
        }
    }
    catch (Exception $e)
    {
        $this->messageManager->addError($e->getMessage());
    }
    return $this->resultRedirectFactory->create()->setPath(
        '*/*/upload', ['_secure'=>$this->getRequest()->isSecure()]
    );
    /*For Image Upload Finished*/

    $data = $this->getRequest()->getPostValue();
    if (!$data) {
        $this->_redirect('grid/grid/addrow');
        return;
    }
    try {
        $rowData = $this->_objectManager->create('Webkul\Grid\Model\Grid');
        $rowData->setData($data);
        if (isset($data['id'])) {
            $rowData->setEntityId($data['id']);
        }
        $rowData->save();
        $this->messageManager->addSuccess(__('Row data has been successfully saved.'));
    } catch (Exception $e) {
        $this->messageManager->addError(__($e->getMessage()));
    }
    $this->_redirect('grid/grid/index');
}

/**
 * Check Category Map permission.
 *
 * @return bool
 */
protected function _isAllowed()
{
    return $this->_authorization->isAllowed('Webkul_Auction::add_auction');
}
}

A: Finally, I solved my issue.
My controller.
Save.php
<?php
namespace Webkul\Grid\Controller\Adminhtml\Grid;

use Magento\Framework\App\Filesystem\DirectoryList;
class Save extends \Magento\Backend\App\Action
{

protected $_mediaDirectory;
protected $_fileUploaderFactory;

public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Framework\Filesystem $filesystem,
    \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
)
{
    $this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $this->_fileUploaderFactory = $fileUploaderFactory;
    parent::__construct($context);
}

public function execute()
{
    /*For Image Upload*/

    /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();

    try{
        //echo "hi";die;
        $target = $this->_mediaDirectory->getAbsolutePath('mycustomfolder/');

        $targetOne = "mycustomfolder/";
        /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
        $uploader = $this->_fileUploaderFactory->create(['fileId' => 'content']);
        /** Allowed extension types */
        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'zip', 'doc']);
        /** rename file name if already exists */
        $uploader->setAllowRenameFiles(true);
        /** upload file in folder "mycustomfolder" */
        $result = $uploader->save($target);
        /*If file found then display message*/
        if ($result['file'])
        {
            $this->messageManager->addSuccess(__('File has been successfully uploaded'));
        }
    }
    catch (Exception $e)
    {
        $this->messageManager->addError($e->getMessage());
    }

    /*For Image Upload Finished*/

    $data = $this->getRequest()->getPostValue();

    $data['content'] = $targetOne.$result['file'];

    if (!$data) {
        $this->_redirect('grid/grid/addrow');
        return;
    }
    try {

        $rowData = $this->_objectManager->create('Webkul\Grid\Model\Grid');

        $rowData->setData($data);

        if (isset($data['id']))
        {
            $rowData->setEntityId($data['id']);
        }
        $rowData->save();
        $this->messageManager->addSuccess(__('Row data has been successfully saved.'));
    }
    catch (Exception $e)
    {
        $this->messageManager->addError(__($e->getMessage()));
    }
    $this->_redirect('grid/grid/index');

    return $this->resultRedirectFactory->create()->setPath(
        '*/*/upload', ['_secure'=>$this->getRequest()->isSecure()]
    );
}

/**
 * Check Category Map permission.
 *
 * @return bool
 */
protected function _isAllowed()
{
    return $this->_authorization->isAllowed('Webkul_Auction::a    namespace Webkul\Grid\Controller\Adminhtml\Grid;

use Magento\Framework\App\Filesystem\DirectoryList;
class Save extends \Magento\Backend\App\Action
{dd_action');
}
}

My Layout file.
    <?php $collection = $block->getCollectionFor();

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //instance of\Magento\Framework\App\ObjectManager
$storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface');
$currentStore = $storeManager->getStore();
$mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

 ?>
<?php foreach($collection as $data)
        {
            $values = $data['content'];
            ?><img src="<?php echo $mediaUrl.$values; ?>" heigh="50" width="150"/><?php
        }
?>

A: put this code before $rowData->setData($data);
$data['content'] = $data['content']['name'];

Flush cache after update this


text:
Q: Python & Matplotlib - Creating date ticks from string I have an array of strings which contain dates formatted as such: '01/01/09'. I also have an array of floats with the date values.
I want to take these dates and ultimately display them as x tick labels on my graph.
How do I use the floats or strings to label the ticks on the x-axis on my matplotlib graph? (using something like xticks)

A: You set the count (and values) of the ticks using set_xticks.  You set the text of the ticks using set_xticklabels
from matplotlib import pyplot as plt
plt.plot([1,2,3],[3,4,3])
ax = plt.gca()
ax.set_xticks([1,2,3])
ax.set_xticklabels(['1/1','1/2','1/3'])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android: Add arrow heads on poly line using Baidu map? Is it possible to add arrows heads on poly line using Baidu map?

A: I found answer my self and posting answer so it can help to others.
In my case I need to add arrow at the end of the poly line.
I do not find any built in way to do this with Baidu SDK, so I came up with custom solution.
The idea is to find the heading angle between last two points of the poly line, and rotate the arrow bitmap by that angle, and position the angle at the end of poly line.
Solution.
val points = polyline.points
val p1 = points[points.size -1]
val p2 = points[points.size -2]

// heading angle between points (+180 is for bringing the value in 0..360 range, as heading's default range is -180..180 degree)
val angle = SphericalUtil.computeHeading(p1,p2)+180 // SphericalUtil link -> https://github.com/googlemaps/android-maps-utils

// rotate the bitmap to fit last two points direction
val rotatedArrowBitmap = arrowBitmap.rotate(angle) // .rotate(value) is a kotlin extention, find ful method below

val markerOptions = MarkerOptions().position(LatLng(p1.latitude, p1.longitude))
                                 .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
                                 .anchor(0.5f, 0.5f) // this will fit marker center with the p1 coordinate
                                 .flat(true) // this will make marker rotate with map

map.addOverlay(markerOptions)


text:
Q: Cannot set static IP address using Netsh I have followed this article to set the following environment:

*

*DC: Windows Server 2008 R2 Enterprise (Full Installation) - Domain
controller for the lab network, contoso.com

*SQL-A: Windows Server 2008 R2 Enterprise (Full Installation) - Domain
member for hosting SQL Server

*SQL-B: Windows Server 2008 R2 Enterprise  (Full Installation) -
Domain member for hosting SQL Server

*SQL-C: Windows Server 2008 R2 Enterprise (Full Installation) - Domain
member for hosting SQL Server

*SQL-D: Windows Server 2008 R2 Enterprise (Full Installation) - Domain
member for hosting SQL Server

*SQL-CORE: Windows Server 2008 R2 Enterprise (Server Core
Installation) - Domain member for hosting SQL Server

Now I have to executing the following command on the DC machine:
Netsh interface ipv4 set address "Local Area Connection" static 10.10.10.10

but I get error:

Element not found.

I have not got any experience with windows administration and was not able to solve the error googling it.
Could anyone tell what is causing the issue?

A: I had the exact same problem. It turns out that during the setup of my VM, I had multiple LAN connections created (I created mine in VirtualBox) and I ended up deleting the one named "Local Area Connection." My active connection was named "Local Area Connection 2."
I discovered this by running the command: netsh interface ipv4 show interfaces
Then I ran the original netsh command with the interface number instead of the name and it worked.
See here for original source of answer.


text:
Q: What is the span of the following matrix?
What is the span of the following row reduced matrix?
$$\begin{bmatrix}
0&1&0&3&0\\
0&0&1&2&0\\
0&0&0&0&1\\
0&0&0&0&0\end{bmatrix}$$
Explain your answer.

I can't understand how to deal with matrices with one row of 0s and one column of 0s. I thought the parametric equations should be $\{(0, -3d, -2d, d, e)\}$ but I guess I am wrong.

A: The span of the rows of the matrix is simply obtained by multiplying the three non-zero rows by $a,b,c$ respectively and adding: $(0,a,b,3a+2b,c)$ where $a,b,c\in\mathbb R$.


text:
Q: Using Struts2 Iterate an ArrayList> I am trying to display the result of the select query.
PS - I don't want to print the value by typing in the Each Parameter name.
As there are lot of columns.
So what can be the best option and how can I achieve it?
My thought process was to Iterate an ArrayList of ArrayList but how can I do that without the name of each parameter.
In Action Class:
ArrayList<ArrayList<String>> al ;
// It stores the data in this fashion
  al  0->{"abcd","bccd","bank","ased"}
      1->{"visa","Bhan","okas","adwq"}
      ........
      ........

// In Display .jsp

  <s:iterator value="al">
      <S:iterator ...//that's where I am stuck..
</s>

Thanks.


text:
Q: How to write a multiline text on a Material button? I need to make a multiline text material button.
I have followed this question's answers, but it turns out that material buttons work differently.
<com.google.android.material.button.MaterialButtonToggleGroup
    android:id="@+id/toggle_parent_child"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:theme="@style/Theme.MaterialComponents"
    android:visibility="gone"
    app:checkedButton="@id/button_parent"
    app:singleSelection="true">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button_parent"
        style="@style/Login.Button.ToggleButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Parent\n Device" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button_child"
        style="@style/Login.Button.ToggleButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Child \n Device" />

I'm getting this:

but I need every word to be in a different line like this:

A: It might be late but here is my implementation to fix it
class MonsterButtonToggleGroup : MaterialButtonToggleGroup {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
        super.addView(child, index, params)
        if (child is MaterialButton)
            child.maxLines = 2
    }

}

A: you can use replace to make it a multiline string in you MaterialButton like this -
val singleLine = getString(R.string.hello_blank_activity)
demoText.text = singleLine

val multiLine = singleLine.replace(" ", "\n")
demoTextMulti.text = multiLine

Here is the screenshot of the output -


text:
Q: Data catalog and Meta data management in AWS for a Data Lake architecture We are setting up a data platform loosely based on the Data Lake architecture. We are evaluating candidates that provide centralized data catalog and meta-data management and tagging. Glue seems very promising, but it's still not out for public consumption, so we looked into

*

*Ground

*Waterline

*Zaloni

Ground is fairly DYI. It seems we have to extend it extensively to make it work for us. (Scavenging from S3, Writing to Titan)
Waterline and Zaloni are packaged full-blown solutions that might not be what we are looking for since we prefer open-sources, point solutions.
Are there are any alternatives that we should look for? We like the MetaModel available in Ground and are leaning towards using this with Kinesis schema management.

A: It might be worth reconsidering the DIY route. You'll be wasting a lot of time on building the product you want, and supporting it, instead of using it.
I know it's a little marketing fluff, but Zaloni's page says 650% ROI vs. build your own. There's got to be at least a little something in that.


text:
Q: PHPExcel graph design (border, graph color, graph inner position) I'm using PHPExcel to build excel sheet with multiple graphs and im trying to customize them.
i have only 3 problems left unsolved:
1. i want the graph to have no border.
2. i want to change the color of the graphs lines.
3. i want to change the position of the graph inside the graphs area.
as for now this is the way i build graphs:
$xAxisTickValues = $TruexAxisTickValues;
$series = new PHPExcel_Chart_DataSeries(
  PHPExcel_Chart_DataSeries::TYPE_LINECHART,        // plotType
  PHPExcel_Chart_DataSeries::GROUPING_STANDARD,     // plotGrouping
  range(0, 10),                                 // plotOrder
  null,                                         // plotLabel
  $xAxisTickValues,                                 // plotCategory
  $values                                           // plotValues
);
$series->setPlotDirection(PHPExcel_Chart_DataSeries::DIRECTION_COL);
$plotarea = new PHPExcel_Chart_PlotArea(null, array($series));
$chart = new PHPExcel_Chart(
  'chart1',                                       // name
  null,                                           // title
  null,                                         // legend
  $plotarea,                                      // plotArea
  true,                                           // plotVisibleOnly
  0,                                              // displayBlanksAs
  null,                                           // xAxisLabel
  null                                            // yAxisLabel
);
$chart->setTopLeftPosition('C5' );
$chart->setBottomRightPosition('J11' );
$sheet->addChart($chart);

is there a way to do this customize graphs ?

A: As Rzangue stated, PHPExcel does not currently provide an easy way of doing so, however, if you don't mind hard-coding the changes for all graphs created with PHPExcel, you can make the changes suggested below to your PHPExcel/Classes/Writer/Excel2007/Chart.php file.
To alter the chart's border color and thickness, within the public function writeChart(), add:
$cBorderColor = "000000";
$objWriter->startElement('c:spPr');
    $objWriter->startElement('a:ln');
    $objWriter->writeAttribute('w', '40000');//alters border thickness
       $objWriter->startElement('a:solidFill');
           $objWriter->startElement('a:srgbClr');
           $objWriter->writeAttribute('val',$cBorderColor);//changes the color
           $objWriter->endElement();
       $objWriter->endElement();
    $objWriter->endElement();
$objWriter->endElement();

after:
    $objWriter->startElement('c:showDLblsOverMax');
        $objWriter->writeAttribute('val', 0);
    $objWriter->endElement();

$objWriter->endElement();

but before:
$this->_writePrintSettings($objWriter);

which should be around line 106 of the Chart.php file.
Obviously replacing "000000" with whatever web color you desire to be your chart border color to be.  To remove the border color entirely, insert:
$objWriter->startElement('c:spPr');
    $objWriter->startElement('a:ln');
        $objWriter->startElement('a:noFill');
        $objWriter->endElement();
    $objWriter->endElement();
$objWriter->endElement();

instead.
Next, to alter the positioning of the plot area within the chart, scroll down within the Chart.php file to the private function _writeLayout().
Delete all code within the function besides the open/close brackets {}.  Within the function, add:
$layoutTarget = "inner";
$xMode = "edge";
$yMode = "edge";
$xOffset = 0.1;  //The left margin in percentage of graph width.
$yOffset = 0.1;  //The top margin in percentage of graph width.
$paWidth = 0.9;  //The percentage width of the plot area relative to the graph width;
$paHeight = 0.9; //The percentage height of the plot area relative to the graph height;

$objWriter->startElement('c:layout');
    $objWriter->startElement('c:manualLayout');
        $objWriter->startElement('c:layoutTarget');
            $objWriter->writeAttribute('val',$layoutTarget);
        $objWriter->endElement();
        $objWriter->startElement('c:xMode');
            $objWriter->writeAttribute('val',$xMode);
        $objWriter->endElement();
        $objWriter->startElement('c:yMode');
            $objWriter->writeAttribute('val',$yMode);
        $objWriter->endElement();
        $objWriter->startElement('c:x');
            $objWriter->writeAttribute('val',$xOffset);
        $objWriter->endElement();
        $objWriter->startElement('c:y');
            $objWriter->writeAttribute('val',$yOffset);
        $objWriter->endElement();
        $objWriter->startElement('c:w');
            $objWriter->writeAttribute('val',$paWidth);
        $objWriter->endElement();
        $objWriter->startElement('c:h');
            $objWriter->writeAttribute('val',$paHeight);
        $objWriter->endElement();
    $objWriter->endElement();
$objWriter->endElement();

You can then adjust the x/y offset and w/h as you wish.
To control/change the colors of each data series, within:
private function _writePlotGroup()

before:
foreach($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) {

add:
$ci=-1;
$colorNDX=array();
$colorNDX[0] = "111111";
$colorNDX[1] = "222222";
$colorNDX[2] = "333333";
$colorNDX[3] = "444444";
$colorNDX[4] = "555555";
$colorNDX[5] = "666666";
$colorNDX[6] = "777777";

and so on, being sure to add enough color indexes for all series of data and obviously changing the 111111,222222,333333 to web colors of your liking.
Also, after:
foreach($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) {

Add:
$ci++;

And after:
//  Labels
$plotSeriesLabel = $plotGroup->getPlotLabelByIndex($plotSeriesRef);
if ($plotSeriesLabel && ($plotSeriesLabel->getPointCount() > 0)) {
    $objWriter->startElement('c:tx');
    $objWriter->startElement('c:strRef');
        $this->_writePlotSeriesLabel($plotSeriesLabel, $objWriter);
    $objWriter->endElement();
$objWriter->endElement();
}

Add:
$objWriter->startElement('c:spPr');
    $objWriter->startElement('a:solidFill');
        $objWriter->startElement('a:srgbClr');
            $objWriter->writeAttribute('val',$colorNDX[$ci]);
        $objWriter->endElement();
    $objWriter->endElement();
$objWriter->endElement();

Let me know if this helps.  Again, these changes will be applied to all charts generated by PHPExcel, however, a couple well placed if statements should be more than enough to make the changes more dynamic on a per chart type basis.

A: Adding IIIOXIII's code, specifically the following block, when using LineCharts caused Excel 2007 to error for me
$objWriter->startElement('c:spPr');
 $objWriter->startElement('a:solidFill');
  $objWriter->startElement('a:srgbClr');
   $objWriter->writeAttribute('val',$colorNDX[$ci]);
  $objWriter->endElement();
 $objWriter->endElement();
$objWriter->endElement();

Firstly add the following condition statement around the above block
if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_LINECHART && $groupType !== PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) {
    // above code block
}

Then after the block around a dozen lines further down the code which reads
if ($groupType == PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) {
  $objWriter->startElement('a:noFill');
  $objWriter->endElement();
}

add the following
$objWriter->startElement('a:solidFill');
  $objWriter->startElement('a:srgbClr');
   $objWriter->writeAttribute('val',$colorNDX[$ci])
  $objWriter->endElement();
$objWriter->endElement();

This will then prevent Excel from erroring and allow you to colour line charts

A: In my case I wanted to change to original colors of the pie chart, I was able to accomplish this by editing the PHPExcel_Writer_Excel2007_Theme class without editing its original writer Excel2007 like so:

*

*copy Excel2007 folder and past it in the same folder with a different name e.g. 'Excel2007Custom'

*open all the classes in the Excel2007Custom folder and rename the classes e.g.
PHPExcel_Writer_Excel2007_Chart will become PHPExcel_Writer_Excel2007Custom_Chart
PHPExcel_Writer_Excel2007_Comments will become  PHPExcel_Writer_Excel2007Custom_Comments
and so on.

*

*copy Excel2007.php file and past it in the same folder with a different name e.g. 'Excel2007Custom.php'

*open the class file Excel2007Custom.phpand:

*

*rename the classes from  PHPExcel_Writer_Excel2007 will become PHPExcel_Writer_Excel2007Custom

*change the array $writerPartsArray value in the constructor.

from:

    $writerPartsArray = array(
        'stringtable'   => 'PHPExcel_Writer_Excel2007_StringTable',
        'contenttypes'  => 'PHPExcel_Writer_Excel2007_ContentTypes',
        'docprops'      => 'PHPExcel_Writer_Excel2007_DocProps',
        'rels'          => 'PHPExcel_Writer_Excel2007_Rels',
        'theme'         => 'PHPExcel_Writer_Excel2007_Theme',
        'style'         => 'PHPExcel_Writer_Excel2007_Style',
        'workbook'      => 'PHPExcel_Writer_Excel2007_Workbook',
        'worksheet'     => 'PHPExcel_Writer_Excel2007_Worksheet',
        'drawing'       => 'PHPExcel_Writer_Excel2007_Drawing',
        'comments'      => 'PHPExcel_Writer_Excel2007_Comments',
        'chart'         => 'PHPExcel_Writer_Excel2007_Chart',
        'relsvba'       => 'PHPExcel_Writer_Excel2007_RelsVBA',
        'relsribbonobjects' => 'PHPExcel_Writer_Excel2007_RelsRibbon'
     );

to:

    $writerPartsArray = array(
        'stringtable'   => 'PHPExcel_Writer_Excel2007Custom_StringTable',
        'contenttypes'  => 'PHPExcel_Writer_Excel2007Custom_ContentTypes',
        'docprops'      => 'PHPExcel_Writer_Excel2007Custom_DocProps',
        'rels'          => 'PHPExcel_Writer_Excel2007Custom_Rels',
        'theme'         => 'PHPExcel_Writer_Excel2007Custom_Theme',
        'style'         => 'PHPExcel_Writer_Excel2007Custom_Style',
        'workbook'      => 'PHPExcel_Writer_Excel2007Custom_Workbook',
        'worksheet'     => 'PHPExcel_Writer_Excel2007Custom_Worksheet',
        'drawing'       => 'PHPExcel_Writer_Excel2007Custom_Drawing',
        'comments'      => 'PHPExcel_Writer_Excel2007Custom_Comments',
        'chart'         => 'PHPExcel_Writer_Excel2007Custom_Chart',
        'relsvba'       => 'PHPExcel_Writer_Excel2007Custom_RelsVBA',
        'relsribbonobjects' => 'PHPExcel_Writer_Excel2007Custom_RelsRibbon'
     );

*

*And then editing PHPExcel_Writer_Excel2007Custom_Theme class $_colourScheme class property

*In the end I called the class writer like so:

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007Custom');

A: Just took some hours to have a look on that -> change the color of the graphs.
Open the files Theme.php
\PHPExcel\Classes\PHPExcel\Writer\Excel2007\Theme.php
At the bottom, you will find:
private function writeColourScheme($objWriter)
{
    foreach (self::$colourScheme as $colourName => $colourValue) {
        $objWriter->startElement('a:'.$colourName);

            $objWriter->startElement('a:srgbClr');
                $objWriter->writeAttribute('val', $colourValue);
            $objWriter->endElement();

        $objWriter->endElement();
    }
}

Instead, You will have to place this:
private function writeColourScheme($objWriter)
{
    $ci = 0;
    $colorNDX=array();
    $colorNDX[0] = "a09a9a";
    $colorNDX[1] = "1b1b1b";
    $colorNDX[2] = "350d0d";
    $colorNDX[3] = "ff0000";
    $colorNDX[4] = "b9a8a8";
    $colorNDX[5] = "a09a9a";
    $colorNDX[6] = "ff0000";
    $colorNDX[7] = "a09a9a";
    $colorNDX[8] = "1b1b1b";
    $colorNDX[9] = "ff0000";
    $colorNDX[10] = "1b1b1b";

    foreach (self::$colourScheme as $colourName => $colourValue) {

        $objWriter->startElement('a:'.$colourName);
            $objWriter->startElement('a:srgbClr');
            $objWriter->writeAttribute('val', $colorNDX[$ci]);
            $objWriter->endElement();

            $ci++;
        $objWriter->endElement();
    }
}

Hope this work for you :-)

A: The current release: PHPExcel 1.7.9 doesn't allow to do anything you want.

A: In the piecharts I found that PHPExcel write only 1 datapoint from serie, number 3 (why not 5,or 1, I don't know =) ),  therefore if you want to customize colors of pies, you have to edit file Classes/PHPExcel/Writer/Excel2007/Charts.php in function _writePlotGroup
//Getting datapoints and  loop around $objWrite->startElement(c:dPt)
 $plotSeriesValues = $plotGroup->getPlotValuesByIndex($plotSeriesRef);
if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) ||
                    ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) ||
                    ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) {

foreach($plotSeriesValues->getDataValues() as $plotSeriesKey => $plotSeriesValue) {
...
   /*instead of $objWriter->writeAttribute('val', 3); put after
 $objWriter->startElement('c:dPt');
                        $objWriter->startElement('c:idx');*/
$objWriter->writeAttribute('val', $plotSeriesKey);
//according to previous answer, find the color of pie by index of datapoint in colorNDX

$objWriter->writeAttribute('val',$colorNDX[$plotSeriesKey]);


text:
Q: is there a size limit for inline strings in ruby? Is there a string size limitation for any of the cases below?
str1 = 'looong text'
str2 = "#{text_var}"

A: No size limitation.
You can define long multi-line strings either through "HERE" documents like this:
str = <<THE_END

some

very

long

text

THE_END

or like this:
str = %Q{
some

very

long

text

}


text:
Q: find img tag inside a tag with regex I have a HTML string and I want to find image links like
I try this regex pattern but it's not working: "\<a\s.*\<img.*\<\/a\>"
When I use that pattern it finds a string like some text1some text2. but I don't want first <a href part. I just want img tags inside a tag and I need help about it.

A: When you want only part of your overall regex you need to use groups or back references( ).
"\<a\s.*\()<\/a\>"

Then depending on the language you need to get the first group.
http://www.regular-expressions.info/brackets.html
Update:
To match exactly  try:
 \<a[^<]*\<img.*\<\/a\>

instead of a \s I used [^<] which is any character except a <.


text:
Q: Java incremented object names My current issue that I am overwriting my cell object. Since I cannot do ("cell" + i), how would I be able to do this?
public void printMonthCounts(int cellMonthPosition, String month) {

        for (int i = 0; i < 10; i++) {//11 countrys
            Row row = sheet2.createRow(7 + i);//Starts with Gb
            Cell cell = row.createCell(cellMonthPos);//Month position

            switch (i) {
                case 0:
                    cell.setCellValue(countryHash.get(month).getGb());
                    break;
                case 1:
                    cell.setCellValue(countryHash.get(month).getPt());
                    break;
                case 2:
                    cell.setCellValue(countryHash.get(month).getEs());
                    break;
            }
        }

I am using Apache POI for excel, but I know this to be a general Java 'thing', I am beginner in Java.
How can I have an incremented object names?
*The switch case is longer but I shortened it for this example.

A: If I got this right, you want to dynamically create object names? Long story short, you can't. The usual way to do this is to use an array: instead of trying to create n objects called cell1, cell2, etc just create an array of cells and create each object at the ith position of your array.

A: Maybe you should try creating an array and increment the index using a loop

A: you can do that, if I am getting your question right, by setting  a temporary string that holds the string plus the incremented number. After that, you can name your object with the temporary  string.
As in my situation,
temp = "row" + String.valueOf(k); //k is incremented int
    temp2 = temp; //I stored the value of temp because it changes to obj
    Row temp = new Row();
    temp.setNamel(temp2);//this is a method in my class Row to set name
    temp.setClientName((String)nameField.getText());
    k++;
    System.out.println(temp.getClientName());
    System.out.println(temp.getID());
    System.out.println(temp.getNamel());//to return the name of object

Output:
John
0
row0


text:
Q: create and insert into temporary table using mysql stored procedure I have a stored procedure as follows.
Here I have created a temporary table named tempDesTable and put the data from database. Now I have to put additional data from another select query. But it shows Error Code : 1327 Undeclared variable: tempDesTable
BEGIN

    CREATE TEMPORARY TABLE tempDesTable AS (SELECT ID, FirstName, LastName FROM t_users WHERE `DesignationID` = p_DesignationID AND BranchID = 0);

    SELECT ID, FirstName, LastName INTO `tempDesTable` FROM t_users WHERE `DesignationID` = p_DesignationID AND BranchID = p_BranchID;

END$$

A: You need to use insert ... select rather than select ... into
INSERT INTO tempDesTable SELECT ID, FirstName, LastName FROM t_users
WHERE `DesignationID` = p_DesignationID AND BranchID = p_BranchID;


text:
Q: Synchronize timestamps on directories Let's say I have two directories with the same structure and I want to set the timestamps of files, contained in the second to those of the first if and only if  the content of the files is the same.
I give an answer here but if you guys have less clumsy and more efficient ways of achieving the goal, that would be perfect.

A: An even easier way is simply:
rsync -uav /path/to/dir1/ /path/to/dir2

(removing v suppresses --verbose output)
note: the trailing '/' following dir1. It tells rsync to take the contents of dir1 instead of dir1 itself.

A: One possible solution is this script:
#!/bin/bash

OLDDIR=$(readlink -f $1)
NEWDIR=$(readlink -f $2)

cd $NEWDIR
for file in $(find .); do
    file2=$OLDDIR/$file
    if test -e "$file2" && diff >/dev/null -q "$file" "$file2" ; then
        touch -r "$file2" "$file"
    fi
done


text:
Q: How to show user's own retweet of other people's tweet in discord bot? Im trying to add a retweet feature to my discord bot such that it can show the user retweeted post. I have tried to do something like this, but when i run my code it still only post new tweets. Can anyone help troubleshoot?
Let me try to simplify the scenario cuze i think it might be abit hard to say what i actually wanna achieve.

*

*Imagine if i am a twitter user called @hojitea(jus an example). I follow a user in twitter called @readDonaldTrump.

*What i would want my discord bot to do is to not only get new tweet that @realDonaldTrump has posted, but also the retweets that he did.

*So like this image(i wanna get this retweet in my discord bot):

*Note that in the image, it states 'Donald J. Trump Retweeted', which is what i want my discord bot to also display, not any other user. This is unachievable based on my current code.

Right now, this is how it looks like(a snippet of the entire source code):
// setting up necessary libraries
require('dotenv').config();
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.commands = new Discord.Collection();
const botCommands = require('./commands');
const Twitter = require('twit')

//Set up discord and twitter token blah blah blah...

const twitterClient = new Twitter(twitterConf);

// create a stream to follow tweets
const stream = twitterClient.stream('statuses/filter', {
    follow: '25073877', //donaldtrump twt id
});

const dest = '765217504305872896' //streaming twts to #twitter channel

// TWITTER MAIN PROCESS
// stream directly to that channel
stream.on('tweet', tweet => {
    if (tweet.retweeted_status  //to prevent other user tweets and only get specifically from the user
        || tweet.in_reply_to_status_id_str
        || tweet.in_reply_to_user_id
        || tweet.in_reply_to_user_id_str
        || tweet.in_reply_to_screen_name) return true;

    if (tweet.current_user_retweet) { //to show the retweeted message by the user
        const twitterRetweetMessage = `**${tweet.user.name} (@${tweet.user.screen_name}) new retweet!**\n https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`
        bot.channels.cache.get(dest).send(twitterRetweetMessage);
        console.log(`A new retweet has been posted by @${tweet.user.screen_name}!`)
        return false;
    }
    const twitterMessage = `**${tweet.user.name} (@${tweet.user.screen_name}) new tweet!**\n https://twitter.com/${tweet.user.screen_name}/status/${tweet.id_str}`
    bot.channels.cache.get(dest).send(twitterMessage);
    console.log(`A new tweet has been posted by @${tweet.user.screen_name}!`)
    return false;
});

// acknowledge bot has connected
bot.on('ready', () => {
    console.log(`Logged in as ${bot.user.tag}!`);
});

DISCLAIMER: I AM NOT A US CITIZEN BY ANY CHANCE. THE USERNAME USED IS PURELY MEANT AS AN EXAMPLE AND NOT A US ELECTION PROPOGANDA.

A: According to the Twitter documentation (this link is for GET statuses/show/:id, but all Tweet objects follow the same format anyway), current_user_retweet is only supplied if the authenticating user (@hojitea) retweeted the tweet. Since the Tweet object is supplied directly after a Tweet is posted, it is near impossible that the authenticating user has already retweeted the tweet.
You have to remove tweet.retweeted_status from the big if statement if you want to parse retweets. This will also show all Retweets of that person's tweets, so to filter out tweets by other users, just check if the ID of the user you're subscribed to is equal to the id of the user in the tweet object (tweet.user.id). You'd want to put this before processing any tweets, so you'd put it right before the aforementioned if statement.
To check if the Tweet is a Retweet, use tweet.retweeted_status for your if statement instead. This value is always supplied for retweets, but is always null for non-retweets.
// ...
if (tweet.retweeted_status) { // true if the tweet was a retweet.
    const twitterRetweetMessage = `**${tweet.user.name} ...`
// ...

P.S.: If I were to be a bit nitpicky, the message should be `A new Tweet has been retweeted by @${tweet.user.screen_name}!` instead, since the retweeting user technically didn't post the Tweet.


text:
Q: Google Admin SDK Directory API User Privileges Can a normal user account in my domain access the function on Google OAuth2 directory service API to retrieve users list or data ?
I have a web-application which allow the users to login with OAuth2.0. After that, the users should be able to see their profile data.
If I am using a super admin login, everything work just fine which the data is displayed. When I am using a normal user login and a group admin login, I cannot see any data and receive error message as follow:
    Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/admin/directory/v1/users/yifei.liu@example.com?key=(MY_API_Key): (403) Not Authorized to access this resource/api' in /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php:66 Stack trace: #0 /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))
#1 /home2/iaapro/public_html/php/google-api-php-client/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest))
#2 /home2/iaapro/public_html/php/google-api-php-client/src/contrib/Google_DirectoryService.php(653): Google_ServiceResource->__call('get', Array)
#3 /home2/iaapro/public_html/php/google-plus-access.php(47): Google_UsersServiceResource->get('yifei.liu@iaapr...')
#4 /home2/iaapro/public_html/php/index.php(2): include_once('/home2/iaapro/p...')
#5 {main} thrown in /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php on line 66

Does it mean that only account with domain super admin rights can access the Google Admin SDK Directory API ? Is it possible for me to allow normal user to use this API too ?
Thanks.

A: Yes.  A normal user can retrieve Directory contacts for your domain in read-only mode.  They can't make changes to anything in the Directory.
To list Directory contacts, you'll need to
$client->addScope("https://www.googleapis.com/auth/admin.directory.user.readonly");

in your oauth flow.
Then to retrieve, do something like this:
$service = new Google_Service_Directory($client);
$optParams = array(
        'domain' => 'google.domain.com',
        'orderBy' => 'email',
        'viewType' => 'domain_public',
        'query' => "givenName:'Joe' familyName:'Schmoe Jr'"
);
$results = $service->users->listUsers($optParams);
$users = $results->getUsers();

You can also do this entirely via a service account, in which case your user never needs to go through the oauth step.  See here for a working example: Google php client library loadServiceAccountJson broken - fix enclosed

A: No. A "normal" user can not manage the users of your domain. For example, only Admin accounts can Create, Delete or update info. about the users.
Please, take a look in the Admin SDK page If you want to manage contacts
A "normal" user can manage his/her contacts. They can see the email, telephone number, labels, etc., etc.
You can visit  visit Google contacts API V3 for more information about it.


text:
Q: Getting and extra size on my page as you can see in this links
http://hybrid-tech.net/clients/ferrara/onepagemodel1/
and the end of the page I getting a white line and I don't understand why.
Could you help me to resolve this issues.
Thanks in advance for your help.

A: Remove the padding-bottom line in body of the CSS; that makes that "white line" appear.
body {
    padding-bottom: 40px;
    color: #5a5a5a;
}

to
body {
    color: #5a5a5a;
}


text:
Q: Autofocus on form inputs within list items I have a form and the inputs are in list items so as to display each input one at a time as the user enters information. I can not get autofocus to work. When the user clicks enter, the current input slides out and the next one slides in but does not have the cursor in the field.

                <form id="myform" class="fs-form fs-form-full" autocomplete="off">

                            What's your name?
                            <input class="fs-anim-lower" id="q1" name="q1" type="text" placeholder="Joe Web" required/>

                            What's your email address?
                            <input class="fs-anim-lower" id="q2" name="q2" type="email" placeholder="jweb@dev.com" required/>

                            Leave me a note here
                            <textarea class="fs-anim-lower" id="q4" name="q4" placeholder="Describe here"></textarea>

                    <button class="fs-submit button button--nuka" type="submit">Ready? submit</button>

This js didnt work and Im not sure why
$(document).ready(function(){
            $('.fs-anim-upper').on('keypress', function(e) {
                if(e.which == 13) {
                    switch($(this).attr('id')){
                        case 'q2':
                        $('#q2').focus();
                        e.preventDefault();
                        break;
                        case 'q3':
                        $('#q3').focus();
                        e.preventDefault();
                        break;
                    }
                }
            });
        });

A: You have several issues in your code
Issue: wrong selector
You have now:
$('.fs-anim-upper').on('keypress', function(e) {

These are the labels in your html not the inputs. Change it to:
$('.fs-anim-lower').on('keypress', function(e) {

Issue: most probably wrong id's
 case 'q2':
  $('#q2').focus();
  e.preventDefault();
  break;
 case 'q3':
  $('#q3').focus();
  e.preventDefault();
  break;

This means, when you press enter give focus to yourself.. I think you want:
case 'q1':
    $('#q2').focus();
    e.preventDefault();
    break;
case 'q2':
    $('#q4').focus(); // <--- Note that you have q4 in html, not q3
    e.preventDefault();
    break;

See here for a working fiddle: http://jsfiddle.net/6mm6gc9a/7/


text:
Q: Searchlogic - searching for exact match I am using Searchlogic to perform searches on my 'report' index page.
<% form_for @search do |f| %>
  Search:
  <%= f.text_field :report_id_like, :size=> 50 %>
  <%= f.submit "Search" %>
<% end %>

Currently, if I search for a report with report id '5', I get a list of entries with report id containing '5'.
I would like to get only the record with report_id '5' when I input '5'.
Any suggestion?
Many thanks

A: Got the answer:
Instead of :
<%= f.text_field :report_id_like, :size=> 50 %>

Put:
<%= f.text_field :report_id_equals, :size=> 50 %>

Hope it might be of help to someone else


text:
Q: Which DML Events Cause Trigger Recursion I am curious, besides the UPDATE DML event causing trigger recursion (an update causing another update due to a field update), what other scenarios can result in trigger recursion.
I would like to know so I can be mindful of these scenarios when designing triggers in the future.

A: There is no correct answer to this question as it's always going to depend on what triggers and workflows are configured in a given org.
Like you say, updating the records being processed in an update trigger is likely to set off a waterfall, but so is insert in an insert, inserting in an update when there's an insert trigger etc., the number of scenarios is huge.
You could have a trigger on insert of Object A that inserts a record of Object B, which then creates an insert of Object A... the list goes on and on.
The best way to protect yourself is to use a trigger framework, a decent naming scheme, and implement recursion control in triggers that could be at risk.


text:
Q: Create a root node in binary tree python structure class Tree:
    class Node:
        def __init__(self, left=None, right=None, parent=None, element=None):
            self.left = left
            self.right = right
            self.parent = parent
            self.element = element

    class Position:
        def make_position(self, node):
            def __init__(self):
                """Create an initially empty binary tree."""
                self.root = None
                self.size = 0

            def root(self):
                """Return the root Position of the tree( or None if tree is empty)."""
                return self.make_position(self.root)

            def add_root(self, e):
                """Place element e at the root of an empty tree and return new Position.
                Raise ValueError if tree nonempty."""
                if self.root is not None:
                    raise ValueError("Root Exist")
                self.size = 1
                self.root = self.Node(e)
                return self.make_position(self.root)

I'am a beginner with python and python data structure.
  How can I call at the end of file .py the methods add_root and print this method to see the element in root node?
  I tried to write

root = Tree.Position()
print(root.make_position(root))
root = Tree.Position.make_position()
print(root.make_position(root))

but the interpreter return an AttributeError

A: It's not very typical to define classes within other classes. I would recommend defining Tree, Node, and Position separately and then including those objects within the classes that require them. Also, it doesn't make much sense to define functions inside other functions. Functions should be defined independently from each other. Something like this:
class Tree:
    def __init__(self, root=None):
        self.root = root
    def print_values(self, root):
        if root == None:
            return
        self.print_values(self.root.left)
        print root.data
        self.print_values(self.root.right)
    #Define other tree operations that you want to perform here

class Node:
    def __init__(self, data=0, left=None, right=None):
        self.data = data
        self.left=left
        self.right=right

#Create a root node
root = Node(0)
#Create a tree with the root node
m_tree = Tree(root)
#Add a left and right node to the root
left_node = Node(3)
right_node = Node(4)
root.left = left_node
root.right = right_node
m_tree.print_values(m_tree.root)


text:
Q: If function with multiple inputs that returns text strings with variable Essentially I have 4 columns of values I'm pulling from.
A: "Old # of Cards"
B: "Old Std Pack Qty"
C: "New # of Cards"
D: "New Std Pack Qty"
In a separate column E, I comment what changes need to be made.
If all values stay the same then I write "Keep Same"
If the A > C "Delete X card(s)" or if A < C "Add X card(s)" where X = A-C or C-A
If B ≠ D "Change Std Pack to Y" where Y = B-D or D-B
Also if A ≠ C and B ≠ D then "Add/Delete X Card(s); Change Std Pack to Y"
I almost had it figured out with a bunch of nested if(and's but I'm struggling with getting that "X" variable between the "Add/Delete" and the "card(s)". Also not sure if it's possible to pluralize the "card" if > 1. I'm sure there may be an easier way that doesn't involve the if formulas but I'm not sure what that would be.
Here is what my table would look like:

A: Assuming your table is in A1 to E7.
Place the following formula in E2 and copy down
=IF(AND(A2=C2,B2=D2),"Keep Same",IF(A2<>C2,IF(A2>C2,"Delete ","Add ")&ABS(A2-C2)&" card"&IF(ABS(A2-C2)<>1,"s",""),"")&IF(AND(A2<>C2,B2<>D2),"; ","")&IF(B2<>D2,"Change Std Pack to "&D2,""))

Note the following part from the formula above is optional.  It is just taking care of placing the s on the end of card when there is more than 1 card being added or deleted.
&IF(ABS(A2-C2)<>1,"s","")


text:
Q: Accessing a Page Factory's declared Using Using C#, suppose I've declared a web element as follows
[FindsBy(How = How.Id, Using = "foo")]
private IWebElement bar { get; set; }

Is there any way to access this element's locator, "foo" inline using the element?
Something like
string locator = bar.GetTheUsing


text:
Q: Зачем нужна функция std::iter_swap? В стандартной библиотеке есть функция std::iter_swap.
Зачем она нужна, если можно самому написать
using std::swap; swap(*a, *b);

A: Во-первых, эта функция выполняет такую же роль, как и std::next, она гарантирует, что операция разыменования итератора производится для lvalue, а не rvalue.
Стандарт требует что для переменной-итератора i можно написать *i, однако он не требует что можно написать *f(), поэтому следующий код может не скомпилироваться (или работать не так), если итератор не поддерживает разыменование rvalue:
swap(*first, *std::max_element(std::next(first), last));  // ПЛОХО, может не работать

Во-вторых, для того чтобы была возможность использовать пользовательские реализации функции swap, вместо std::swap(*a, *b) надо писать
using std::swap; swap(*a, *b);

что выглядит несколько длинно, и об этом легко забыть.
Также, теоретически std::iter_swap может быть перегружена для итераторов связанных списков, так что вместо обмена самих элементов списка, меняются только связи на его элементы. Впрочем алгоритмы стандартной библиотеки вызывают std::iter_swap, что отключает поиск пользовательских функций.


text:
Q: Query to find phone number based on combination of other column? Query to select all phone number from combination of circle, subscriber Type, subscriber sub type, Device Type with RES status as "Y".
select combination of circle, subscriber Type, subscriber sub type, Device Type with RES status as "Y"
Suppose a table contain data as shown

It is just a sample
How can I find all the phone number in different combination of other column
as Subscriber type, Subscriber Sub type, Device Type, RES (Prepaid,Consumer,Mobile ,y)?

A: If I understand the question correctly, you can write a simple SELECT query to get these, e.g.:
SELECT phone_number subscriber_type, subscriber_sub_type, device_type
FROM table
WHERE res = 'y';


text:
Q: Visio VBA copy/cut/paste intercept I have another challenge. Has anyone tried to intercept the copy/paste events? My goal is to prevent someone from cut/copy/paste a shape that is already on a sheet. If they drag it from a stencil, that is fine. I just can't have them duplicate an existing shape. To make this a bit harder, it is only the shape that I need to prevent. If the want to copy text, that is fine.
We have a order type database that contains items that need to be dropped on a Visio sheet. I cannot use the shapeID because I need to be able to update the shape from the database and I can't write the ID back to the database as it is against security policy. The way that I am tying the two together is a property named shapeKey and that value is provided by the database at the time the shape is dropped.
When a use needs to refresh the sheet from the database, I interate through the shapes, comparing the shapeKey in the shape and in the database. if there is a match, I do an update of the other properties. If there is no match, I want to delete the shape. if a user copies a shape, the shapeKey will also be duplicated and that causes problems. Lastly, they can add their own shapes from stencils and those shapes must be excluded from the delete process
I have two options:

*

*Disable shape cut/copy/paste

*Intercept the copy/cut and when they paste, change a property so that I know that it was a user pasted shape. This is preferred because it is more user friendly

*I just thought if another way I that might work. Is there a way to lock the shapes to prevent the copy? If there is a lock, would that also lock the location? The user needs to be able to most the shapes around.

I thought about capturing the event but I could not find the event codes to look for. I cannot install the Visio SDK which has the Event monitor. The monitor might have shown me the code. Here is some pseudo code as to what I think would be the flow.
option 1
if select item is a shape then
    msgbox "shape copying verboten. please us the stencil"
    clear selected item

option 2
capture the paste event
    if selected item is a shape then
        vsoShape.Cells("Prop.ShapeKey").Formula = Chr(34) & "protect" & Chr(34)

Layers might work. All the database controlled shapes can be on one layers and all the user shapes on another but I haven't worked with layers before. would that work? How can I be sure that any shape pasted goes onto the user layer?

A: Thanks all! I did find a solution and it was really elegant. I found the idea here and changed it to what I needed:
Shape added event: https://msdn.microsoft.com/en-us/library/office/ff767288.aspx
Here is what I came up with:
Private Sub Document_ShapeAdded(ByVal vsoShape As Visio.IVShape)
    If vsoShape.CellExistsU("Prop.ShapeName", 0) Then
        vsoShape.CellsU("Prop.ShapeName").Formula = Chr(34) & "ShapeName" & Chr(34)
    End If
End Sub

The interesting thing is that it doesn't fire if I add the shape via VBA. That is perfect for what I need but I would have thought that dropping a shape is adding a shape. I am only looking for one property because not all shapes on the stencils come from a database and for those objects, I don't need to do anything.
It was not the solution that I expected but it works really well.


text:
Q: How to temporarily highlight editable columns of Ext JS grid panel (version 4.2.1) I am using a grid panel from ExtJS 4.2.1. I have some column definitions with editor : 'textfield' (editable columns) and some without editor (read-only columns).
What I want?
I want to temporarily highlight the editable column with a background color at the on mouse over event to that specific column.
I request for help. Please guide. I have spent lot of time on it and all in vain :(
Regards,
Jagpreet Singh
TASK - When mouse is placed over columns Editable 1 and 2 below (having editor config option), I want the target column to be highlight temporarily with some bright color for few seconds.
Ext.define('XX.view.account.Portfolios', {
extend : 'Ext.grid.Panel',
plugins : {
    ptype : 'cellediting',
    clicksToEdit : 1
},
columns : [{
    text : 'Read Only 1',
    flex : 1,
    sortable : true,
    dataIndex : 'ro1'
}, {
    text : 'Read Only 2',
    flex : 2,
    sortable : true,
    dataIndex : 'ro2'
}, {
    text : 'MV',
    flex : 1,
    sortable : true,
    dataIndex : 'mv'
}, {
    text : 'Editable 1',
    flex : 1,
    sortable : true,
    dataIndex : 'e1',
    editor : 'textfield'
}, {
    text : 'Editable 2',
    flex : 1,
    sortable : true,
    dataIndex : 'e2',
    editor : 'textfield'
}

A: As Lorenz suggested you can catch the itemmouseenter event and then highlight the editable rows calling highlight method, in order to only highlight those cells that have editors associated you probably can use a class applied to those columns, and then select the matching elements on the mouse enter event handler, something like this:
itemmouseenter: function (grid, record, item, index, e, eOpts) {
        var node = grid.getNode(record);
        var cells = Ext.dom.Query.select('.editable-cell', node);

        for (var i = 0; i < cells.length; i++) {
            Ext.fly(cells[i]).highlight();
        }
    }

You can see a working sample here.
Hope it helps to solve your problem

A: another option here with CSS animation: https://fiddle.sencha.com/#fiddle/16a


text:
Q: Magento 2 - Type error: require is not a function for admin grid in custom page with custom tab I am trying to load a grid to a tab on a custom page in Mangento 2 admin. The grid is rendered beautifully but js seems to be uninitialized after the ajax reload fetches it from controller. The grid is not responsive at all. Browser console displays "Type Error: require is not a function", but I don't understand how to initialize js for the grid after ajax.
My code (skipping boilerplate e.g. registration.php, composer.json, etc/module.xml, etc/adminhtml/routes.xml):
/Vendor/Module/Controller/Adminhtml/Offers/Edit.php
<?php
  namespace Vendor\Module\Controller\Adminhtml\Offers;

  class Edit extends \Magento\Backend\App\Action{

    protected $resultPageFactory;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
         parent::__construct($context);
         $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
         return  $resultPage = $this->resultPageFactory->create();
    }
  }
?>

/Vendor/Module/view/adminhtml/layouts/module_offers_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <title>
            Angebot
        </title>
    </head>
    <body>
        <referenceContainer name="left">
            <block class="Vendor\Module\Block\Adminhtml\Offer\Edit\Tabs"
                name="vendor_module_offer.edit.tabs"/>
        </referenceContainer>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\Adminhtml\Offer\Edit"
                name="vendor_module_offer.edit"/>
        </referenceContainer>
    </body>
</page>

/Vendor/Module/Block/Adminhtml/Offer/Edit.php
<?php
namespace Vendor\Module\Block\Adminhtml\Offer;

use Magento\Backend\Block\Widget\Form\Container;

class Edit extends Container{

    protected $_coreRegistry = null;

    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }
    protected function _construct()
    {
        $this->_objectId = 'module_offer_id';
        $this->_blockGroup = 'Vendor_Module';
        $this->_controller = 'adminhtml_offer';
        parent::_construct();
        $this->buttonList->remove('save');
    }

    public function getHeaderText()
    {
        return __('Offer');
    }

    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }

}

/Vendor/Module/Block/Adminhtml/Offer/Edit/Tabs.php
<?php
   namespace Vendor\Module\Block\Adminhtml\Offer\Edit;

   use Magento\Backend\Block\Widget\Tabs as WidgetTabs;

   class Tabs extends WidgetTabs{

    protected function _construct()
    {
        parent::_construct();
        $this->setId('offer_edit_tabs');
        $this->setDestElementId('edit_form');
        $this->setTitle(__('Angebot'));
    }

    protected function _beforeToHtml()
    {
        $this->addTab(
            'Produkte',
            [
                'label' => __('Products'),
                'url' => $this->getUrl('module/*/products', ['_current' => true]),
                'class' => 'ajax'
            ]
        );
        return parent::_beforeToHtml();
    }
}

This is all just setup for the tabs to display on the page with path .../admin/module/offers/edit/ID. Now, to fill the tab with products I load the grid with this:
/Vendor/Module/Controller/Adminhtml/Offers/Products.php
<?php
  namespace Vendor\Module\Controller\Adminhtml\Offers;

  class Products extends \Magento\Backend\App\Action{
    protected $resultPageFactory;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
         parent::__construct($context);
         $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
         return  $resultPage = $this->resultPageFactory->create();
    }
  }
?>

/Vendor/Module/view/adminhtml/layout/module_offers_products.xml
<?xml version="1.0"?>
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/layout_generic.xsd">
    <container name="root" label="Root">
        <block class="Vendor\Module\Block\Adminhtml\Offer\Edit\Tab\View\Products" name="offer.edit.tab.product"/>
    </container>
</layout>

/Vendor/Module/Block/Adminhtml/Offer/Edit/Tab/View/Products.php
<?php
namespace Vendor\Module\Block\Adminhtml\Offer\Edit\Tab\View;

use Magento\Customer\Controller\RegistryConstants;

class Products extends \Magento\Backend\Block\Widget\Grid\Extended
{

    protected $_coreRegistry = null;

    protected $_collectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Vendor\Module\Model\OfferItemFactory $collectionFactory,
        \Magento\Framework\Registry $coreRegistry,
        \Psr\Log\LoggerInterface $logger,
        array $data = []
    ) {
         $this->_logger = $logger;
        $this->_coreRegistry = $coreRegistry;
        $this->_collectionFactory = $collectionFactory;
        parent::__construct($context, $backendHelper, $data);
    }

    protected function _construct()
    {
        parent::_construct();
        $this->setId('offer_view_products_grid');
        $this->setDefaultSort('offer_item_stock_id', 'desc');
        $this->setSortable(true);
        $this->setPagerVisibility(true);
        $this->setFilterVisibility(true);
    }

    protected function _preparePage()
    {
        $this->getCollection()->setPageSize(5)->setCurPage(1);
    }

    protected function _prepareCollection()
    {
        $collection = $this->_collectionFactory->create()->getCollection();
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('offer_item_stock_id');
        $this->getMassactionBlock()->setFormFieldName('stock_ids');
        $this->getMassactionBlock()->addItem(
            'customize',
            [
                'label' => __('Anpassen (ToDo)'),
                'url' => $this->getUrl('test/test/test')
            ]
        );
        return $this;
    }
     protected function _prepareColumns()
    {
        $this->addColumn(
            'offer_item_stock_id',
            ['header' => __('Stock ID'), 'index' => 'offer_item_stock_id', 'type' => 'number', 'width' => '50px']
        );
        return parent::_prepareColumns();
    }

    public function getHeadersVisibility()
    {
        return $this->getCollection()->getSize() >= 0;
    }

    public function getRowUrl($row)
    {
        return $this->getUrl('test/test/test');
    }
}

So my question is how to initialize js for the grid after ajax load.


text:
Q: Is the gravitational acceleration at the event horizon constant? If the escape velocity at the event horizon of a black hole is equal to the speed of light, does this imply that the gravitational acceleration at the event horizon is also constant?
For example, using Earth $\left(m=5.967 \cdot {10}^{24}\, \mathrm{kg}\right)$  and the equation $ c^2 = \frac {GM}{r_{\text{S}}} $, we find a Schwarzchild radius of $r_{\text{S}} =8.86 \cdot {10}^{-3} \, m$.
Substituting this value into $a = \frac {GM}{r^2}  $ we derived an answer of $ a=5.071525376 \cdot {10}^{18} \, m$ at the Schwarzchild radius.
Furthermore, an object's mass will be directly proportional to its Schwarzchild radius, thus the gravitational acceleration would remain constant for all black holes at its event horizon.  Is this assumption corrects and does this withhold with all black holes?


text:
Q: Force a div over an auto complete Is it possible to force an element to render above an automatic autocomplete in chrome?
A simple absolute with a z-index renders fine above the form, but autocompletes don't share the z-ordering of the form element....
I would like to retain the use of the default auto-complete (rather than 3rd party ones).   Googling suggests styling with 'webkit-autofill' might be a relevant, but doesn't seem to help.
(I realise this is terrible UI design - you don't have to tell me about that!)
Thanks!

    <form>

            Jennifer

            Alison

            Phillipa

            Sue

        <input id="id1" name="test" style="width:100%">
    </form>


text:
Q: Using Ajax to dynamically insert images for the owl carousel I am trying to insert images from a json file using Ajax. These images will then be used by the owl carousel, however currently it is only displaying the last image in json file.
Here is my code:
html

New Releases

js
$(document).ready(function() {

    $.getJSON("data/owl.json",function(img){
       $.each(img, function(index,img){
            var $newImg = $(img.item);

        $(".owl-carousel").append($newImg);

       });
  $(".owl-carousel").owlCarousel({
      dots:true
  });

});
});

json
[
{
    "item":"",
    "item":"",
    "item":""
}
]

A: You can't have multiple identical keys in the same object.
I suggest a different data structure. A top-level object that has an images property, which is an array of objects, each carrying information about a single image.
{
    "images": [
        {"url": "images/slide1.jpg"},
        {"url": "images/slide2.jpg"},
        {"url": "images/slide3.jpg"}
    ]
}

Then the code follows naturally:
$(document).ready(function() {
    $.getJSON("data/owl.json").done(function (data) {
        $.each(data.images, function(index, img) {
            $('', { src: img.url }).appendTo(".owl-carousel");
        });

        $(".owl-carousel").owlCarousel({
            dots:true
        });
    });
});

Note that it's not a good idea to have the finished HTML inside your JSON, as this limits what you can do with it on the client side and leads to useless duplication in the JSON data.
jQuery makes it quite easy to build HTML elements from data, make use of that feature and only include the actual data in the JSON. The client-side code can take care of the details how to render it.


text:
Q: How to obtain principal component % variance explained in R? prcomp() and preProcess() comparison I know that PCA can be conducted with the prcomp() function in base R, or with the preProcess() function in the caret package, amongst others.
Firstly, am I right in saying that if we just use the default settings for operations of type prcomp(<SOME_MATRIX>) or preProcess(<SOME_MATRIX>, method = "pca"), then the only difference in our results is that prcomp() does not centre and scale the data before conducting PCA, and preProcess() does? Therefore, do prcomp(scale(<SOME_MATRIX>)) and preProcess(<SOME_MATRIX>, method = "pca") output the same thing?
Secondly, and more importantly, how can we obtain the % variance explained by each PC from the output of either prcomp() or preProcess()? From both of these outputs I can see things like the means, standard deviations or rotations, but I think these refer just to the 'old' variables. Where is the information about the 'new' PCs and how much variance they account for?
This might come in useful if, for example, I am using preProcess(<SOME_MATRIX>, method = "pca", thresh = 0.8) and this returns 6 PCs, but I find that the first 5 PCs explain a total of 79.5% of the variance. Then I might be inclined not to include all 6 PCs.

A: Since your first question has already been answered, here the answer to your second question for prcomp. We can get the % variance explained by each PC by calling summary:
df <- iris[1:4]
pca_res <- prcomp(df, scale. = TRUE)
summ <- summary(pca_res)
summ

#Importance of components:
#                          PC1    PC2     PC3     PC4
#Standard deviation     1.7084 0.9560 0.38309 0.14393
#Proportion of Variance 0.7296 0.2285 0.03669 0.00518
#Cumulative Proportion  0.7296 0.9581 0.99482 1.00000

summ$importance[2,]
# PC1     PC2     PC3     PC4
#0.72962 0.22851 0.03669 0.00518

From what I know this information is not available when using the caret package (see issue discussed here):
mod <- train(Species ~ ., data = iris, method = "knn",
                            preProc = c("center", "scale", "pca"))
str(mod$preProcess)

List of 22
 $ dim              : int [1:2] 150 4
 $ bc               : NULL
 $ yj               : NULL
 $ et               : NULL
 $ invHyperbolicSine: NULL
 $ mean             : Named num [1:4] 5.84 3.06 3.76 1.2
  ..- attr(*, "names")= chr [1:4] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
 $ std              : Named num [1:4] 0.828 0.436 1.765 0.762
  ..- attr(*, "names")= chr [1:4] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
 $ ranges           : NULL
 $ rotation         : num [1:4, 1:2] 0.521 -0.269 0.58 0.565 -0.377 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:4] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
  .. ..$ : chr [1:2] "PC1" "PC2"
 $ method           :List of 4
  ..$ center: chr [1:4] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
  ..$ scale : chr [1:4] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
  ..$ pca   : chr [1:4] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
  ..$ ignore: chr(0)
 $ thresh           : num 0.95
 $ pcaComp          : NULL
 $ numComp          : num 2
 $ ica              : NULL
 $ wildcards        :List of 2
  ..$ PCA: chr(0)
  ..$ ICA: chr(0)
 $ k                : num 5
 $ knnSummary       :function (x, ...)
 $ bagImp           : NULL
 $ median           : NULL
 $ data             : NULL
 $ rangeBounds      : num [1:2] 0 1
 $ call             : chr "scrubed"
 - attr(*, "class")= chr "preProcess"


text:
Q: How to put a PHP variable inside a html file that is being created using fwrite()? I need to create many html files all using the same template. In this case:

 This is //here goes the variable// 's profile

I need to use different variables defined at the login (in this case "uname"). To do this I was using fwrite(). (usertest is the folder where all the files will be stored):
<?php
if(isset($_POST['action'])) {
    $uname = $_POST["uname"];
    $filecount = count(glob("usertest/*.html"));
    $filename = "user" .($filecount+1).".html";
    $myfile = fopen("usertest/$filename", "w") or die("unable to create file");
    $html = "
 This is" .$uname."'s profile
";
    fwrite($myfile, $html);
    fclose($myfile);
?>

From this html file:
<!DOCTYPE html>

</head

    <form>
        <input id="userinput" type="text" name="uname" />
       <input type="submit" class="button" value="submit" />

    </form>

And this Jquery (mango.js):
$(document).ready(function(){
$('.button').click(function(){
     var clickBtnValue = $(this).val();
     var ajaxurl = 'ajax.php',
     data = {'action': clickBtnValue};
     $.post(ajaxurl, data, function(response) {
         alert("success!");
     });
});
});

The file names are created perfectly and everything. However when I open the created html files they just read:
This is 's profile

They completely ignore the variable!
The question is, how do I include this PHP variable in the html? Or is it not possible?
Help would be greatly appreciated!
Thanks!

A: Have you tried replacing <form> by <form method="POST"> ?
By default <form> method is GET, so you will get nothing in $_POST['uname']
Otherwise, declare $uname = $_GET['uname'];

A: Check if $_POST["uname"] is not empty in your php file, otherwise, the rest of the php seems ok.

A: That is because you are not sending the uname to server in order to save it.
The js code should actually be:
$(document).ready(function(){
$('.button').click(function(){
     var unameValue = $('#userinput').val();
     var actionValue = $(this).val();
     var ajaxurl = 'ajax.php',
     data = {
        uname: unameValue,
        action: actionValue
     };
     $.post(ajaxurl, data, function(response) {
         alert("success!");
     });
});
});

notice that we are now send the uname as uname: unameValue value which you can capture in php as $_POST['uname'];


text:
Q: Is there a word for wanting bad things to happen to others? The German word schadenfreude is often used in English to express the pleasure derived from seeing misery in others.
From dictionary.reference.com

schadenfreude noun. satisfaction or pleasure felt at someone else's misfortune.

For example quite harmlessly, finding it funny when someone trips over, or more dramatically the pleasure derived when seeing your ex-partner go through a messy break up.
Is there a word for wanting bad things to happen to others? The context would typically a bit a jilted lover or a jealous person.
For example hoping someone's holiday goes badly, or hoping the company project goes badly after you leave.

A: From the Wikipedia section on this word:

An English expression with a similar meaning is Roman holiday, a
  metaphor from the poem Childe Harold's Pilgrimage by George Gordon,
  Lord Byron, where a gladiator in Ancient Rome expects to be "butchered
  to make a Roman holiday" while the audience would take pleasure from
  watching his suffering. The term suggests debauchery and disorder in
  addition to sadistic enjoyment.[9]
Another phrase with a meaning similar to Schadenfreude is "morose
  delectation" (delectatio morosa in Latin), meaning, "The habit of
  dwelling with enjoyment on evil thoughts".[10] The medieval church
  taught that morose delectation was a sin.[11][12] French writer Pierre
  Klossowski maintained that the appeal of sadism is morose
  delectation.[13][14]
An English word of similar meaning is "gloating", where "gloat" means
  "to observe or think about something with triumphant and often
  malicious satisfaction, gratification, or delight" (e.g. to gloat over
  an enemy's misfortune).[15] Gloating is differentiated from
  Schadenfreude in that it does not necessarily require malice (one may
  gloat to a friend about having defeated him in a game without ill
  intent), and that it describes an action rather than a state of mind
  (one typically gloats to the subject of the misfortune or to a third
  party).


text:
Q: Combine multiple .git repositories while retaining file based commit info Coming from CVS we have a packages directory, which contains single .git repositories for each package.
Sadly, these are not as independent as the original CVS owners thought, so usually they are all checked out together and combined as a whole package into whatever versioning system you happen to use as a developer.
Combining multiple git repositories and http://progit.org/book/ch6-7.html already told me how to combine them all into one .git repository, so instead of:
packages/intranet-asus-client/.git
packages/intranet-timesheet/.git
packages/intranet-core/.git

it looks like
packages/.git
packages/intranet-core (without .git, and so on).

git log in packages shows me the whole commit history (great), yet what is missing is:

*

*File based git history like git log --pretty=oneline -- intranet-core/intranet-core.info. It only shows me the commits which I made in the combined repository (meaning in /packages/.git)

*No branches or tags. I have a hunch that I would have to create a branch in /packages/.git for each branch present in /packages/acs-kernel/.git and so on. But how about tags?

Or is this one of those great examples where submodules would really be helpful? Sadly, this means for us (as we do regular client patches to packages) that we would have to fork (we use github....) every packages .git remote repository into a private one and use our own client branches there. Though this would be awesome for github (more money), it is less convenient for us.
Is there a solution for our problem, maybe with scripts running series of git commands to correctly pull the branches together and more importantly redo all the commits in the new packages directory with timestamp and author, so it appears as if the commits where done there all along instead of the subtrees? Or do I just use git log in a wrong way ?

A: You might want to investigate gitslave (http://gitslave.sf.net) which provides CVSish recursive superproject management in the git framework.  It is much simpler and easier to use that git-submodules, but has some drawbacks (which you would not notice coming from CVS).  Unlike git-submodules, gitslave does not take over your repository so you can use a mixture of legacy and gitslave commands.  One use can always use gitslave another can always use pure git, and a third can use a mixture back and forth.
Once you set up gitslave, you can create a branch or a tag on all of the repos in one simple command, and switch branches, checkin, push, or do whatever you want.
It currently will probably not give you the file history that you want without work on your side, but that is something that could be added (patches welcome :-).


text:
Q: How to pass a function as a parameter to void function pointer in C I am new to function pointers .
I have written a function which can take pointer to a function.
 register_agent( void (*agent)())

I want to pass a pointer of the function
 registry_agent

as a parameter to
 register_agent

Can anyone pls suggest how do I do this in C. Also explain the concept behind

A: It cant be done in C as you will have an infinite-length function declaration:
void ra(void (*r)(void (*r)(void (*r)(void .......))))

(assuming that you want to declare it giving the parameter list)


text:
Q: UWP - OneDrive file download error: "Access to the path '…' is denied" when using sample code from MS Graph team I'm working on this exercise from Microsoft Graph team: Access and download files from OneDrive. And I'm getting the following Access denied error on the following code at the end under the section: Download a file from the user's OneDrive:

Access to the path 'C:\DotNETCore2019\UWP\AccessFilesTrainingCourse\bin\x86\Debug\AppX\driveItem_17B6A4972C38846A!2923.file' is denied.

Remarks with Question: Error occurs at line var driveItemFile = System.IO.File.Create(driveItemPath); of the code below. I know that UWP apps can access certain file system locations by default. Apps can also access additional locations through the file picker, or by declaring capabilities as explained here. According to this official link, one of those default locations is Application install directory which during debug mode is supposed to be ...\bin\debug folder. And the above linked tutorial from MS Graph team does not mention declaring a capability in the app's Package.appxmanifest file. So, why the error and how can we resolve it without declaring broadFileSystemAccess capability - as you don't want go free for all scenario?
Code:
// request 3 - download specific file
var fileId = "REPLACE_THIS"; //I have correctly placed corresponding fileid here
var request = client.Me.Drive.Items[fileId].Content.Request();

var stream = request.GetAsync().Result;
var driveItemPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "driveItem_" + fileId + ".file");
var driveItemFile = System.IO.File.Create(driveItemPath);
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(driveItemFile);
Console.WriteLine("Saved file to: " + driveItemPath);

A: Use ApplicationData.Current.LocalFolder.Path instead of System.IO.Directory.GetCurrentDirectory(). The default location is C:\Users\username\AppData\Local\Packages\your package name\LocalState


text:
Q: How to check if our system has been exploited by log4j vulnerability? Recently there was a log4j vulnerability reported:

*

*https://nvd.nist.gov/vuln/detail/CVE-2021-44228

*https://www.randori.com/blog/cve-2021-44228/

*https://www.lunasec.io/docs/blog/log4j-zero-day/
How do I know exactly my system has been attacked or exploited by injected arbitrary code?
Thank you so much

A: UPDATE: 2021-12-18...
Remember to always check for the latest information from the resources listed below
CVE-2021-45105... 2.16.0 and 2.12.2 are no longer valid remediations! The current fixing versions are 2.17.0 (Java 8) and 2.12.3 (Java 7). All other Java versions have to take the stop gap approach (removing/deleting JndiLookup.class file from the log4j-core JAR.
I have updated my message below accordingly.

Answering the question directly:
Reddit thread: log4j_0day_being_exploited has SEVERAL resources that can help you.
To detect vulnerability

*

*cntl + f for Vendor Advisories. Check those lists to see if you are running any of that software. If you are and an update is available for it, update.

*THEN cntl + f for .class and .jar recursive hunter. Run the program there, if it finds anything remediate.

*You can also cntl + f for Vulnerability Detection if you want to perform a manual active test of your systems for the vulnerability

To detect exploit... this is more complex and all I do is is till you

*

*cntl + f for Vendor Advisories... search through the stuff there... not sure which option will be best for you

*

*More resources

*

*https://www.reddit.com/r/blueteamsec/comments/rd38z9/log4j_0day_being_exploited/

*

*This one has TONS of useful info including detectors, even more resource links, very easy to understand remediation steps, and more

*https://www.cisa.gov/uscert/apache-log4j-vulnerability-guidance

*https://github.com/cisagov/log4j-affected-db

*https://logging.apache.org/log4j/2.x/security.html

Remediation:
CVE-2021-45046 ... CVE-2021-44228 ... CVE-2021-45105
While most people that need to know probably already know enough to do what they need to do, I thought I would still put this just in case...

*

*Follow the guidance in those resources... it may change, but

As of 2021-12-18
It's basically

*

*Remove log4j-core JAR files if possible

*

*From both running machines for immediate fix AND

*in your source code / source code management files to prevent future builds / releases / deployments from overwriting the change

*If that is not possible (due to a dependency), upgrade them

*

*If you are running Java8, then you can upgrade to log4j 2.17.0+

*If you are running an earlier version of Java, then you can upgrade to log4j 2.12.3

*If you are running an older version of Java, then you need to upgrade to the newest version of Java, and then use the newest version of Log4J

*Again, these changes have to happen both on running machine and in code

*If neither of those are possible for some reason... then there is the NON-remediation stop gap of removing the JndiLookup.class file from the log4j-core JARs.

*

*There is a one-liner for the stop gap option on Linux using the zip command that comes packaged with most Linux distros by default.

*

*zip -q -d "$LOG4J_JAR_PATH" org/apache/logging/log4j/core/lookup/JndiLookup.class

*At time of writing, most of the guides online for the stop gap option on Windows say to do the following (again... assuming you can't do one of the remove JAR or upgrade options above):

*

*Install something like 7-zip

*Locate all of your log4j-core JAR files and for each one do the following...

*Rename the JAR to change the extension to .zip

*Use 7-zip to unzip the JAR (which now has a .zip extension)

*Locate and remove the JndiLookup.class file from the unzipped folder

*

*The path is \\path\\to\\unzippedFolder\\org\\apache\\logging\\log4j\\core\\lookup\\JndiLookup.class

*Delete the old JAR file (which now has an extension of .zip)

*Use 7-zip to RE-zip the folder

*Rename the new .zip folder to change the extension to .jar

*There are also some options to use Power Shell

*

*Reddit thread: log4j_0day_being_exploited

*ctrl+f for "PowerShell"

This is fine if you only have 1 or 2 JAR files to deal with and you don't mind installing 7-zip or you have PowerShell available to do it. However, if you have lots of JAR files, or if you don't want to install 7-zip and don't have access to Power Shell, I created an open-source VBS script that will do it for you without needing to install any additional software. https://github.com/CrazyKidJack/Windowslog4jClassRemover
Read the README and the Release Notes https://github.com/CrazyKidJack/Windowslog4jClassRemover/releases/latest

A: You can check on your request log if you see something looking like this :
{jndi:ldap://example.com:1234/callback}

If you want to check if you can be attacked, you can run a POC from Github. This link seems to be the first POC released. You can now find others.
You can also find a black-box testing here.


text:
Q: what kind of parameters can I pass to XMLHttpRequest.send()? I have a request that looks like this
var xhr = new XMLHttpRequest();
[...]
xhr.send("param1=" + obj.param1 + "&param2=" + val);

I'd really prefer to write something like
xhr.send( {"param1": obj.param1, "param2": val} );

(A) Is it possible to do that?
(B) Where can I find a spec that would answer that question?

A:
Is it possible to do that?

Not currently, but such things are included in the draft: http://www.w3.org/TR/XMLHttpRequest/#the-send-method. XmlHttpRequest should be able to send ArrayBuffers, Blobs, Documents, strings and FormData objects (examples at html5rocks).
However, sending objects is not supported - they'd need to be serializable. You could send them as a JSON string, or use one of the many library function to generate URL argument strings (like jQuery.param()).

Where can I find a spec that would answer that question?

I've linked the spec above, though for browser support you'd need to look at compatibility tables or the browsers' documentations (eg. for FF at MDN).

A: you can do this kind of thing easily with jQuery:  jQuery.ajax({ url: http://yoururl.com, data: {"param1": obj.param1, "param2": val}});


text:
Q: convert Spark dataframe to scala dictionary like format I have a spark dataframe which i need to convert to (key, value) pairs. below is the format:
+--------------------+--------------------+-------------------+------+------+
|                 cid|                 uid|               date|rating|  type|
+--------------------+--------------------+-------------------+------+------+
|          1111111111|           user1-316|2019-10-11 14:01:49|     1|others|
|          1111111111|               user1|2019-10-11 14:25:35|     2|mobile|
|          1111111111|               user2|2019-10-11 14:30:05|     3|others|
|          1111111112|               user2|2019-10-11 14:16:58|     4|others|
|          1111111113|               user2|2019-10-11 14:32:00|     1|mobile|
+--------------------+--------------------+-------------------+------+------+

i need ta aggregate it based on uid and create a list of cid,rating,date for each type
 uid       | history
-----------+--------------------------------------------------------
 user1-316 | {"others": [["1111111111", 1, "2019-10-11 14:01:49"]]}
 user1     | {"mobile": [["1111111111", 2, "2019-10-11 14:25:35"]]}
 user2     | {"others": [["1111111111", 3, "2019-10-11 14:30:05"],["1111111112", 4, "2019-10-11 14:16:58"]],"mobile":[["1111111113", 1, "2019-10-11 14:32:00"]]}

In python i can achive this as we have dict format. How do we get this done in scala.

A: Updated answer:
You can try something like this. I am not sure dict in Python but for (key,value), Scala has map type.

scala> df.show
+----------+---------+-------------------+------+------+
|       cid|      uid|               date|rating|  type|
+----------+---------+-------------------+------+------+
|1111111111|user1-316|2019-10-11 14:01:49|     1|others|
|1111111111|    user1|2019-10-11 14:25:35|     2|mobile|
|1111111111|    user2|2019-10-11 14:30:05|     3|others|
|1111111112|    user2|2019-10-11 14:16:58|     4|others|
|1111111113|    user2|2019-10-11 14:32:00|     1|mobile|
+----------+---------+-------------------+------+------+

scala> df.withColumn("col1",array("cid","rating","date"))
         .groupBy("type","uid")
         .agg(map(col("type"),collect_list("col1")).as("col2"))
         .groupBy("uid")
         .agg(collect_list(col("col2")).as("history"))
         .show(false)

+---------+----------------------------------------------------------------------------------------------------------------------------------------------+
|uid      |history                                                                                |
+---------+----------------------------------------------------------------------------------------------------------------------------------------------+
|user1-316|[[others -> [[1111111111, 1, 2019-10-11 14:01:49]]]]                                                                                |
|user1    |[[mobile -> [[1111111111, 2, 2019-10-11 14:25:35]]]]                                                                                |
|user2    |[[others -> [[1111111111, 3, 2019-10-11 14:30:05], [1111111112, 4, 2019-10-11 14:16:58]]], [mobile -> [[1111111113, 1, 2019-10-11 14:32:00]]]]|
+---------+----------------------------------------------------------------------------------------------------------------------------------------------+

A: AS said, we can have Key -> Value pair in scala, but not with the similar representation of Python
First, read the data
scala> val df = Seq((1111111111,"user1-316","2019-10-1114:01:49",1,"others"), (1111111111,"user1","2019-10-1114:25:35",2,"mobile"), (1111111111,"user2","2019-10-1114:30:05",3,"others"), (1111111112,"user2","2019-10-1114:16:58",4,"others"), (1111111113,"user2","2019-10-1114:32:00",1,"mobile")).toDF("cid","uid","date","rating","type")
df: org.apache.spark.sql.DataFrame = [cid: int, uid: string ... 3 more fields]
scala> df.show
+----------+---------+------------------+------+------+
|       cid|      uid|              date|rating|  type|
+----------+---------+------------------+------+------+
|1111111111|user1-316|2019-10-1114:01:49|     1|others|
|1111111111|    user1|2019-10-1114:25:35|     2|mobile|
|1111111111|    user2|2019-10-1114:30:05|     3|others|
|1111111112|    user2|2019-10-1114:16:58|     4|others|
|1111111113|    user2|2019-10-1114:32:00|     1|mobile|
+----------+---------+------------------+------+------+

Now, we convert cid,rating,date to list
scala> val df1 = df.groupBy($"uid", $"type").agg(collect_list(array($"cid", $"rating", $"date")).as("aggNew"))
df1: org.apache.spark.sql.DataFrame = [uid: string, type: string ... 1 more field]

scala> df1.show(false)
+---------+------+--------------------------------------------------------------------------------------------------+
|uid      |type  |aggNew                                                                                |
+---------+------+--------------------------------------------------------------------------------------------------+
|user1    |mobile|[WrappedArray(1111111111, 2, 2019-10-1114:25:35)]                                                 |
|user2    |mobile|[WrappedArray(1111111113, 1, 2019-10-1114:32:00)]                                                 |
|user1-316|others|[WrappedArray(1111111111, 1, 2019-10-1114:01:49)]                                                 |
|user2    |others|[WrappedArray(1111111111, 3, 2019-10-1114:30:05), WrappedArray(1111111112, 4, 2019-10-1114:16:58)]|
+---------+------+--------------------------------------------------------------------------------------------------+

On top of it, applying groupBy on uid for obtaining required (key, values)
scala> df1.groupBy($"uid").agg(collect_list(map($"type", $"aggNew"))).show(false)
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|uid      |collect_list(map(type, aggNew))                                                                                |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|user1-316|[Map(others -> WrappedArray(WrappedArray(1111111111, 1, 2019-10-1114:01:49)))]                                                                                |
|user1    |[Map(mobile -> WrappedArray(WrappedArray(1111111111, 2, 2019-10-1114:25:35)))]                                                                                |
|user2    |[Map(mobile -> WrappedArray(WrappedArray(1111111113, 1, 2019-10-1114:32:00))), Map(others -> WrappedArray(WrappedArray(1111111111, 3, 2019-10-1114:30:05), WrappedArray(1111111112, 4, 2019-10-1114:16:58)))]|
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Added schema
root
 |-- uid: string (nullable = true)
 |-- collect_list(map(type, aggNew)): array (nullable = true)
 |    |-- element: map (containsNull = true)
 |    |    |-- key: string
 |    |    |-- value: array (valueContainsNull = true)
 |    |    |    |-- element: array (containsNull = true)
 |    |    |    |    |-- element: string (containsNull = true)


text:
Q: Is TypeScript capable of shaping an argument based on another one? My package support multiple loaders, implementing LoaderInterface:
// tslint:disable-next-line:no-empty-interface
export interface LoaderOptions { }

export interface LoaderInterface {
  load(options: LoaderOptions): Object;
}

export interface SimpleLoaderOptions extends LoaderOptions {
  option1: string;
}
export interface AdvancedLoaderOptions extends LoaderOptions {
  option2: string;
}

MyModule entry point should accept two options:

*

*loader that is an instance of LoaderInterface (concrete class)

*options object witch should "match" the corresponding loader options

My problem is I dont' know how to create a "connection" between the two options.
I need something like: if loader is this, than options should look like this. Possible?

Solution 1: silly, becase one can pass anything to options argument:
class MyModule {
  static create(loader: LoaderInterface, options: any) { }
}

Solution 2: also silly, because allow any object with the shape of LoaderOptions (basically, anything):
class MyModule {
  static create(loader: LoaderInterface, options: LoaderOptions) { }
}

MyModule.create(new SimpleLoader, { foo: 'bar' })

Solution 3: better, but one can still "mix" options. But what about a custom loader with custom options?:
class MyModule {
  static create(loader: LoaderInterface, options: SimpleLoaderOptions
    | AdvancedLoaderOptions) { }
}

MyModule.create(new SimpleLoader, { option1: 'foo', option2: 'bar' })

A: You can make the loader interface generic. When the loader is implemented it specifies the option it supports as the generic parameter. The create method will be generic and will use the same type parameter for the type parameter of the loader and the options object creating thus a link between them
export interface LoaderOptions { }

export interface LoaderInterface<T extends LoaderOptions> {
    load(options: T): Object;
}

export interface SimpleLoaderOptions extends LoaderOptions {
    option1: string;
}
export interface AdvancedLoaderOptions extends LoaderOptions {
    option2: string;
}

class MyModule {
    static create<T extends LoaderOptions>(loader: LoaderInterface<T>, options: T & {}) {
    }
}

class LoaderAdvanced implements LoaderInterface<AdvancedLoaderOptions> {
    load(options: AdvancedLoaderOptions): Object {
        return null as any;
    }
}

let m = MyModule.create(new LoaderAdvanced(), {
    option2: '' // required since we need AdvancedLoaderOptions
});

Playground link
Note:we use T&{} for the options parameter in order to decrease the priority of this inference site, ensuring T is dictated by the loader parameter not by options


text:
Q: How to record a stream in flutter I have a video stream that I get through a websocket in my app and I want to know if i can record it like it is a video without showing it on the screen ?
I'd love to know how to do it if anyone know, thanks!

A: I found a good way to record my stream with FFMPEG and a tutorial in this video :
https://youtu.be/Z5vBs8Mk5rA?t=581
It work fine for now


text:
Q: Undocumented error during OpenGL context creation I'm using wglCreateContextAttribsARB() function to create an OGL context with the following parameters:
const int contextAttrib[] = {
    WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
    WGL_CONTEXT_MINOR_VERSION_ARB, 2,
    WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
#ifdef _DEBUG
    WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB,
#else
    WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
#endif
    0
};

mContext = wglCreateContextAttribsARB_local(mhDC, shareLists, contextAttrib);

Unfortunately, I get an error - 0xc00710dd or 3221688541 (returned by GetLastError()), when I try to create a second context which shares data with some context created successfully earlier (the shareLists argument). Googling it gave only a single result: http://software.intel.com/en-us/forums/topic/303629 I'm using GeForce 680 GTX on Windows 8.1 with the latest drivers, so the thread isn't much us anyway.
One strange thing is the way this error could be reproduced. When I create context A and context B which shares data with A, then C sharing data with A, the error only occurs when B renders something before creating C (which fails).
Does anyone have an idea what might be going on?

A: This error is probably an HRESULT / SCODE which is a compound value. Each of the pieces (severity, facility, code) can be accessed with a macro:
HRESULT_SEVERITY(0xC00710DD) = 0xC0000000 //ERROR_SEVERITY_ERROR
HRESULT_FACILITY(0xC00710DD) = 7          //FACILITY_WIN32
HRESULT_CODE(0xC00710DD)     = 4317       //ERROR_INVALID_OPERATION