text:
Q: Calculating a Cost Using a Stored Procedure in MYSQL I have two tables in my database: Package and Shipment. There can be multiple packages in a shipment. (Hence each package has a unique shipment_track_no)
Package(package_number, type, content, weight, shipment_track_no)

Shipment(tracking_number, sender_id, receiver_name, receiver_phone_number, method, is_delivered, shipment_date)

I would like to create a stored procedure in MYSQL that would calculate the cost of a shipment, iterating through the packages in a shipment.
Calculation has several steps to it:

*

*First, the package is valued according to its type (1-5 enum).

*Then extras are added if the package has special content (1-3 enum).

*After calculating the cost of each package of shipment I add it to a
common sum. According to the delivery method of the shipment an extra
sum might be added as well.

The code that I came up with using all available resources that I could find is below. I think I am messing up the syntax but the main flow should be all-right. I would really appreciate if anyone helps me with the correct syntax.
DROP PROCEDURE IF EXISTS cost_of_shipment;

DELIMITER $$
CREATE PROCEDURE cost_of_shipment(IN shipment_id_fed int(11),
                                    OUT total decimal(12,2))
BEGIN
DROP TEMPORARY TABLE IF EXISTS temporaryTable;
CREATE TEMPORARY TABLE temporaryTable engine=memory SELECT package_number, Package.`type`, content, weight FROM Package WHERE shipment_track_no = shipment_id_fed;

DECLARE i INT(11) DEFAULT 1;

DECLARE rowCount INT(11) DEFAULT 0;
SET rowCount = (SELECT COUNT(package_number) FROM temporaryTable);

DECLARE shipment_cost DECIMAL (12,2) DEFAULT = 0.00;

WHILE (i <= rowCount)
BEGIN

        DECLARE ipackage_number INT(11), ipackage_type INT(11), icontent INT(11), iweight DECIMAL(12,2), package_cost DECIMAL(12,2);

        SELECT ipackage_number = package_number, ipackage_type = package_type, icontent = content , iweight = weight FROM temporaryTable LIMIT 1;
        IF ipackage_type = 1 OR ipackage_type = 2 OR  ipackage_type = 3
        THEN
        SET package_cost = 10;
        END IF;

        IF ipackage_type = 4
        THEN
        SET package_cost = 15;
        END IF;

        IF ipackage_type = 5 AND iweight<20
        THEN
        SET package_cost = 20;
        END IF;

        IF ipackage_type = 5 AND iweight>20
        THEN
        SET package_cost = 20 + (iweight-20)*1;
        END IF;

        IF icontent = 2
        THEN
        SET package_cost = package_cost + 10;
        END IF;

        IF icontent = 3
        THEN
        SET package_cost = package_cost * 1.1;
        END IF;

        shipment_cost = shipment_cost + package_cost;

        DELETE FROM temporaryTable WHERE package_number = ipackage_number;
        SET i = i  + 1
END

        IF (SELECT method FROM Shipment WHERE tracking_number = shipment_id_fed) = 2
        THEN
        SET shipment_cost = shipment_cost +10;
        END IF;

        IF (SELECT method FROM Shipment WHERE tracking_number = shipment_id_fed) = 3
        THEN
        SET shipment_cost = shipment_cost +25;
        END IF;

    SELECT shipment_cost INTO total FROM Shipment;
END $$
DELIMITER ;

A: I redesigned the tables for Package and Shipment; added cost attributes to them. I dealt with the issue with creating triggers for inserting and updating a Package.
On Insert Trigger for calculating the cost of a Package
    DELIMITER $$
    CREATE TRIGGER package_cost_insert BEFORE INSERT ON Package
    FOR EACH ROW
    BEGIN
        IF new.type = 1 OR new.type = 2 OR new.type = 3  THEN
             SET new.cost = new.cost + 10.00;
        END IF;

        IF new.type = 4  THEN
             SET new.cost = new.cost + 15.00;
        END IF;

        IF new.type = 5 AND new.weight< 20.00 THEN
             SET new.cost = new.cost + 20.00;
        END IF;

        IF new.type = 5 AND new.weight> 20.00  THEN
             SET new.cost = new.cost + 20.00 + ROUND((new.weight -20.00),0);
        END IF;

        IF new.content = 1 THEN
             SET new.cost = new.cost + 0.00;
        END IF;

        IF new.content = 2  THEN
             SET new.cost = new.cost + 10.00;
        END IF;

        IF new.content = 3  THEN
             SET new.cost = new.cost *1.1;
        END IF;
    END;
    $$

    DELIMITER ;

On Update Trigger for calculating the cost of a Package
    DELIMITER $$
    CREATE TRIGGER package_cost_update BEFORE UPDATE ON Package
    FOR EACH ROW
    BEGIN
        SET new.cost = 0;
        IF new.type = 1 OR new.type = 2 OR new.type = 3  THEN
             SET new.cost = new.cost + 10.00;
        END IF;

        IF new.type = 4  THEN
             SET new.cost = new.cost + 15.00;
        END IF;

        IF new.type = 5 AND new.weight< 20.00 THEN
             SET new.cost = new.cost + 20.00;
        END IF;

        IF new.type = 5 AND new.weight> 20  THEN
             SET new.cost = new.cost + 20.00 + ROUND((new.weight -20.00),0);
        END IF;

        IF new.content = 1 THEN
             SET new.cost = new.cost + 0.00;
        END IF;

        IF new.content = 2  THEN
             SET new.cost = new.cost + 10.00;
        END IF;

        IF new.content = 3  THEN
             SET new.cost = new.cost *1.1;
        END IF;
    END;
    $$

    DELIMITER ;

On Insert Trigger for calculating the cost of a Shipment
DELIMITER $$
CREATE TRIGGER shipment_cost_insert AFTER INSERT ON Package
FOR EACH ROW
BEGIN
    UPDATE Shipment SET Shipment.`shipment_cost` = (SELECT SUM(cost) FROM Package WHERE Package.`shipment_track_no` = Shipment.`tracking_number`);
        IF (SELECT method FROM Shipment WHERE new.`shipment_track_no` = Shipment.`tracking_number`) = 1 THEN
        UPDATE Shipment SET Shipment.`shipment_cost` = Shipment.`shipment_cost` + 0.00;
    END IF;

    IF (SELECT method FROM Shipment WHERE new.`shipment_track_no` = Shipment.`tracking_number`) = 2 THEN
        UPDATE Shipment SET Shipment.`shipment_cost` = Shipment.`shipment_cost` + 10.00;
    END IF;

    IF (SELECT method FROM Shipment WHERE new.`shipment_track_no` = Shipment.`tracking_number`) = 3 THEN
        UPDATE Shipment SET Shipment.`shipment_cost` = Shipment.`shipment_cost` + 25.00;
    END IF;
END;
$$

DELIMITER ;

On Update Trigger for calculating the cost of a Shipment
DELIMITER $$
CREATE TRIGGER shipment_cost_update AFTER UPDATE ON Package
FOR EACH ROW
BEGIN
    UPDATE Shipment SET Shipment.`shipment_cost` = (SELECT SUM(cost) FROM Package WHERE Package.`shipment_track_no` = Shipment.`tracking_number`);

    IF (SELECT method FROM Shipment WHERE new.`shipment_track_no` = Shipment.`tracking_number`) = 1 THEN
        UPDATE Shipment SET Shipment.`shipment_cost` = Shipment.`shipment_cost` + 0.00;
    END IF;

    IF (SELECT method FROM Shipment WHERE new.`shipment_track_no` = Shipment.`tracking_number`) = 2 THEN
        UPDATE Shipment SET Shipment.`shipment_cost` = Shipment.`shipment_cost` + 10.00;
    END IF;

    IF (SELECT method FROM Shipment WHERE new.`shipment_track_no` = Shipment.`tracking_number`) = 3 THEN
        UPDATE Shipment SET Shipment.`shipment_cost` = Shipment.`shipment_cost` + 25.00;
    END IF;

END;
$$

DELIMITER ;


text:
Q: What causes NextJS Warning: "Extra attributes from the server: data-new-gr-c-s-check-loaded... " I'm getting the following warning from my NextJS Application:
**Warning:** Extra attributes from the server: data-new-gr-c-s-check-loaded,data-gr-ext-installed,cz-shortcut-listen
I don't know why it happens, what is the explanation for this?

A: This is usually caused by an extension installed in your browser affecting your application passing these extra attributes when code is executed there, most likely it is a language extension so if you have Grammarly or LanguageTool or any other extension similar, try disabling/uninstalling it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to load a csv file into a database when the filename for the CSV changes everyday Trying to load a .csv into a database using SQL loader but The filename is changing every day but will always start with health_safety.
Here is the control file, it loads the data but I need to put in a specific file name, so if the filename changes, it breaks.
LOAD DATA
INFILE "\\ALI.PRI\Files\Apps\CRIS\test\Trents tests\Cris Too Tidal Job\HEALTH_SAFETY\health_safety345.csv"
INTO TABLE CRIS.CRIS_HEALTH_SAFETY_DATA
FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(
REPORTING_PERIOD,
PROJECT_ID,
VENDOR_ID,
HEALTH_SAFETY_ID,
HEALTH_SAFETY_ACTUAL,
HEALTH_SAFETY_DATE
)

A: You don't say what version of Oracle you are on, but if you are on 12c the infile clause now supports wildcard characters.
If you are lucky, you could use:
INFILE "\\ALI.PRI\Files\...\health_safety*.csv"

Otherwise, you'll need a wrapper script that passes the filename in using the DATA argument. Do a little searching here, there are examples.


text:
Q: C#, Write XLSX using OpenXmlWriter and Open XML SDK In C#, the following program compiles and runs, but it doesn't write anything in the excel output file.
I got it working without the OpenXmlWriter but I started running out of memory so I have to switch to the OpenXmlWriter according to this http://blogs.msdn.com/b/brian_jones/archive/2010/06/22/writing-large-excel-files-with-the-open-xml-sdk.aspx
class Program
{
    static void Main(string[] args)
    {
        File.Copy("book.xlsx", "output.xlsx", true);
        WriteValuesSAX("output.xlsx", 10, 10);
    }

    static void WriteValuesSAX(string filename, int numRows, int numCols)
    {
        using (SpreadsheetDocument myDoc =
               SpreadsheetDocument.Open(filename, true))
        {
            WorkbookPart workbookPart = myDoc.WorkbookPart;
            WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();

            OpenXmlWriter writer = OpenXmlWriter.Create(worksheetPart);

            Row r = new Row();
            Cell c = new Cell();
            CellValue v = new CellValue("Test");
            c.AppendChild(v);

            writer.WriteStartElement(new SheetData());
            for (int row = 0; row < numRows; row++)
            {
                writer.WriteStartElement(r);
                for (int col = 0; col < numCols; col++)
                {
                    writer.WriteElement(c);
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            writer.Close();
        }
    }
}

Why doesn't it write anything to output?

A: I don't understand this well enough yet, but I got it working.
Here's what I ended up with.
class Program
{
    static void Main(string[] args)
    {
        File.Copy("book.xlsx", "output.xlsx", true);
        WriteRandomValuesSAX("output.xlsx", 10, 10);
    }

    static void WriteRandomValuesSAX(string filename, int numRows, int numCols)
    {
        using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(filename, true))
        {
            WorkbookPart workbookPart = myDoc.WorkbookPart;
            WorksheetPart worksheetPart = workbookPart.WorksheetParts.Last();

            OpenXmlWriter writer = OpenXmlWriter.Create(worksheetPart);

            Row r = new Row();
            Cell c = new Cell();
            CellValue v = new CellValue("Test");
            c.AppendChild(v);

            writer.WriteStartElement(new Worksheet());
            writer.WriteStartElement(new SheetData());
            for (int row = 0; row < numRows; row++)
            {
                writer.WriteStartElement(r);
                for (int col = 0; col < numCols; col++)
                {
                    writer.WriteElement(c);
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteEndElement();

            writer.Close();
        }
    }
}

Notice I added writer.WriteStartElement(new Worksheet()); and another writer.WriteEndElement();

I found the correct xml format here: http://msdn.microsoft.com/en-us/library/gg278309.aspx
Which is
<?xml version="1.0" encoding="utf-8"?> <x:worksheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <x:sheetData>
        <x:row r="1">
            <x:c r="A1" t="n">
                <x:v>100</x:v>
            </x:c>
        </x:row>
    </x:sheetData> </x:worksheet>

So I opened (unzipped) the xlsx file and navigated to output.xlsx\xl\worksheets\sheet1.xml and saw that I was missing the <x:worksheet>.

A: Using the code above gives me the error message "Excel found unreadable content" in Excel 2007.
Using information from here how-to-properly-use-openxmlwriter-to-write-large-excel-files and changing the code when adding the columns to the following removed the error.
for(int col = 0; col < numCols; col++)
{
    var oxa = new List<OpenXmlAttribute>();
    oxa.Add(new OpenXmlAttribute("t",null,"str"));
    writer.WriteStartElement(c,oxa);
    writer.WriteElement(new CellValue(string.Format("R{0}C{1}", row, col)));
    writer.WriteEndElement();
}


text:
Q: How do you deal with multiple developers and database changes? I would like to know how you guys deal with development database changes in groups of 2 or more devs? Do you have a global db everyone access, maybe a local copy and manually apply script changes? It would be nice to see pros and cons that you've noticed for each approach and the number of devs in your team.

A: Start with "Evolutionary Database Design" by Martin Fowler. This sums it up nicely
There are have been other questions about DB development that may be useful too, for example Is RedGate SQL Source Control for me?

A: Our approach is that everyone has their own DB, the complete DB can be created from create scripts with base data if required. All the scripts required for this are in source control.
All scripts are CREATE scripts and they reflect the current state of the database schema. Upgrades are in separate SQL files which can upgrade existing DBs from a specific version to a newer one (run sequentially). After all the updates have been applied, the schema must be identical to what you would get from running the setup scripts.
We have some tools to do this (we use SQL Server and .NET):

*

*Scripting is done with a tool which also applies a standard formatting so that the changes are well traceable with text diff tools (and by the SCM)

*A runtime module takes care of comparing the existing DB objects, run updates if required, automatically apply "non-destructive" changes, then check the DB objects again to ensure a correct migration before committing the changes

The toolset is available as open-source project (licensed under LGPL), it's called the bsn ModuleStore (note that it is limited to SQL Server 2005/2008/Azure and to .NET for the runtime part).

A: We use what was code named "Data Dude" - the database features in TFS and Visual Studio - to deal with this. When you "get latest" and bring in code that relies on a schema change, you also bring in the revised schemas, stored procedures etc. You rigght-click the database project and Deploy; that gets your local schema and sp in sync but doesn't overwrite your data. The job of working out the script to get you from your old schema to the new one falls to Visual Studio, not to you or your DBA. We also have "populate" scripts for things like lists of provinces and a deploy runs them for you.
So much better than the old way which always fell apart at high stress times, with people checking in code then going home and nobody knowing what columns to add to make the code work etc.


text:
Q: Verilog - Wiring multiple hardware instances together I am very new to Verilog and digital hardware implementation.
I want to instantiate multiple instances of a hardware block, place them side-by-side, then wire them together (ie. one block's output is the next block's input). What makes it complicated is that I want to create a 2D array-like layout of these hardware instances. Thus, each instance would propagate a signal to its lower and right-side counterpart.
This block is instantiated once below:
alg_unit alg_unit_inst (
.clk(clk),
.rst(rst),
.init(init_temp),
.in_a(in_a_temp),
.in_b(in_b_temp),
.valid_D_in(valid_D_in_temp),
);

To instantiate multiple, I am using 2 generate loops.
generate
        for (i=0; i<N; i=i+1) begin : alg_unit_generate_i
                for (j=0; j<N; j=j+1) begin : alg_unit_generate_j

                        wire init_temp;
                        wire in_a_temp;
                        wire in_b_temp;
                        wire valid_D_in_temp;

                        assign in_a_temp = A[0];
                        // other assign statements here ...

                        alg_unit alg_unit_inst (
                        .clk(clk),
                        .rst(rst),
                        .init(init_temp),
                        .in_a(in_a_temp),
                        .in_b(in_b_temp),
                        .valid_D_in(valid_D_in_temp),
                        );

           end
end
endgenerate

I need a way to refer to previously instantiated alg_unit blocks. That way, I can hook up the input signals of the alg_unit blocks generated "later" to the output signals of the alg_unit blocks generated "earlier".
Should I be assigning/storing output signals from the earlier-generated alg_unit blocks to intermediate "wire"s? Alternatively, is there a way to refer to previously instantiated alg_unit blocks?
Ie)
// alg_unit_inst[0] was a previously-instantiated block
// I feel like using the approach below may require hard-coding some instantiations ???
alg_unit alg_unit_inst[1] (
.in_a(alg_unit_inst[0].out_a),
.in_b(alg_unit_inst[0].out_b),

);

Thanks in advance.

A: With access to System Verilog I would use a 3-dimensional array:
wire [31:0] a [0:N-1][0:N-1];

Now you can wire the ports using a[x][y].
For the module at position [i][j] you can use e.g. a[i][j] at the output. To connect that to the input of the next module you can there use a[i-1][j] or a[i][j-1] or if you need to connect diagonally even a[i-1][j-1]
If ever you must use Verilog (As I had to do before System Verilog came along) you use the same method as compilers use to map an N-dimentional array on a linear memory:
wire [31:0] a [0:N*N-1];

Now the index is a combination of j and i: a[j*N+i] (If I remember correctly)


text:
Q: Issue importing properties in test In a @RunWith(SpringRunner.class) test, I want to import some properties defined in com/.../test/resources/application.yml but they are not well formatted. This issue does not replicate when running the application.
Configuration class:
@ConfigurationProperties("my.property")
@Component
@Data
public class MyConfig{

    private List<String> val1;
    private List<String> val2;
}

main/.../application.yml:
my.property.val1: [string1, string2, string3]
my.property.val2: [string1, string2]

test/.../application.yml (just the same content):
my.property.val1: [string1, string2, string3]
my.property.val2: [string1, string2]

The test class:
@RunWith(SpringRunner.class)
@TestPropertySource(locations = "classpath:application.yml")
@EnableConfigurationProperties(value = MyConfig.class)
public class MyTest {

    @Autowired
    private MyConfig myConfig;

When running the application, the object looks good (meaning that val1 is a list of string1, string2, string3), but when running the unit test, the [ and ] are also included. For example, val1 would be a list of the following Strings: [string1, string2, string3]
Basically, the issue is that the [ and ] characters are included (but this happens only on the testing part). Any ideas?

A: Can you try setting the test values as the following. Normal structure for array in yaml:
my.property.val1:
  - string1
  - string2
  - string3
my.property.val2:
  - string1
  - string2


text:
Q: How do I Inner join my calendar_table to get full range of calendar dates + my query result from other_table I have a table "calendar_table" with full calendar date set:
dt
--------------------------
2014-07-09
2014-07-10
2014-07-11
2014-07-12
2014-07-13
2014-07-14 etc.....

I have another table "activity" with columns:
aveHR   duration    date
------------------------------
74      91          2014-08-02
59      25          2014-07-31
59      27          2014-07-28
59      27          2014-07-25
59      27          2014-07-22

I want to JOIN my calendar_table to get a full sequential range of dates to pad out the missing calendar dates in other_table (first value (2014-07-22) to last value (2014-08-02))
If I run:
SELECT aveHR, duration, date FROM `activity`

I get:
74      91          2014-08-02
59      25          2014-07-31
59      27          2014-07-28
59      27          2014-07-25
59      27          2014-07-22

What I am wanting to achieve is the sequential daily dates from: 2014-07-22 to 2014-08-02. I.E. 2014-07-22, 2014-07-23, 2014-07-24, 2014-07-26, 2014-07-27, 2014-07-28, 2014-07-29, 2014-07-30, 2014-07-31, 2014-08-01, 2014-08-02
Where the matching dates from "activity" show their respective data for aveHR and duration and the dates that do not match this show the date only.
SELECT aveHR, duration, date, calendar.dt FROM `activity`
INNER JOIN calendar
ON activity.date WHERE date BETWEEN "first and last date from activity.date"

This does not work I have no idea how to get the result above any ideas?

A: You could try with LEFT JOIN. Something like:
SELECT cal.dt, aveHR, duration, date FROM calendar cal
LEFT JOIN `activity` act ON act.date = cal.dt
WHERE dt BETWEEN
(SELECT MIN(date) FROM activity)
and (SELECT MAX(date) FROM activity);

SQL DEMO FIDDLE


text:
Q: Magento2 : Create multi select category attribute with custom source Magento2 : Create multi select category attribute with custom source.
Can anyone give me with example?

A: This is just an addition to Amits Answer for last step which he has not given.
For admin form you need to create below file.
 [VendorName][ModuleName]\view\adminhtml\ui_component\category_form.xml

<?xml version="1.0"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="general">
        <field name="multi_custom_attribute">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">app\code\[VendorName]\[ModuleName]\Model\Category\Attribute\Source\Custom</item>
                <item name="config" xsi:type="array">
                    <item name="sortOrder" xsi:type="number">60</item>
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="formElement" xsi:type="string">multiselect</item>
                    <item name="label" xsi:type="string" translate="true">Custom Label</item>
                </item>
            </argument>
        </field>
    </fieldset>
</form>

@Amit you are great.
Hope this helps others.

A: For a mult select attribute, you can need to add  below at your installer:

*

*source model: [VendorName]\[ModuleName]\Model\Category\Attribute\Source\Custom.php

*backend Model [VendorName]\[ModuleName]\Model\Category\Attribute\Backend\Custom.php

*input_renderer for admin html area [VendorName]\[ModuleName]\Block\Adminhtml\Category\Helper\Custom\Options.php
Install file[app/code/[VendorName]/[ModuleName]/Setup/InstallData.php] an code:
<?php
namespace [VendorName]\[ModuleName]\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;
    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        /**
         * Add attributes to the eav/attribute
         */
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Category::ENTITY,
            'multi_custom_attribute',
                      [
                        'type' => 'text',
                        'label' => 'Custom Attribute Description',
                        'input' => 'multiselect',
                        'required' => false,

                        'source' => '[VendorName]\[ModuleName]\Model\Category\Attribute\Source\Custom',
                        'backend' => '[VendorName]\[ModuleName]\Model\Category\Attribute\Backend\Custom',
                        'input_renderer' => '[VendorName]\[ModuleName]\Block\Adminhtml\Category\Helper\Custom\Options',

                        'sort_order' => 100,
                        'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                        'group' => 'General Information',
                        'is_used_in_grid' => true,
                        'is_visible_in_grid' => false,
                        'is_filterable_in_grid' => true,
            ]
        );

    }
}

Source model:
location: app\code\[VendorName]\[ModuleName]\Model\Category\Attribute\Source\Custom.php
code:
<?php
namespace [VendorName]\[ModuleName]\Model\Category\Attribute\Source;

class Custom extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    /**
     * Catalog config
     *
     * @var \Magento\Catalog\Model\Config
     */
    protected $_catalogConfig;

    /**
     * Construct
     *
     * @param \Magento\Catalog\Model\Config $catalogConfig
     */
    public function __construct(\Magento\Catalog\Model\Config $catalogConfig)
    {
        $this->_catalogConfig = $catalogConfig;
    }

    /**
     * Retrieve Catalog Config Singleton
     *
     * @return \Magento\Catalog\Model\Config
     */
    protected function _getCatalogConfig()
    {
        return $this->_catalogConfig;
    }

    /**
     * {@inheritdoc}
     */
    public function getAllOptions()
    {
        if ($this->_options === null) {
            $this->_options = [
                                ['label' => __('Label1'), 'value' => 'value1'],
                                ['label' => __('Label2'), 'value' => 'value2'],
                                ['label' => __('Label3'), 'value' => 'value3'],
                                ['label' => __('Label4'), 'value' => 'value4']

                                ];

        }
        return $this->_options;
    }
}

backend model:
location: [VendorName]\[ModuleName]\Model\Category\Attribute\Backend\Custom.php
code:
<?php
namespace [VendorName]\[ModuleName]\Model\Category\Attribute\Backend;
class Custom extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
{
    /**
     * Core store config
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_scopeConfig;

    /**
     * Construct
     *
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig)
    {
        $this->_scopeConfig = $scopeConfig;
    }

    /**
     * Validate process
     *
     * @param \Magento\Framework\DataObject $object
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */

    /**
     * Before Attribute Save Process
     *
     * @param \Magento\Framework\DataObject $object
     * @return $this
     */
    public function beforeSave($object)
    {
        $attributeCode = $this->getAttribute()->getName();
        if ($attributeCode == 'multi_custom_attribute') {
            $data = $object->getData($attributeCode);
            if (!is_array($data)) {
                $data = [];
            }
            $object->setData($attributeCode, implode(',', $data) ?: null);
        }
        if (!$object->hasData($attributeCode)) {
            $object->setData($attributeCode, null);
        }
        return $this;
    }

    /**
     * After Load Attribute Process
     *
     * @param \Magento\Framework\DataObject $object
     * @return $this
     */
    public function afterLoad($object)
    {
        $attributeCode = $this->getAttribute()->getName();
        if ($attributeCode == 'multi_custom_attribute') {
            $data = $object->getData($attributeCode);
            if ($data) {
                if (!is_array($data)) {
                    $object->setData($attributeCode, explode(',', $data));
                } else {
                    $object->setData($attributeCode, $data);
                }

            }
        }
        return $this;
    }
}

input_renderer for admin html area:
location: [VendorName]\[ModuleName]\Block\Adminhtml\Category\Helper\Custom\Options.php
code:
<?php
namespace [VendorName]\[ModuleName]\Block\Adminhtml\Category\Helper\Custom;

class Options extends \Magento\Framework\Data\Form\Element\Multiselect
{
    /**
     * Returns js code that is used instead of default toggle code for "Use default config" checkbox
     *
     * @return string
     */
    public function getToggleCode()
    {
        $htmlId = 'use_config_' . $this->getHtmlId();
        return "toggleValueElements(this, this.parentNode.parentNode);" .
            "if (!this.checked) toggleValueElements(\$('{$htmlId}'), \$('{$htmlId}').parentNode);";
    }

    /**
     * Retrieve Element HTML fragment
     *
     * @return string
     */
    public function getElementHtml()
    {
        $elementDisabled = $this->getDisabled() == 'disabled';
        $disabled = false;

        if (!$this->getValue() || $elementDisabled) {
            $this->setData('disabled', 'disabled');
            $disabled = true;
        }

        $html = parent::getElementHtml();
        $htmlId = 'use_config_' . $this->getHtmlId();
        $html .= '<input id="' . $htmlId . '" name="use_config[]" value="' . $this->getId() . '"';
        $html .= $disabled ? ' checked="checked"' : '';

        if ($this->getReadonly() || $elementDisabled) {
            $html .= ' disabled="disabled"';
        }

        $html .= ' onclick="toggleValueElements(this, this.parentNode);" class="checkbox" type="checkbox" />';
        $html .= ' <label for="' . $htmlId . '" class="normal">' . __('Use All Available Attributes') . '</label>';
        $html .= '<script>require(["prototype"], function(){toggleValueElements($(\'' .
            $htmlId .
            '\'), $(\'' .
            $htmlId .
            '\').parentNode);});</script>';

        return $html;
    }
}

A: I have tried to run the above code. Thanks @Amit for sharing this code and @Ashish for adding missing file but there are three corrections in the paths so as to make the code work.
Below are the details of the corrections that I have done after which the module worked.
First:
In Install file [app/code/[VendorName]/[ModuleName]/Setup/InstallData.php] code:
Change:
'backend' => '[VendorName]\[ModuleName]\Model\Category\Attribute\Source\Custom',
To:
'backend' => '[VendorName]\[ModuleName]\Model\Category\Attribute\Backend\Custom',

Second:
backend model file location:
Change:
location: [VendorName]\[ModuleName]\Model\Category\Attribute\Source\Custom.php
To:
location: [VendorName]\[ModuleName]\Model\Category\Attribute\Backend\Custom.php

Third Correction is in missing file that @Ashish has shared:
Change:
<item name="options" xsi:type="object">app\code\[VendorName]\[ModuleName]\Model\Category\Attribute\Source\Custom</item>
To:
<item name="options" xsi:type="object">[VendorName]\[ModuleName]\Model\Category\Attribute\Source\Custom</item>

Hope it will help to other user's who were facing the same problem. Thanks.


text:
Q: Virtual Machine for Linux partition error: VERR_SHARING_VIOLATION I have a SSD HD with two partitions, one for Windows 10 and another for Linux mint. I am trying to create a vmdk to boot my Linux on a VM running in my Windows 10, but I am getting this error: "Cannot open the raw disk '\.\PhysicalDrive0': VERR_SHARING_VIOLATION"; when I try to run this command on Windows:
VBoxManage internalcommands createrawvmdk -filename C:\Users\mucida\Desktop\ubuntu.vmdk -rawdisk \\.\PhysicalDrive0

All solutuions that I have found so far seems to be for those who have two HD (not just one with partitions)
Any help?


text:
Q: Deprecation errors using run to test an nginx container in Kubernetes v1.3.6 I'm getting deprecation errors while trying to run a couple of nginx pods
bash-4.4$ kubectl run nginx --image=nginx --port=80 --replicas=3
WARNING: New generator "deployment/apps.v1beta1" specified, but it isn't available. Falling back to "deployment/v1beta1".
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
error: no matches for kind "Deployment" in version "apps/v1beta1"

While attempting to add the apps generator I also hit a snag...
bash-4.4$ kubectl run nginx --image=nginx --port=80 --replicas=3 --generator=deployment/apps.v1beta1
kubectl run --generator=deployment/apps.v1beta1 is DEPRECATED and will be removed in a future version. Use kubectl create instead.
error: no matches for kind "Deployment" in version "apps/v1beta1"

Not really certain what is going on, I'm just trying a simple hello world, here's the playbook that deploys and exposes
---
#######################################
# Deploy and expose Nginx service
#######################################

# Expects kubectl being configured on the local machine
# using kubectl.yml playbook

- hosts: localhost
  connection: local

  tasks:

  - name: Launch 3 nginx pods
    command: "kubectl run nginx --image=nginx --port=80 --replicas=3"
    # command: "kubectl create deployment nginx --image=nginx --generator=deployment-basic/v1beta1"

  - name: Expose nginx
    command: "kubectl expose deployment nginx --type NodePort"

  - name: Get exposed port
    command: "kubectl get svc nginx --output=jsonpath='{range .spec.ports[0]}{.nodePort}'"
    register: result
  - set_fact:
      node_port: "{{ result.stdout }}"

  - debug: msg="Exposed port {{ node_port }}"

And here is some background on the cluster and versions etc
bash-4.4$ kubectl version
Client Version: version.Info{Major:"1", Minor:"12", GitVersion:"v1.12.2", GitCommit:"17c77c7898218073f14c8d573582e8d2313dc740", GitTreeState:"clean", BuildDate:"2018-10-30T21:39:38Z", GoVersion:"go1.11.1", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"3", GitVersion:"v1.3.6", GitCommit:"ae4550cc9c89a593bcda6678df201db1b208133b", GitTreeState:"clean", BuildDate:"2016-08-26T18:06:06Z", GoVersion:"go1.6.2", Compiler:"gc", Platform:"linux/amd64"}

bash-4.4$ kubectl get  componentstatus
NAME                 STATUS    MESSAGE              ERROR
controller-manager   Healthy   ok
scheduler            Healthy   ok
etcd-1               Healthy   {"health": "true"}
etcd-2               Healthy   {"health": "true"}
etcd-0               Healthy   {"health": "true"}

Help would be greatly appreciated, I'm holding up some guys at a hackathon ;)

A: You have a very large mismatch over kubectl and Kubernetes cluster versions (1.12.2 vs 1.3.6). I recommend you download kubectl 1.3.6. If you are using Linux:
$ wget https://dl.k8s.io/v1.3.6/kubernetes-client-linux-amd64.tar.gz
$ tar zxvf kubernetes-client-linux-amd64.tar.gz

Or MacOS:
$ wget https://dl.k8s.io/v1.3.6/kubernetes-client-darwin-amd64.tar.gz
$ tar zxvf kubernetes-client-darwin-amd64.tar.gz


text:
Q: MongoDB Ops Manager backup and restore The documentation claims that snapshots taken by ops manager are delta (differential) between successive snapshots.

*

*How do you then restore?

*I mean if you are able to delete some snapshots according to
retention, how do you connect the dots in between to restore to a
point in time.

*What do they mean by base snapshot? Is that whole backup?

*How can a given snapshot become full and ready for restore if any
snapshot before it is deleted?

I understand one can replay oplog to go forward to a point in time from a given snapshot. This question is if any snapshot before the snapshot where restore begins gets deleted how can you restore?
From MongoDB docs:
"...The snapshot only stores the differences between successive snapshots. Snapshots use only a fraction of the disk space required for full snapshots."
Any help is much appreciated.

A: I'm not sure which version of Ops Manager you were running, but there's been a lot of improvements in the last year. The latest docs explain the space-spacing approaches of the different storage choices:

*

*MongoDB blockstore and AWS S3 bucket  - Each successive snapshot stores only the differences from the previous snapshot. Compression and block-level de-duplication reduce the size of snapshot data.

*File system store - uses compression only.


text:
Q: Getting a KeyHash I can't get keyhash, it shows this System error.How can I fix this
W/System.err: android.content.pm.PackageManager$NameNotFoundException:
Here is my code
PackageInfo info;
    try {
         info = getPackageManager().getPackageInfo(
                 "com.example.yunus.quetosviewpager",
                 PackageManager.GET_SIGNATURES);
         for (Signature signature : info.signatures) {
             MessageDigest md = MessageDigest.getInstance("SHA");
             md.update(signature.toByteArray());
             Log.d(TAG, Base64.encodeToString(md.digest(), Base64.DEFAULT));
         }
     } catch (PackageManager.NameNotFoundException e) {
         e.printStackTrace();
     } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
     }

A: Please double check if your packagename is spelt correctly. Also, an app with that package name that is written inside of
getPackageManager().getPackageInfo(
             "com.example.yunus.quetosviewpager",
             PackageManager.GET_SIGNATURES);

should be installed on the device where you are running those lines, just in case you have a separate app for obtaining SHA.


text:
Q: C# Use async or thread for long running database activity in Azure SQL I have a nightly C# Windows service that updates tables and calls a long running (~ hour) stored procedure on 5-10 Azure SQL databases.  Since I can run all database work at the same time in Azure SQL with little to no performance hit, I'd like to run them asynchronously.  I can either call a method with async void (using Await Task.Delay(10)) or create a new thread.
What is the better approach?... does it matter?
EDIT: Here is an example of the asynch void method.  I want to make sure it's clear what it's doing.
 public static async void DoRanking(object e)
    {
        // will start all orgs concurrently
        await Task.Delay(10);
        ... do a bunch of database work here ...
        ... call a long running stored procedure here ...
    }

A: You can use the older Thread/ThreadPool APIs or the newer TPL.  But in either case you shouldn't just start a long-running process on a threadpool thread.
Use a new Thread or a LongRunning Task:

Specifies that a task will be a long-running, coarse-grained operation
involving fewer, larger components than fine-grained systems. It
provides a hint to the TaskScheduler that oversubscription may be
warranted. Oversubscription lets you create more threads than the
available number of hardware threads. It also provides a hint to the
task scheduler that an additional thread might be required for the
task so that it does not block the forward progress of other threads
or work items on the local thread-pool queue.

Documentation for TaskCreationOptions.LongRunning


text:
Q: Transactions and Order Safety with MySQL (InnoDB) Scenario
Say I have a list of voucher codes that I am giving away, I need to ensure that if two persons place an order at the exact same time, that they do not get the same voucher.
Tables
CREATE TABLE IF NOT EXISTS `order` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `voucher_id` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `voucher_id` (`voucher_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `order` ADD CONSTRAINT `order_fk` FOREIGN KEY (`voucher_id`) REFERENCES `voucher` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

CREATE TABLE IF NOT EXISTS `voucher` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Sample data
INSERT INTO `voucher` (`code`) VALUES ('A'), ('B'), ('C');

Sample Query
SELECT @voucher_id := v.id FROM `voucher` v LEFT JOIN `order` o ON o.voucher_id = v.id WHERE o.id IS NULL;
INSERT INTO `order` (`voucher_id`) VALUES (@voucher_id);

Question
I believe the UNIQUE KEY on voucher_id in the order table will prevent two orders having the same voucher_id, giving an error / throwing an exception if the same voucher id is inserted twice. This would require a while loop to retry upon failure.
The alternative is read locking the vouchers table before the SELECT and releasing that lock after the INSERT, ensuring the same voucher isn't picked twice.
My question is therefore:

*

*Which is faster?

*

*A while loop in PHP code.

*Read locking the vouchers table.

*Is there another way?

Edits
ALTER TABLEorderCHANGEvoucher_idvoucher_idBIGINT(20) UNSIGNED NOT NULL
will cause the INSERT to fail if @voucher_id is null (as desired, as there would be no vouchers left).

A: You can use START TRANSACTION, COMMIT, and ROLLBACK to prevent race conditions in your SQL. http://dev.mysql.com/doc/refman/4.1/en/commit.html
In your case, I would just put your transactions into a critical area bounded by these tokens.

A: The "correct" and by that I mean best way to do what you're looking to do is to generate the voucher at the time you place the order. Look at the documentation for the sha1() function in php. You can seed it with unique information to prevent duplicates and use that for your voucher along with an auto_increment field for the unique ID.
When the order is placed, PHP generates a new voucher, saves it to the database, and sends it to the user. This way you're only storing valid vouchers and you're also preventing duplicates from being created.


text:
Q: select two markers & draw line between them in leaflet I am very much new to leaflet.
I have multiple markers plotted on my map in leaflet.
now I have to draw line between two markers when I select them.
Can any one help in doing this.

A: So it seems to me all you have to do is take the two markers you have selected and grab their latlngs and add them to the polyline.
var latlngs = Array();

//Get latlng from first marker
latlngs.push(marker1.getLatLng());

//Get latlng from first marker
latlngs.push(marker2.getLatLng());

//You can just keep adding markers

//From documentation http://leafletjs.com/reference.html#polyline
// create a red polyline from an arrays of LatLng points
var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);

// zoom the map to the polyline
map.fitBounds(polyline.getBounds());

Edit
In case you are looking for a way to also get the selected markers. You will need to probably listen to the click event of each marker and add the markers to an array that contains your selected markers.  You will just need to limit that array to two entries.  This is not an optimal solution but should get you there and will allow you to easily extend if you want more than two markers.


text:
Q: How to import data to mongodb container and creating an image I spent a lot of time on a task which seems a simple one. I want to run a monogodb container. then copy csv file in to the container or execute a command from docker file to import the csv file into the mongodb database. I tried using RUN, script.sh but nothing is working. Please help.
I want to automate the task and when I copy the data, I will make a new image for my automated task.
Here is the Dockerfile I have.
FROM mongo
RUN mkdir -p /app/data
WORKDIR /app/data
COPY gene.csv /app/data
COPY script.sh /app/data
EXPOSE 27017
# CMD ["/app/data/script.sh"]

The script file is
#! /bin/sh
mongoimport -d Gene -c genes --type csv --file gene.csv --headerline

A: Too late, maybe help to others.
    FROM mongo
    RUN mkdir -p /app/data
    WORKDIR /app/data
    COPY gene.csv /app/data
    COPY script.sh /app/data
    CMD ["mongod", "&&", "mongoimport", "-d", "Gene", "-c", "Genes", "--file", "gene.csv", "--headerline"]

A: Edit: This answer solves a problem, but not the problem, as apparently mongo has to be running for any of this to work. In that case a custom entrypoint is probably the way to go.
Using RUN is the right way, as then when you use CMD you can actually run the Mongo process. However your problem is with your COPY instructions.
COPY gene.csv /app/data
COPY script.sh /app/data

These lines need a / on the end, as right now they say 'copy this file from my host, to be this file in my container'. Whereas you're trying to say 'copy this file from my host, into this folder in my container. They should read as below (but can be simplified even further, see final Dockerfile at the end):
COPY gene.csv /app/data/
COPY script.sh /app/data/

Your script will then run if you put it in a RUN instruction and that layer will be committed into the image, then you can have a CMD at the end to run mongo (or just leave it blank and inherit the default ENTRYPOINT / CMD from the parent (mongo) image. So the full Dockerfile becomes:
FROM mongo
WORKDIR /app/data        # This will be created if it doesn't exist
COPY gene.csv .
COPY script.sh .
RUN chmod +x script.sh && sync && ./script.sh

A: I was able to do that but through another container. Whose job is to insert the data in to the mongodb database container and exit. For more details check the accepted answer here. I changed the JSON file with my csv file and the command which import it, although I found that mongodb works better with json.


text:
Q: Validate whether a string is valid for IP Address or not As title, I want to validate whether a string is valid for IP Address or not in C#, and I've used
IPAddress.TryParse(value out address)

but it seems not so "Accurate", which means if I enter "500", the address will be "0.0.1.244", so its "Valid".
However, the form I'd like to accept is like "xxx.xxx.xxx.xxx", and each term is less than 256. Is there any API or method could achieve this?

A: You can pretty straightforward check it: split string to parts separated by dot and ensure it will be exactly four parts having values in range 1...255:
string s = "123.123.123.123";

var parts = s.Split('.');

bool isValid = parts.Length == 4
               && !parts.Any(
                   x =>
                   {
                       int y;
                       return Int32.TryParse(x, out y) && y > 255 || y < 1;
                   });

A: Something like that:
private static Boolean IsIP(String value) {
  if (String.IsNullOrEmpty(value))
    return false;

  var items = value.Split('.');

  if (items.Length != 4)
    return false;

  // Simplest: you may want use, say, NumberStyles.AllowHexSpecifier to allow hex as well
  return items.All(item => byte.TryParse(item, out _));
}

A: If you dont rely on TryParse here is one way to match for xxx.xxx.xxx.xxx
public static bool MyIP(string value)
    {
        var x = value.Split('.');
        if (!(x.Length==4))
           return false;

        foreach(var i in x)
        {
            int q;
            if (!Int32.TryParse(x, out q)||q.ToString().Length.Equals(x.Length)
                || q < 0 || q > 255)
            {
               return false;
            }

        }

        return true;
    }

A: If you'd rather not do the parsing yourself the NuGet package IPAddressRange will do it for you. It has the advantage of supporting IPv6 addresses as well.
You can check out the source code and documentation here.

A: string addrString = "192.168.0.1";
IPAddress address;
if (IPAddress.TryParse(addrString, out address)) {
       //Valid IP, with address containing the IP
} else {
       //Invalid IP
}

A: You could try what you are already doing, with a short test before hand to ensure there are the correct number of "."s in the string.
https://msdn.microsoft.com/en-us/library/system.net.ipaddress.tryparse.aspx
It will determine if string is valid IPv4 address, this will not work for IPv6:
var stringToCheck = "192.168.1.1";
var countDots = stringToCheck.Split('.').Length - 1;
if (countDots==3)
{
    IPAddress validIpAddress;
    if (IPAddress.TryParse(stringToCheck, out validIpAddress))
    {
        //Valid IP, with validIpAddress containing the IP
        Console.WriteLine("Valid IP");
    }
    else
    {
        //Invalid IP
        Console.WriteLine("Invalid IP");
    }
}
else
{
    // Invalid as no "." in string, not even worth checking
    Console.WriteLine("Invalid IP not correct number Dots");
}


text:
Q: Where can I find Cypher Grammar specification? As a part of my assignment at the University I have to go trough Cypher specification. The link on openCypher site is broken. Is this what is published on gihhub current version of openCypher specification? I don't see the version denoted anywhere.

A: The file name in the grammar link has not been updated to M19, like all the other links.
It should be https://s3.amazonaws.com/artifacts.opencypher.org/M19/grammar-M19.zip.
You should inform the openCypher project so that it can be fixed. I have created a pull request to fix the links: https://github.com/opencypher/website/pull/27


text:
Q: How to return XML from SQL Server 2008 that is structured with multiple selections sharing a common parent I've tried using "FOR XML PATH", "FOR XML EXPLICIT" and "FOR XML AUTO" but the data is never structured with the correct heirarchy.
Basically, I have one parent table (Customers) and 3 child tables. Each table has a customerid column. There is a one-to-many relationship from the Customers table to each of the 3 child tables.
As a mock example, I have a parent "Customers" table, and I have 3 other tables - Products, Hobbies and Vehicles - all related to the Customers table by a customerid.
What is the SQL code to achieve the following kind of structure -
<Customers>
    <Customer customerid="1" name="Fred">
       <Products>
           <Product productname="table" />
           <Product productname="chair" />
           <Product productname="wardrobe" />
       </Products>
       <Hobbies>
           <Hobby hobbyname="Golf" />
           <Hobby hobbyname="Swimming" />
       </Hobbies>
       <Vehicles>
           <Vehicle name="Car" color="Red" />
           <Vehicle name="Bicycle" color="Blue" />
       </Vehicles>
    </Customer>
    <Customer customerid="2" name="Sue">
       <Products>
           <Product productname="CD player" />
           <Product productname="Picture frame" />
       </Products>
       <Hobbies>
           <Hobby hobbyname="Dancing" />
           <Hobby hobbyname="Reading" />
       </Hobbies>
       <Vehicles>
           <Vehicle name="Car" color="Yellow" />
       </Vehicles>
    </Customer>
</Customers>

A: Try something like this - it uses FOR XML PATH and subselects to create the "linked" sub-nodes for a given customer (I limited this to two sub tables - but you should get the "gist" of it and be able to extend it to any number of linked subtables):
SELECT
    CustomerID AS '@CustomerID',
    CustName AS '@Name',

    (SELECT ProductName AS '@productname'
     FROM dbo.Products p
     WHERE p.CustomerID = c.CustomerID
     FOR XML PATH('Product'), TYPE) AS 'Products',

    (SELECT HobbyName AS '@hobbyname'
     FROM dbo.Hobbies h
     WHERE h.CUstomerID = c.CustomerID
     FOR XML PATH('Hobby'), TYPE) AS 'Hobbies'
FROM
    dbo.Customers c
FOR XML PATH('Customer'), ROOT('Customers')

Gives me an output something like:
<Customers>
  <Customer CustomerID="1" Name="Fred">
    <Products>
      <Product productname="Table" />
      <Product productname="Wardrobe" />
      <Product productname="Chair" />
    </Products>
    <Hobbies>
      <Hobby hobbyname="Golf" />
      <Hobby hobbyname="Swimming" />
    </Hobbies>
  </Customer>
  <Customer CustomerID="2" Name="Sue">
    <Products>
      <Product productname="CD Player" />
      <Product productname="Picture frame" />
    </Products>
    <Hobbies>
      <Hobby hobbyname="Dancing" />
      <Hobby hobbyname="Gardening" />
      <Hobby hobbyname="Reading" />
    </Hobbies>
  </Customer>
</Customers>

A: Using FOR XML RAW
IF OBJECT_ID ('tempdb..#customer') IS NOT NULL DROP TABLE #Customer
IF OBJECT_ID ('tempdb..#product') IS NOT NULL DROP TABLE #product
IF OBJECT_ID ('tempdb..#vehicle') IS NOT NULL DROP TABLE #Vehicle
IF OBJECT_ID ('tempdb..#hobbies') IS NOT NULL DROP TABLE #Hobbies

CREATE TABLE #Customer (id INT,name NVARCHAR(20))
INSERT INTO #customer SELECT 1,'Fred' UNION ALL SELECT 2,'Sue'

CREATE TABLE #product(customer_id INT, name NVARCHAR(20))
INSERT INTO #product
SELECt 1 AS id, 'table' as product
UNION ALL SELECT 1 AS id, 'chair' as product
UNION ALL SELECT 1 AS id, 'wardrobe' as product
UNION ALL SELECT 2 AS id, 'CD Player' as product
UNION ALL SELECT 2 AS id, 'Picture Frame' as product

CREATE TABLE #vehicle(customer_id INT, name NVARCHAR(20),colour NVARCHAR(20))
INSERT INTO #vehicle
SELECt 1 AS id, 'Car' as vehicle,'red' as colour
UNION ALL SELECT 1 AS id, 'bicycle' as vehicle,'Blue' AS colour
UNION ALL SELECT 2 AS id, 'Car' as vehicle, 'Yellow' as colour

CREATE TABLE #hobbies(customer_id INT, name NVARCHAR(20))
INSERT INTO #hobbies
SELECt 1 AS id, 'Golf' as name
UNION ALL SELECT 1 AS id, 'Swimming' as name
UNION ALL SELECT 2 AS id, 'Dancing' as name
UNION ALL SELECT 2 AS id, 'Reading' as name

SELECT
c.id AS id
,c.name AS name
,(SELECT p.name
    FROM #product p
    WHERE p.customer_id = c.id
    FOR XML RAW('Products'),TYPE) AS Products
,(SELECT h.name
    FROM #hobbies h
    WHERE h.customer_id = c.id
    FOR XML RAW('Hobbies'),TYPE) AS Hobbies
,(SELECT v.name,v.colour
    FROM #vehicle v
    WHERE v.customer_id = c.id
    FOR XML RAW('Vehicle'),TYPE) AS Vehicle
FROM #customer c
FOR XML RAW('Customer'), ROOT('Customers')

A: select
    c.customerid,
    c.name,
    (
        select p.productname
        from Products as p
        where p.customerid = c.customerid
        for xml raw('Product'), root('Products'), type
    ),
    (
        select h.hobbyname
        from Hobbies as h
        where h.customerid = c.customerid
        for xml raw('Hobby'), root('Hobbies'), type
    ),
    (
        select v.name, v.color
        from Vehicles as v
        where v.customerid = c.customerid
        for xml raw('Vehicle'), root('Vehicles'), type
    )
from Customers as c
for xml raw('Customer'), root('Customers')

=> sql fiddle demo

A: DECLARE @sampleCount int =10
SET STATISTICS TIME ON

SELECT

    (SELECT TOP  (@sampleCount) * FROM [Table1]TABLESAMPLE(100 PERCENT) FOR XML PATH('tbl1'), TYPE) AS 'tbl1',
    (SELECT top (@sampleCount) * FROM [Table2] TABLESAMPLE(100 PERCENT)  FOR XML PATH('tbl2'), TYPE) AS 'tbl2',
    (SELECT top (@sampleCount) * FROM [Table3] TABLESAMPLE(100 PERCENT) FOR XML PATH('tbl3'), TYPE) AS 'tbl3'

FOR XML PATH(''), ROOT('Table')

A: USE [EAPP_BranchDb]
GO

/****** Object:  StoredProcedure [dbo].[SP_procXMLOutput]    Script Date: 09/05/2013 15:14:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_procXMLOutput]
                   @Data XML  OUTPUT
AS
BEGIN

DECLARE @myDoc xml,
        @myDoc1 xml,
        @var_Doc1 nvarchar(max),
        @myDoc2 xml,
        @var1 nvarchar(max),
        @var2 nvarchar(max),
        @var3 nvarchar(max),
        @var_id as int,
        @var_id1 as nvarchar(10),
        @var_grp_id1 as nvarchar(10),
        @var_parent_id as bigint,
        @var_grp_id as nvarchar(10),
        @var_parent_type as nvarchar(1),
        @var_type as nvarchar(10),
        @xml XML,
        @grp1 nvarchar(max),
        @grp2 nvarchar(max)

DECLARE xml_cur_id CURSOR FOR
SELECT id, parent_id, grp_id, parent_type,type FROM xml_table where parent_type='P' order by id

DECLARE xml_cur_grpid CURSOR FOR
SELECT GRP_ID FROM xml_table WHERE parent_id=6 and parent_type='C' group by GRP_ID

BEGIN
    SET @myDoc = N'<frameSet label="Personal Details" id="1"
                   </frameSet';

    SET @var_Doc1='<field pid="6" type="ROW" /</field';
    OPEN xml_cur_id
        FETCH NEXT FROM xml_cur_id INTO @var_id, @var_parent_id, @var_grp_id, @var_parent_type,@var_type
            WHILE @@FETCH_STATUS = 0
            BEGIN

            IF @var_type<'TABLE' and @var_parent_type='P'
            BEGIN
                SET @myDoc1=(SELECT id, name, type, isMandtory, isDependent, isDependentValue,dataType, lookupPath, lookupName, defaultValue, minDate, maxDate, fieldLabel, maxLength, readonly, disabled, onChangeEvent, reloadEvent,  validationMessage, tabindex FROM xml_table WHERE id=@var_id FOR XML RAW('field'))
                SET @myDoc.modify('insert sql:variable("@myDoc1") as last into (/frameSet)[1] ')
            END

            IF @var_type='TABLE' and @var_parent_type='P'
            BEGIN
                /*table parent creation START*/
                SET @myDoc1=(SELECT id, name, type,fieldLabel FROM xml_table WHERE id=@var_id FOR XML RAW('field'))
                SET @myDoc.modify('insert sql:variable("@myDoc1") as last into (/frameSet)[1] ')
                /*table parent creation END*/

                /*table COLUMN creation START*/
                SELECT @var1=(SELECT type,fieldLabel FROM XML_RELATION_TABLE WHERE Parent_id=6 order by id FOR XML RAW('field'))
                SELECT @var2=(SELECT '<field type="ROW"'+@var1+'</field')
                SELECT @myDoc1=@var2
                SET @var_id1=@var_id
                /*table COLUMN creation START*/
                /*TABLE CHILD row creation START*/
                SET @var3=''
                OPEN xml_cur_grpid
                    FETCH NEXT FROM xml_cur_grpid INTO @var_grp_id1
                        WHILE @@FETCH_STATUS = 0
                        BEGIN

                            SELECT @grp1=(SELECT id, name, type, isMandtory, isDependent, isDependentValue,dataType, lookupPath,
                            lookupName, defaultValue, minDate, maxDate, fieldLabel, maxLength,
                            readonly, disabled, onChangeEvent, reloadEvent,  validationMessage, tabindex FROM xml_table
                            WHERE parent_id=@var_parent_id and parent_type='C' and grp_id=@var_grp_id1 order by id
                            FOR XML RAW('field'))

                            SELECT @grp2=(SELECT '<field type="ROW"'+@grp1+'</field')
                            SET @var3=@var3+@grp2

                        FETCH NEXT FROM xml_cur_grpid INTO @var_grp_id1
                        END
                CLOSE xml_cur_grpid
                DEALLOCATE xml_cur_grpid
                /*TABLE CHILD row creation END*/

                SELECT @myDoc1=@var2+@var3
                SET @myDoc.modify('insert sql:variable("@myDoc1")  into (/frameSet/field[@id=sql:variable("@var_id1")])[1] ')
                SET @var2=''
                SET @var3=''
           END

           FETCH NEXT FROM xml_cur_id INTO @var_id, @var_parent_id, @var_grp_id, @var_parent_type,@var_type
           END
    CLOSE xml_cur_id
    DEALLOCATE xml_cur_id

    SET @Data=@myDoc

END

END

GO


text:
Q: Cakephp Custom Finder for Auth, with related model First, this question builds on the question and answer here:  Modifying AuthComponent identify method
What I'm trying to implement is token based access to API using Basic Auth over SSL.  I have the API prefix setup and working, and I've successfully used Basic authentication AS LONG AS the fields defined for username & password are within the Tokens table, as below:
public function initialize() {
    parent::initialize();
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Basic' => [
                'fields' => ['username' => 'user_id', 'password' => 'app_key_hashed'],
                'userModel' => 'Tokens'
            ]
        ],
        'storage' => 'Memory',
        'unauthorizedRedirect' => false
    ]);
}

Ultimately I would like to authenticate using the User's email (From the Users model) AND the app_key (from the Tokens model).  After reading the documentation (and the above linked question and answer), I feel as though I need to implement this using a custom finder.  So I change the code above to read:
public function initialize() {
    parent::initialize();
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Basic' => [
                'fields' => ['username' => 'user.email', 'password' => 'app_key_hashed'],
                'userModel' => 'Tokens',
                'finder' => 'auth'
            ]
        ],
        'storage' => 'Memory',
        'unauthorizedRedirect' => false
    ]);
}

And include the following in my TokensTable.php:
    /**
 * Custom finder for Auth
 */

public function findAuth(\Cake\ORM\Query $query, array $options) {
    $query->select(['id', 'user_id', 'app_key_hashed', 'Users.email'])
            ->where(['Tokens.inactive' => 0])
            ->contain(['Users']);

    return $query;
}

When I do this, the return message is this:
{
  "message": "SQLSTATE[42S22]: Column not found: 1054 Unknown column    'Tokens.user.email' in 'where clause'",
  "url": "/flight-ops/api/tokens",
  "code": 500
}

I feel as though the issue isn't in the custom finder finding the data, but in the filtering of the data by the Auth component.  Am I correct?  Am I missing something simple?  Am I barking up the right tree using a custom finder?
I'm using CakePHP 3.2.4.
Thanks for your help!
Here are my Tables and relationships:
class TokensTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('tokens');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

    $this->belongsTo('Users', [
        'foreignKey' => 'user_id'
    ]);
}
}

class UsersTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('users');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->addBehavior('Timestamp');

    $this->hasOne('Tokens', [
        'foreignKey' => 'user_id'
    ]);
}
}

A: First, thanks to Chris in the comments above for confirming I was heading in the right direction.  I accomplished the task in the question by extending the BasicAuthenticate class (really, I only extended a function from BaseAuthenticate, but I wanted to include BasicAuthenticate at the same time, so I extended that class).
Here is my TokenBasicAuthenticate class:
namespace App\Auth;

use Cake\Auth\BasicAuthenticate;
use Cake\Network\Request;
use Cake\Network\Response;
use Cake\ORM\TableRegistry;

class TokenBasicAuthenticate extends BasicAuthenticate{

    protected function _query($username)
    {

        $config = $this->_config;
        $table = TableRegistry::get($config['userModel']);

        $query = $table->find()
                        ->where([$config['userModel'] . '.inactive' => 0])
                        ->contain([$config['relatedModel']])
                        ->matching($config['relatedModel'], function($q) use ($config, $username) {
                           return $q->where([$config['fields']['username'] => $username]) ;
                        });

        return $query;

    }
}

I also changed my Auth initialization to this:
public function initialize() {
        parent::initialize();
        $this->loadComponent('RequestHandler');
        $this->loadComponent('Auth', [
            'authenticate' => [
                'TokenBasic' => [
                    'fields' => ['username' => 'Users.email', 'password' => 'app_key_hashed'],
                    'userModel' => 'Tokens',
                    'relatedModel' => 'Users',
                    'finder' => 'auth'
                ]
            ],
            'storage' => 'Memory',
            'unauthorizedRedirect' => false
        ]);
    }

As you can see, I included an additional field 'relatedModel' to reference the related model.
It works well for my needs, hopefully someone else finds this as useful.  I'm sure there's more than one way to complete this, feel free to add anything useful.


text:
Q: Upgrading from 10.04 to 12.04.1 stuck at downloading python-qt4 I am a Java programmer and I consider myself a Linux newbie. So I could use a little help here.
I am trying to update my Ubuntu from version 10.04 to 12.04.1 (LTS). The downloading start and runs at around 10MB/s until I am somewhere near 26% and the speed just drops to 0.
I figured I could use the command do-release-update so I could see what it was doing. Again the same occurred: the downloading got stuck on 26% at http://nl.archive.ubuntu.com/ubuntu/ precise/main python-qt4 1386 4.9.1-2ubuntu1. It says it downloaded 41% of that file/package. It also tries another wget on the same file every X seconds.
Help?


text:
Q: Choose part of Row Names as qualifier I'm currently trying to select rows from a data frame in R based on the row names of another data frame, which is usually straight forward:
data1 <- data1[which(row.names(data1) %in% row.names(data2))]

But, my current challenge involves differing lengths of row names between the two data sets. My first data frame has row names that are the first 12 characters of the row names of my second data frame. I want to be able to pick out the rows that have the first 12 characters matching across the two data sets but I'm having problems. Any suggestions?

A: Use substr():
data1 <- data1[which(row.names(data1) %in% substr(row.names(data2), 1, 12)), ]


text:
Q: Finding a seven-digit number with all of its prime factors less than 20? How can I find a seven-digit number with all of its prime factors less than 20?
I have no clue how to do this.

A: Given that the 8th prime is less than 20 (Prime[8] = 19), then the product of all primes up to and including that one is:
Times @@ Prime[Range[8]]

(*
9699690
*)
You can list those primes:
Prime[Range[8]]

You can answer the generalized problem from the below figure, e.g., How many distinct, sequential, smallest prime factors are needed to get a number greater than $10^{18}$?
ListLogPlot[Table[{i, Times @@ Prime[Range[i]]}, {i, 1, 20}],
 AxesLabel -> {Text[
    Style["number of\n sequential prime\n factors of \!\(\*
StyleBox[\"x\",\nFontSlant->\"Italic\"]\)", 18]], Text[Style["\!\(\*
StyleBox[\"x\",\nFontSlant->\"Italic\"]\)", 18]]},
 ImageSize -> 500]


text: Q: Read chars in Text area and produce desired output back in Text area, for Text Editor project I am working on a personal project and want to create a text editor to write my code. I am wondering how could I read the last input from the user and if say it was an open curly brace {, then like netbean's my editor will supply the closing curly brace. My java experience is limited but have tried to read key board input and a few other options that did not work. I would really appreciate some help and guidance on the subject please?


text:
Q: Zend2 Db\Select with dynamic IN clause with HAVING SELECT
    CONCAT_WS(' ', user.firstname, user.lastname) AS name,
    user.email AS email
FROM
    user
WHERE
    op_id IN (
        SELECT
            user.op_id AS op_id
        FROM
            user
        WHERE
            last_login_on IS NOT NULL
        GROUP BY op_id
        HAVING (SUM(IF(DATE(last_login_on) > DATE(DATE_SUB(NOW(), INTERVAL 31 DAY)), 1, 0)) = 0)
        ORDER BY op_id ASC)
AND role_type = 'owner';

From the SQL above which, from all users assigns 1 if login within last month and 0 if not logged in for more than a month, then reduces the result set to the ones HAVING 0 logins as the IN clause and then SELECTs the op_id owner details.
This has been replicated in Zend DB\Select and all works as expected, except the HAVING clause is lost in the generated SQL query, when used as a new Expression ("SUM(IF(DATE(last_login_on) > DATE(DATE_SUB(NOW(), INTERVAL 31 DAY)), 1, 0)) = 0").
Can this expression be applied to a $select->having() statement?

A: This should be possible, having() method of Select accepts an expression as parameter. The problem is which expression you use: \Zend\Db\Sql\Expression or \Zend\Db\Sql\Predicate\Expression, although Predicate\Expression inherits from Sql\Expression. Honestly, the difference is not completely clear to me, but I was able to create your query without having got lost:
$select = new Select('user');

$inSelect = new Select('user');
$inSelect->columns(array('op_id' => 'op_id'));
$inSelect->where(new \Zend\Db\Sql\Predicate\IsNotNull('last_login_on'));
$inSelect->group('op_id');
$inSelect->order(array('op_id' => 'asc'));
$inSelect->having(new \Zend\Db\Sql\Predicate\Expression('SUM(IF(DATE(last_login_on) > DATE(DATE_SUB(NOW(), INTERVAL 31 DAY)), 1, 0)) = 0'));

$inExpression = new In('op_id', $inSelect);
$select->where($inExpression);
$select->where(array('role_type' => 'owner'), PredicateSet::OP_AND);

echo $select->getSqlString();

This should echo a string like this:
SELECT
    user.*
FROM
    user
WHERE
    op_id IN (
        SELECT
            user.op_id AS op_id
        FROM
            user
        WHERE
            last_login_on IS NOT NULL
        GROUP BY op_id
        HAVING SUM(IF(DATE(last_login_on) > DATE(DATE_SUB(NOW(), INTERVAL 31 DAY)),
        1,
        0)) = 0
        ORDER BY op_id ASC
    )
AND role_type = 'owner'

Edit:
ZF2 Version: 2.4.9


text:
Q: Error react native running base starter app from bundle Walking through the react-native tutorial, (install prerequisites, then 'react-native init AwesomeProject', and 'react-native run-ios', runs fine in the simulator) when I open the xcode project and try to run from a local bundle (option 2 in AppDelegate.m) I get the following error:

/Users/webb/projects/nativeapp/fuel/node_modules/node-haste/lib/index.js:331
Object.assign(DependencyGraph, {
       ^
TypeError: Object.assign is not a function
    at Object.<anonymous> (/Users/webb/projects/nativeapp/fuel/node_modules/node-haste/lib/index.js:331:8)
    at Module._compile (module.js:430:26)
    at Module._extensions..js (module.js:448:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/webb/projects/nativeapp/fuel/node_modules/babel-register/lib/node.js:166:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (index.js:16:30)
    at Module._compile (module.js:430:26)
Command /bin/sh failed with exit code 1

The error persists if I run in release or debug build configuration.  And happens both on the simulator and device.  Pretty much I am only able to run the sample app with AppDelegate.m configured for option 1 (load from dev server) which wont fly when I want to publish my app.
I tried both node 5.8 and 6.1.  Can anyone else think of next steps in debugging?  This is just the base sample app, it should run from a local bundle right?

"dependencies": {
    "react": "^0.14.8",
    "react-native": "^0.25.1"
  }

I am on a mac, have not tried android, but iOS is for sure non functional.

A: I started fresh on a new machine, everything works fine on a new machine.  So there was obviously something wrong on my old machine, I found mention that global CLI installs of Babel will cause funky issues like I was seeing.  This may have been the case, although it was still persisting after I uninstalled Babel.
My advice if you start to run into this is to not waste a week trying to solve it.  Reload your OS and start fresh.


text:
Q: Is it possible to edit grub.cfg? I wish to change a menu entry in grub.cfg, for example:
From
### BEGIN /etc/grub.d/10_linux ###
menuentry 'Ubuntu is wonderful'

To
### BEGIN /etc/grub.d/10_linux ###
menuentry 'Ubuntu is world famous'

A: How to do it from an emulator to learn how GRUB works, without the risk of breaking anything.

*

*create a Multiboot hello world main.elf file. GRUB knows how to boot those files (GRUB also knows how to boot the Linux kernel, even though it is not Multiboot)

*create a iso/boot/grub/grub.cfg file containing:
menuentry "main" {
    multiboot /boot/main.elf
}

Place main.elf under iso/boot/

*Generate an image and run it:
grub-mkrescue -o main.img iso
qemu-system-x86_64 -hda main.img

This will boot into GRUB, and you will see an entry called main.
Now edit grub.cfg like menuentry "newmain", and upon a reboot the new option name is newmain. So your change would work.
I have posted the exact code for this example at: https://github.com/cirosantilli/x86-bare-metal-examples/tree/d217b180be4220a0b4a453f31275d38e697a99e0/multiboot/hello-world
As others said, don't do it in practice, since that is normally an output file and will get overwritten on update-grub.

A: Edit /etc/grub.d/10_linux instead and run sudo update-grub when you are done. This is a more reliable method, otherwise every time you upgrade to a new kernel your /boot/grub/grub.cfg will be overwritten and you will lose your changes.
Or you can use Grub Customizer. To install it:
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer

A: yes you can edit this file /boot/grub/grub.cfg


text:
Q: Dropdown menu in latest Angular I have the following directive for a custom dropdown menu:
import { Directive, ElementRef, HostBinding, HostListener } from "@angular/core";

@Directive({
    selector: '[appDropdown]'
})
export class DropdownDirective {

    @HostBinding('class.open') isOpen = false;

    @HostListener('document:click', ['$event']) toggleOpen(event: Event) {
        this.isOpen = this.elementRef.nativeElement.contains(event.target) ? !this.isOpen : false;
    }

    constructor(private elementRef: ElementRef) {
        //
    }
}

I have included the references in my app.module.ts of course.
The following is what I have put in my header.component.html:

                        Recipes

                        Shopping List

                        Manage

                                Save Data

                                Fetch Data List

I changed my class from navbar-default to collapse.
The following is the Manage button that is supposed to have the dropdown which includes my appDropdown directive:

            <button type="button"
                    class="btn btn-primary dropdown toggle">
                    Manage Recipe

            </button>

Add Ingredients to Shopping List

Edit Recipe

Delete Recipe

I cannot find the issue in my code. Once I changed the class from defaut to collapse, that menu does not even appear...
What am I doing wrong?
EDIT: My style.css is empty. The content of my package.json and angular.json are as follows:
{
  "name": "app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~11.2.9",
    "@angular/common": "~11.2.9",
    "@angular/compiler": "~11.2.9",
    "@angular/core": "~11.2.9",
    "@angular/forms": "~11.2.9",
    "@angular/platform-browser": "~11.2.9",
    "@angular/platform-browser-dynamic": "~11.2.9",
    "@angular/router": "~11.2.9",
    "bootstrap": "^5.0.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.0.0",
    "zone.js": "~0.11.3"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.1102.8",
    "@angular/cli": "~11.2.8",
    "@angular/compiler-cli": "~11.2.9",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.1.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.1.5"
  }
}

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "APP": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:application": {
          "strict": true
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/APP",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "APP:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "APP:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "APP:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "APP:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "APP:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "APP"
}


text:
Q: Apex Batch job to get Users information I am new to the salesforce. I am working on the Apex batch jobto get Users info which is class User and stored into the csv/text file.
I want username and user emailid stored of All users and this information to the csv/text format.
I am new to the salesforce please suggest me where should I start.
As of now I been to the developers console and starting with new class, what next steps I should follow.,
public class UserInformation implements Database.Batchable<SObject>, Schedulable {
    public void execute(SchedulableContext sc) {
        // Do initial setup

        Database.executeBatch(this, query);
    }

    public Database.QueryLocator start(Database.BatchableContext bc) {
         String query = 'SELECT Username,Email from USER';
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext bc) {
        // process
    }

    public void finish(Database.BatchableContext bc) {

    }
}

A: You can try the following code.
public class UserInformation implements Database.Batchable<SObject>, Database.Stateful {
    string[] Lines;     ///  all records

    public Database.QueryLocator start(Database.BatchableContext bc) {
        lines = new String[0];
        String query = 'SELECT Username,Email from USER';
        return Database.getQueryLocator(query);
    }

    public void execute (Database.BatchableContext bc, SObject[] scope) {
        // process
        for(Sobject record: scope) {
            String line = '';
            // header row
            if ( lines.size() == 0 ) {
                line = 'UserName, Email';
                lines.add(line);
            }
            else {
                // build your csv line here
                line +='"'+ record.get('UserName')  +'"'
                +',' +'"' + record.get('Email') + '"';
                lines.add(line);

                system.debug('Line No >>> ' + line);
            }
        }  // end of for loop
    }

    public void finish(Database.BatchableContext bc) {
        // this will send the CSV file as an attachment
        String finalResults = String.join(lines, '\n');
        lines = null; // Free temp memory to avoid heap errors

        //Create a new File Attachment, Message (email) object, attach the distinct
        //list of Record Type names and send via email
        Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
        blob csvBlob = Blob.valueOf(finalResults );
        string csvname= 'filename.csv';
        csvAttc.setFileName(csvname);
        csvAttc.setBody(csvBlob);
        Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
        String[] toAddresses = new string[] {'[youremail@yourdomain.com]'};
        String subject ='abc';
        email.setSubject(subject);
        email.setToAddresses( toAddresses );
        email.setPlainTextBody('RecordType CSV');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}

Reference:

*

*http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_batch_interface.htm
P.S
Why do you want to have execute(SchedulableContext sc)? It is used for scheduling. You might not need this. In case you do, I suggest you read this.

To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface Schedulable.


text:
Q: Difference between Pig and Hadoop What's the difference between Pig and Hadoop?
Does Pig operate on top of Hadoop and additionally offers Pig Latin to be able to fully exploit Hadoop's technology?

A: Hadoop consists of 2 components HDFS and MapReduce.

*

*HDFS is a distributed file system for storing large chunks of data, which is highly scalable & fault-tolerent.

*MapReduce on the other hand is the processing engine that can process data stored in HDFS. MR tries to bring compute to where the data is located (data-locality).

For designing algorithms to process/analyze the data stored in HDFS, MapReduce provides the following API's:

*

*JAVA API - allows the user to write MapReduce applications, generally in 2 phases Mapper & Reducer

*Streaming API - allows the user to write map & reduce in dynamic programming languages like Python/Perl/Ruby/Shell/...

*Pipes - allows the user to write map & reduce in C++

Pig & Hive on the other hand are the frameworks that sits on top of MapReduce and can convert the code written in PigLatin (data-flow language) or HiveQL (SQL like syntax) respectively to set of MapReduce jobs which saves a lot of programming time.


text:
Q: Magento 1.9 add custom column to associated products grid We have an existing customization that appears to have broken when we upgraded from 1.7 to 1.9 community.
The customization adds a column to the associated products grid.
The customization is a local override of
app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Group.php
This was done before I started on the project
$this->addColumn('breakdown_part_no', array(
'header'    => Mage::helper('catalog')->__('Part No'),
'name'      => 'breakdown_part_no',
'type'      => 'varchar',
'index'     => 'breakdown_part_no',
'width'     => '120px',
'editable'  => true,
 ));

This was added to _prepareColumns()
Another customization was added to method getSelectedGroupedProducts()
public function getSelectedGroupedProducts()
{
    $associatedProducts = Mage::registry('current_product')->getTypeInstance(true)
    ->getAssociatedProducts(Mage::registry('current_product'));
    $products = array();
    foreach ($associatedProducts as $product) {
        $products[$product->getId()] = array(
            'qty'       => $product->getQty(),
            'position'  => $product->getPosition(),
            'breakdown_part_no' => $product->getBreakdownPartNo(),
        );
}
    return $products;
}

The behavior is that the column appears in the admin and can be edited, however when saved, it does not save any value.
If I modify the getSelectedGroupedProducts part and set a hard coded value, it displays still no value (blank field), but interestingly if I click save with no value, it saves the value that was hard coded. If I enter any value in the field, it saves as a blank. This is really strange behavior that makes no sense to me.
If I change one of the other fields, such as position to be a hard coded value, it appears instantly and works as expected. Please let me know the proper way for this to work.

A: There are several posts on various forums about how to do the above and the modification mentioned is true, but what all of the other posts left out was the adminhtml layout input. When a user edits product data in Magento Admin (Associated Products), the data is serialized and sent to the controller save action. I noticed that the fields were not present when a value was entered. This is because the value wasn't in the layout so it was being stripped off of the request before it was posted to the controller.
Add input field in adminhtml/default/default/layout/catalog.xml
adminhtml_catalog_product_supergroup
addColumnInputName


text:
Q: Single word request and/or idiom—worse news What is a word/idiom for worse news on top of bad news?
Like when someone tells you bad news (a doctor) then tells you even worse news?
Here is an example (I'm sorry it is so long!  I don't know if this is okay to post here, but this is the piece I looking for the word/idiom for):
"Your daughter's symptoms of vomiting and headaches were cause for concern.  The E.R. doctors gave her fluids and ran an MRI, then called me in." Dr. Ulestig sits across the small table from me, his serious eyes searching my face for a sign that I am following his words.  I look down at the styrofoam cup I clutch in my hands.  The coffee in the hospital brought to mind the cheap motor oil I put in my college car.  During that time I didn't have money to splurge on expensive things that were unnecessary, considering my car was a piece of sh*! back then.
"Karen?"
"Hmmm?" I look up to see the worried face staring at me.
"Did you hear me?  I was telling you the results of the MRI.  It showed a small mass within her thalamus."  He pauses, waiting for a response. "In her brain."
"Brain?" My own brain seems to be repeating the sequence 'does not compute, does not compute'.
"A tumor."  He simplifies. At that word a strangled sob breaks out of my betrayer of a mouth. "It is fairly small for this type of tumor.  The next step is a biopsy.  We need to see if it is malignant or benign.  And that will tell us how aggressive it is."
"Cancer?  How?  Katie is barely 6."
"Unfortunately, this type of tumor is specific to children and young adults."
"And if it is the bad kind?  What does that mean?  How will you fix her?" I demand.  A part of me knows it isn't fair to put the responsibility of Katie's life on this kind, gentle doctor who I just met, but I need something to focus my anger and blame on.  Dr. Ulestig's eyes soften and he tilts his head.
"We don't know yet if it even is malignant.  It could be benign.  But I will give it to you straight.  It won't be good if it turns out to be malignant.  This type of tumor is called Thalamic Glioma.  There are several Grades.  The one we really don't want is Grade III.  That is malignant, and nasty.  I will not lie to you.  If she has a Grade III tumor then we need it to be a juvenile pilocytic astrocytoma.  If it isn't then the prognosis isn't good.  Karen?  Are you with me?" He reaches out to touch my wrist.  I look down at his hand.  My cup in being crushes from my shaking hands and my lungs can't find oxygen.
"What do you think it is?  Cant you tell anything?"
"I don't like to guess before I have all the information, Karen.  If I tell a patient that their test looks fine but the next one shows they have a fatal cancer then what would happen?  Or the opposite?"
"Please.  I need to know.  It is worse not knowing." I beg him.
He sighs, rubbing the back of his neck.  I didn't notice before, but he is very young to be a doctor.  He can't be more than 24 years old.  How can this kid save my own child's life?
"On the MRI, we can tell the from the way the tumor is growing, if it is malignant then it would most likely not be a JPA.  The tumor would be inoperable an incurable." The pain in his eyes threatens to break free and flood out, but I suspect for my sake he keeps it in.
"She is going to die?  No.  No!" The few people spread around the cafeteria turn to stare, but I don't care.  Not only am I told that my baby girl has a tumor, but it is most likely one of the only tumors that attacks only children and cannot be removed or helped with medicine.  I press the heels of palms over my eyes.  What I wouldn't give to turn back time to when he told me she had a tumor.  Then I thought I would break at the bad news.  Now I know that I will shatter at the even worse news.

A: Probably "Double Whammy" is the phrase you are looking for.
Definition of double whammy (as per Merriam Webster Dictionary)
"A situation that is bad in two different ways"
(or)
"A situation in which two bad conditions exist at the same time or two bad things happen one after the other"
The latter part of the second definition seems to suit this context

A: Figuratively, the person giving the bad news is probably rubbing salt in her wounds (first bad news is the wound and the second one is the salt) or twisting the knife (the second bad news is the twisting).
Wikitionary:

Verb
rub salt into someone's wounds
(idiomatic) To make a painful situation even worse (even with the best
  of intentions).
Verb
twist the knife
(idiomatic) To deliberately do or say something to worsen a
  difficult situation or increase a person's distress, irritation, or
  anger.

A: Now I know that I will shatter at...

*

*news worse still

*the final nail in the coffin

*the fell stroke

*the last straw


text:
Q: Multiple inheritance through interface Lets assume i have 2 interfaces
interface A {

    public static final int CONSTANT1 = 6;

}

interface B {

    public static final int CONSTANT1 = 7;
}

class MYclass implements A, B {

    public static void main(String[] args) {

        System.out.println(CONSTANT1);//<- ??

    }
}

Which constant will get printed or is it compilation error?

A: Just as a reference, however, the code:
interface A
{
    int CONSTANT1 = 6;
}

interface B
{
    int CONSTANT1 = 7;
}

public class Test implements A, B
{
    public static void main(String[] args)
    {
        System.out.println(CONSTANT1);
    }
}

prints 7.

A: my javac 7 fail on adchilds' example:

error: reference to CONSTANT1 is ambiguous, both variable CONSTANT1 in A and variable CONSTANT1 in B match

JLS http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3

It is possible for a class to inherit more than one field with the same name. Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.5.6.1

If an expression name consists of a single Identifier, then there must be exactly one declaration denoting either a local variable, parameter, or field visible (§6.4.1) at the point at which the Identifier occurs. Otherwise, a compile-time error occurs.


text:
Q: How i can read tty file with timeout? I have tty device in /dev , where I send AT commands. I want to read line by line and stop reading file after timeout.

A: You can use the program stty to configure the tty device. To see the settings for terminal /dev/ttyS0, try
stty -a -F /dev/ttyS0
The default settings regarding timeout are min = 1; time = 0, which means that the reading program will read until at least one character has been read and there is no timeout. Using e.g.
stty -F /dev/ttyS0 min 0 time 10
the reading program (e.g. cat) will finish reading after one second whether anything has been read or not. The unit for the parameter time is tenths of a second; you can check out man stty for more information.

A: Compiling some info from here, you can have a script in the sorts of:
#!/bin/bash

#SPECIFYING THE SERIAL PORT
SERIAL=ttyS0

#SETTING UP AN ERROR FLAG
FLAG="GO"

#OPENING SERIAL PORT FOR READING
exec 99</dev/${SERIAL}

#READING FROM SERIAL
while ["${FLAG}" == "GO" ]
do
    #IF NO INPUT IS READ AFTER 5 SECONDS, AN ERROR FLAG IS RAISED
    read -t 5 INPUT <&99
    STATUS=$?
    if test $STATUS -ne 0;
    then
      FLAG="ERROR"
    fi
done

#CLOSING SERIAL PORT
exec 99>&-

While FLAG==GO, the script will read one line at a time from the serial port. The STATUS variable gets the return of READ command. According to the manual READ will return anything different than 0 if the specified timeout is reached; when that happens, FLAG is updated, exiting the read loop.


text:
Q: Cannot find EC2 service using nodejs aws-sdk with browserify I am using Node.js with browserify and I have setup AWS like this:
var AWS = require('aws-sdk');
AWS.config.region = 'us-west-2b';

This works fine. An object is returned when I am printing to console.
However, when I do:
var ec2 = new AWS.EC2();
console.log(ec2);

It is failing to find EC2. I get undefined is not a function.
EC2 doesn't seem to exist. All the documentations direct me in this manner.

A: Try This script, it works for me with no problems.
// ec2script.js
var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
AWS.config.update({accessKeyId: 'XXXXXXXXXXXXXXXXXXXX', secretAccessKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'});
var ec2 = new AWS.EC2();
console.log('EC2');
console.log(ec2);

just execute with
>node ec2script.js

This is the response I get.
EC2
{ config:
   { credentials:
      { expired: false,
        expireTime: null,
        accessKeyId: 'XXXXXXXXXXXXXXXXXXXX',
        sessionToken: undefined },
     credentialProvider: { providers: [Object] },
     region: 'us-east-1',
     logger: null,
     apiVersions: {},
     apiVersion: null,
     endpoint: 'ec2.us-east-1.amazonaws.com',
     httpOptions: { timeout: 120000 },
     maxRetries: undefined,
     maxRedirects: 10,
     paramValidation: true,
     sslEnabled: true,
     s3ForcePathStyle: false,
     s3BucketEndpoint: false,
     computeChecksums: true,
     convertResponseTypes: true,
     dynamoDbCrc32: true,
     systemClockOffset: 0,
     signatureVersion: 'v4' },
  isGlobalEndpoint: false,
  endpoint:
   { protocol: 'https:',
     host: 'ec2.us-east-1.amazonaws.com',
     port: 443,
     hostname: 'ec2.us-east-1.amazonaws.com',
     pathname: '/',
     path: '/',
     href: 'https://ec2.us-east-1.amazonaws.com/' } }

If this doesn't work, check that you are using the correct access key and secret key.  IF the keys are correct and you are still haveing problems check to make sure the correct policies are in place for the keys.
Hope this helps.