text:
Q: Failing to add new attribute to order I am using Magento 1.9.0.1 and right now i am developing a magento extension to add new custom attribute to the order.
I am doing everything by this guide: https://stackoverflow.com/questions/12936470/adding-a-new-attribute-to-order-in-magento You can see the guide as an answer to the question.
So let me show all the files i've created:
1: /app/code/community/VivasIndustries/Vshippingone/etc/config.xml:
<?xml version="1.0"?>
<config>
    <modules>
        <VivasIndustries_Vshippingone>
            <version>1.1</version>
        </VivasIndustries_Vshippingone>
    </modules>

    <global>
         <fieldsets>
            <sales_convert_quote>
                <my_custom_input_field_one><to_order>*</to_order></my_custom_input_field_one>
            </sales_convert_quote>

            <sales_convert_order>
                <my_custom_input_field_one><to_quote>*</to_quote></my_custom_input_field_one>
            </sales_convert_order>
        </fieldsets>
        <helpers>
            <vshippingone>
                <class>VivasIndustries_Vshippingone_Helper</class>
            </vshippingone>
        </helpers>

        <models>
            <vshippingone>
                <class>VivasIndustries_Vshippingone_Model</class>
                <resourceModel>vshippingone_mysql4</resourceModel>
            </vshippingone>
        </models>
        <resources>
            <vshippingone_setup>
                <setup>
                    <module>VivasIndustries_Vshippingone</module>
                    <class>Mage_Sales_Model_Mysql4_Setup</class>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </vshippingone_setup>
            <vshippingone_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </vshippingone_write>
            <vshippingone_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </vshippingone_read>
        </resources>

        <events>
            <adminhtml_sales_order_create_process_data_before>
                <observers>
                    <vshippingone>
                        <type>singleton</type>
                        <class>vshippingone/observer</class>
                        <method>saveCustomDataOne</method>
                    </vshippingone>
                </observers>
            </adminhtml_sales_order_create_process_data_before>
        </events>

        <blocks>
            <vshippingone>
                <class>VivasIndustries_Vshippingone_Block</class>
            </vshippingone>
        </blocks>
    </global>
</config>

2: /app/code/community/VivasIndustries/Vshippingone/Model/Observer.php:
<?PHP
class VivasIndustries_Vshippingone_Model_Observer
{
    public function saveCustomDataOne($event)
    {
        $quote = $event->getSession()->getQuote();
        $quote->setData('my_custom_input_field_one', $event->getRequestModel()->getPost('my_custom_input_field_one'));

        return $this;
    }
}

3: /app/code/community/VivasIndustries/Vshippingone/sql/vshippingone_setup/mysql4-install-1.1.php
<?php
$installer = $this;
$installer->startSetup();

$installer->addAttribute("order", "my_custom_input_field_one", array("type"=>"varchar"));
$installer->addAttribute("quote", "my_custom_input_field_one", array("type"=>"varchar"));
$installer->endSetup();

4: /app/etc/modules/VivasIndustries_Vshippingone.xml:
<?xml version="1.0"?>
<config>
  <modules>
    <VivasIndustries_Vshippingone>
      <active>true</active>
      <codePool>community</codePool>
      <version>1.1</version>
    </VivasIndustries_Vshippingone>
  </modules>
</config>

By my understanding i've added the following:
In: /app/design/frontend/base/default/template/checkout/onepage/shipping_method/available.phtml - I've added the following line so i can see the input field in the checkout page:
<input type="text" name="my_custom_input_field_one" id="my_custom_input_field_one"></input>

Then in: /app/design/adminhtml/default/default/template/sales/order/view/tab/info.phtml:
I've added the following:
<?php if($_order->getMyCustomInputFieldOne()): ?>

    <?php echo Mage::helper('sales')->__('My Custom Input Field One') ?>
    <?php echo $_order->getMyCustomInputFieldOne() ?>

<?php endif; ?>

Then i go and submit a new order. Then i go back in the admin panel to see that new order and i can not see the information shown in the admin order view page.
When i remove the if statements i simply see this text My Custom Input Field One but nothing more. I can not see the information inserted in the input field in the checkout page before submiting the order.
This are all the files i have created and edited. Nothing else was made or changed. Perhaps i am forgetting something, but i do not know what, or i have mistake somewhere.
Can you help me out fix it ?

A: For Adding custom attribute, we have to create new column for custom attribute field in sales_flat_order and sales_flat_quote
We can create it By 2 ways

*

*By custom Module Mysql setup file (file path- app/code/local/pwt/singlepagecheckout/sql/singlepagecheckout_setup/mysql4-install-1.1.php)

Here (pwt -NameSpace, singlepagecheckout-Module)
    $installer = $this;
    $installer->startSetup();
    $installer->addAttribute("order", "delivery_date", array("type"=>"varchar"));
    $installer->addAttribute("quote", "delivery_date", array("type"=>"varchar"));
    $installer->endSetup();

*If you don't have a own module, simply create a php file in the project's root folder with the below code and run this file manually
 <?php require_once('app/Mage.php');
 Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));
 $installer = new Mage_Sales_Model_Mysql4_Setup;
 $attribute  = array(
     'type'          => 'varchar',
     'backend_type'  => 'varchar',
     'frontend_input' => 'varchar',
     'is_user_defined' => true,
     'label'         => 'Delivery Date,
     'visible'       => true,
     'required'      => false,
     'user_defined'  => false,
     'searchable'    => false,
     'filterable'    => false,
     'comparable'    => false,
     'default'       => ""
 );
 $installer->addAttribute('order', 'delivery_date', $attribute);
 $installer->addAttribute('quote', 'delivery_date', $attribute);
 $installer->endSetup();

 echo "success";

Run this file on root folder
Now we have allotted a space for our custom attribute in DB (Created new column in sales_flat_order and sales_flat_quote table)
After this, we have to add this custom attribute to global scope in config.xml.
(if you have been using custom module file path is-app/code/local/pwt/singlepagecheckout/etc/config.xml
if not, app/code/core/mage/sales/etc/config.xml. But editing core file isn't good practice )
<global>
   ...
    <fieldsets>
        <sales_convert_quote>
            <delivery_date><to_order>*</to_order></delivery_date>
        </sales_convert_quote>

        <sales_convert_order>
            <delivery_date><to_quote>*</to_quote></delivery_date>
        </sales_convert_order>
    </fieldsets>
    ...
</global>

Then create an event in this same config.xml file
<global>
    ...
    <events>
        <checkout_type_onepage_save_order>
        <observers>
            <delivery_date_observer>
                <type>singleton</type>
                <class>singlepagecheckout/observer</class>
                <method>saveCustomData</method>
            </delivery_date_observer>
        </observers>
        </checkout_type_onepage_save_order>
    </events>
    ...
</global>

<class>singlepagecheckout/observer</class> –Edit as per your custom module name (in core file you can simply put sales/observer)
The above event triggers the following observer method
public function saveCustomData($observer)
{
    $event = $observer->getEvent();
    $order = $event->getOrder();
    $fieldVal = Mage::app()->getFrontController()->getRequest()->getParams();
    $order->setDeliveryDate($fieldVal['delivery_date']);
}

A: You can follow the following steps and I am sure it will work.
Step 1: Adding HTML
The following code will add a text field to the billing.phtml file.
For magento 1.6(-) the file to edit is checkout/onepage/billing.phtml and for magento 1.6(+) you need to edit file persistent/checkout/onepage/billing.phtml. Open the phtml file, find the code
<?php if ($this->canShip()): ?>

and just above the line add this

        *<?php echo $this->__('SSN') ?>

            <input type="text" name="custom[ssn]" value="<?php echo $this->htmlEscape($this->getQuote()->getSsn()) ?>" title="<?php echo $this->__('SSN') ?>" class="input-text required-entry" id="billing:ssn" />

Step2: Save the field in Quote and Order Tables
Create two tables. 'sales_quote_custom' for sales and 'sales_order_custom'for order. Open phpmyadmin and confirm if the quote and order tables are created. Next we need to write some event observers to capture quote save, and load events. So open your modules config.xml file and inside the  tag put in
<events>
    <sales_quote_save_before>
        <observers>
            <save_before>
                <type>singleton</type>
                <class>Excellence_Custom_Model_Observer</class>
                <method>saveQuoteBefore</method>
            </save_before>
        </observers>
    </sales_quote_save_before>
    <sales_quote_save_after>
        <observers>
            <save_after>
                <type>singleton</type>
                <class>Excellence_Custom_Model_Observer</class>
                <method>saveQuoteAfter</method>
            </save_after>
        </observers>
    </sales_quote_save_after>
    <sales_quote_load_after>
        <observers>
            <load_after>
                <type>singleton</type>
                <class>Excellence_Custom_Model_Observer</class>
                <method>loadQuoteAfter</method>
            </load_after>
        </observers>
    </sales_quote_load_after>
    <sales_model_service_quote_submit_after>
        <observers>
            <sales_model_service_quote_submit_after>
                <type>singleton</type>
                <class>Excellence_Custom_Model_Observer</class>
                <method>saveOrderAfter</method>
            </sales_model_service_quote_submit_after>
        </observers>
    </sales_model_service_quote_submit_after>
    <sales_order_load_after>
        <observers>
            <sales_order_load_after>
                <type>singleton</type>
                <class>Excellence_Custom_Model_Observer</class>
                <method>loadOrderAfter</method>
            </sales_order_load_after>
        </observers>
    </sales_order_load_after>
</events>

and next we need to create our Observer classes in Model folder. So create an Observer.php in your modules Model folder.
<?php
class Excellence_Custom_Model_Observer
{

    public function saveQuoteBefore($evt)
    {
        $quote = $evt->getQuote();
        $post = Mage::app()->getFrontController()->getRequest()->getPost();
        if (isset($post['custom']['ssn'])) {
            $var = $post['custom']['ssn'];
            $quote->setSsn($var);
        }
    }

    public function saveQuoteAfter($evt)
    {
        $quote = $evt->getQuote();
        if ($quote->getSsn()) {
            $var = $quote->getSsn();
            if (!empty($var)) {
                $model = Mage::getModel('custom/custom_quote');
                $model->deteleByQuote($quote->getId(), 'ssn');
                $model->setQuoteId($quote->getId());
                $model->setKey('ssn');
                $model->setValue($var);
                $model->save();
            }
        }
    }

    public function loadQuoteAfter($evt)
    {
        $quote = $evt->getQuote();
        $model = Mage::getModel('custom/custom_quote');
        $data = $model->getByQuote($quote->getId());
        foreach ($data as $key => $value) {
            $quote->setData($key, $value);
        }
    }

    public function saveOrderAfter($evt)
    {
        $order = $evt->getOrder();
        $quote = $evt->getQuote();
        if ($quote->getSsn()) {
            $var = $quote->getSsn();
            if (!empty($var)) {
                $model = Mage::getModel('custom/custom_order');
                $model->deleteByOrder($order->getId(), 'ssn');
                $model->setOrderId($order->getId());
                $model->setKey('ssn');
                $model->setValue($var);
                $order->setSsn($var);
                $model->save();
            }
        }
    }

    public function loadOrderAfter($evt)
    {
        $order = $evt->getOrder();
        $model = Mage::getModel('custom/custom_order');
        $data = $model->getByOrder($order->getId());
        foreach ($data as $key => $value) {
            $order->setData($key, $value);
        }
    }

}

Step3: Display Our Field in My Account -> View Order
After the order is placed by the customer, our custom fields needs to be visible in My Account. So to do this in our module fronted layout file, in my case its custom.xml.
<?xml version="1.0"?>
<layout version="0.1.0">
    <sales_order_view>
        <reference name="my.account.wrapper">
            <block type="custom/custom_order" name="custom.order" template="custom/order.phtml" after='sales.order.info' />
        </reference>
    </sales_order_view>
</layout>

This layout file is simple and understandable. Basically, we are taking reference of my.account.wrapper block and adding a child block to it. Our block type is custom/order_view and template file is custom/order.phtml.
So we need to create our block class
<?php

class Excellence_Custom_Block_Custom_Order extends Mage_Core_Block_Template
{

    public function getCustomVars()
    {
        $model = Mage::getModel('custom/custom_order');
        return $model->getByOrder($this->getOrder()->getId());
    }

    public function getOrder()
    {
        return Mage::registry('current_order');
    }

}

and our order.phtml file

<?php echo $this->__('Custom Fields') ?>

                <?php
                $custom = $this->getCustomVars();
                foreach ($custom as $key => $value) {
                    ?>
                    <?php echo $this->__($key); ?> : <?php echo $value; ?>

                <?php } ?>

Step4: Admin Order View Page
Next we need to show our custom field in Admin -> Order -> View Order page. To do this, in our adminhtml layout file, in my case custom.xml we will put in this code.
<?xml version="1.0"?>
<layout version="0.1.0">
    <adminhtml_sales_order_view>
        <reference name="order_info">
            <action method='setTemplate'>
                <template>custom/sales/order/info.phtml</template>
            </action>
            <block type="adminhtml/sales_order_view_info" name="order_info2" template="sales/order/view/info.phtml"></block>
            <block type="custom/adminhtml_custom_order" name="custom.order" template='custom/order.phtml'/>
        </reference>
    </adminhtml_sales_order_view>
</layout>

So basically here we have added my block "custom.order" to the existing order_info block. So the code for block class custom/adminhtml_custom_order would be
<?php

class Excellence_Custom_Block_Adminhtml_Custom_Order extends Mage_Adminhtml_Block_Sales_Order_Abstract
{

    public function getCustomVars()
    {
        $model = Mage::getModel('custom/custom_order');
        return $model->getByOrder($this->getOrder()->getId());
    }

}

and next we need to create their phtml files
custom/order.phtml
<?php $_order = $this->getOrder() ?>

<?php echo Mage::helper('sales')->__('Custom Fields') ?>

                <?php
                $custom = $this->getCustomVars();
                foreach ($custom as $key => $value) {
                    ?>

                        <?php echo Mage::helper('sales')->__($key) ?>
                        <?php echo $value; ?>

                <?php } ?>

custom/sales/order/info.phtml
<?php echo $this->getChildHtml('order_info2');?>
<?php echo $this->getChildHtml('custom.order');?>


text:
Q: Division by long being truncated - C I'm attempting to time a function using the gettimeofday() function. I'm able to acquire the time in microseconds, but when attempting to divide it by a long to get time in seconds my value is truncated to a single integer. Does anyone have any insights as to why this is happening? I had assumed that division by a long = 1000000.0 would prevent this kind of truncation.
Timing of function:
struct timeval t1,t2;

gettimeofday(&t1, NULL);

// Computes C - C1 - using single thread
for (i=0; i < n; i++)
    for (j=0; j < p; j++)
    {
        C1[i][j]=0;
        for (k=0; k < m; k++)
            C1[i][j] += A[i][k]*B[k][j];
    }

gettimeofday(&t2, NULL);

Division applied here:
long divider = 1000000.0;
long elapsed = ((t2.tv_sec - t1.tv_sec) * 1000000.0L) + (t2.tv_usec - t1.tv_usec);
elapsed = (elapsed/divider);

printf("Time in seconds: %ld seconds\n", elapsed);

Any help is appreciated.

A: Long is an integer type meaning it won't hold decimals, you probably want to use double for divider and elapsed. More information on cplusplus.com
Note that you'll also need %lf to printf the value.
Correction: just %f as printf-format is apparently enough

A: The long type is an integer type.
The problem is that you're trying to store a result which you want to be a float (or a double) in a long.
There are two problems here:
1- Your operands are never cast into float/double (implicit cast by the compiler), so all the intermediate operation returns an int or a long.
2- Your result is a long: even if your operands are float/double, your result will be cast to long.
What you have to do: use double variables.
double divider = 1000000.0;
double elapsed = ((t2.tv_sec - t1.tv_sec) * 1000000.0) + (t2.tv_usec - t1.tv_usec);
elapsed = (elapsed/divider);

printf("Time in seconds: %5.5f seconds\n", elapsed);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to do a GitHub "merge branch"? When I have at Github a main (master) project
 https://github.com/MyUser/MyProject

and some active but non-default branch, listed in MyProject/branches, and with an URL like
 https://github.com/MyUser/MyProject/tree/MyBranchName

how to merge (with Github interface) MyBranchName to master?
NOTE: if really easy, only one command, how to do it by git command on terminal?

The result at
    https://github.com/MyUser/MyProject/compare/MyBranchName?expand=1
is "There isn't anything to compare"... No more clues, no more interface to create a "merge" or "fork" or "...".

A: This only works if the branches are compatible, but that can be said as well from the command line.
Go to the branch using the branch drop down on the repository page. once you are on the branch, click the green pull request icon beside it. It will create a pull request to move all commits from your branch into your master repository.
If the branches are compatible, you should be now able to click merge.
Make sure the merge direction is right reviewing the commit history!


text:
Q: Trouble Converting HTML to PDF I'm using Itext Sharp and trying to convert my .aspx web page into a PDF.  I'm using Web Forms and programming in Visual Basic.  The web page itself is a table that holds a lot of data.  I want to take the table from the page and make it into a pdf.  The web page requires a variable, buildingID, to be passed in to correctly display the data in the table, so I tried to use Web Client to capture the current web page, but it gives me a 500 internal server error.  How do I capture the current web page so I can pass it into the String Reader?
Here is the code I have so far:
 Dim ms As New MemoryStream()
    Dim document As New Document(PageSize.A4, 25, 25, 30, 30)
    Dim writer As PdfWriter = PdfWriter.GetInstance(document, ms)

    document.Open()
    Dim wc As New WebClient()
    Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri

    Dim htmlText = wc.DownloadString(url) <----Error is here
    Response.Write(htmlText)
    Dim strreader As New StringReader(htmlText)

    Dim htmlarraylist As List(Of IElement) = HTMLWorker.ParseToList(strreader, Nothing)

    For i = 0 To htmlarraylist.Count
        document.Add(htmlarraylist(i))
    Next

    document.Close()


text:
Q: Debugging PhoneGap app on VS2010 I am running a sample app written using PhoneGap and jquery on VS2010 and Windows 7 Emulator.
How do I step in the javascript code to debug?
I can't seem to find any thread on debugging or stepping in the codes.

A: good info with few options on debugging PhoneGap applications in general Debugging PhoneGap Apps

A: When you run your mobile code on a browser like IE there is options to place break points in the debug mode.


text:
Q: Swift NSXElement addChild unable to add sub child to child I am in the process of learning Swift and want to create a xml file based on user input.  I am able to create the document root and one child level but not sub child.  I don't know what I am missing. And How do I "pretty print" to my xml?
Example of desired xml file output:
<find_sites>
  <name>Many Sites</name>
       <sites>8</sites>
         <site_info>
              <site_name>First Site</site_name>
              <site_description>Description of first site</site_description>
         </site_info>
</find_sites>

My Swift Code in playground:
let root = NSXMLElement(name: "find_sites")
let xmlFile = NSXMLDocument (rootElement: root)
root.addChild(NSXMLElement(name: "name", stringValue: "Many Sites"))
root.addChild(NSXMLElement(name: "sites", stringValue: "8"))
let site_info = NSXMLElement(name: "site_info")
root.addChild(NSXMLElement(name: "site_info"))
site_info.addChild(NSXMLElement(name: "site_name", stringValue: "First Site"))
site_info.addChild(NSXMLElement(name: "site_description", stringValue: "Description"))
println(" \(xmlFile.XMLString)")

Results:  <find_sites><name>Many Sites</name><sites>8</sites><site_info></site_info></find_sites>

My child elements of 'site_info' are ignored.

A: You're adding a new NSXMLElement instance as a child of root rather than site_info. Change line 6 to this:
root.addChild(site_info)


text:
Q: How can I check if a YouTube channel name exists? I own a website that generates YouTube names, how can I show the user if a channel is already taken or not?

A: You can use channel->list request for this.
As mentioned in documents, all you need to do is do
channels.list(part="id", forUsername="username")

If this return an empty list, there is no channel with that username.
Also here are some samples to get you started.

A: You can try
$api = 'https://gdata.youtube.com/feeds/api/users/';
$user = "user";
$headers = get_headers($api . $user, true);
if ($headers[0] == "HTTP/1.0 200 OK") {
    // its ok
}


text:
Q: Is there a setting change we need to make for iBatis to MyBatis conversion tool? Has anyone used the iBatis to MyBatis conversion tool like in https://code.google.com/p/mybatis/wiki/DocUpgrade3? Did you need to make a setting change for the tool to work?
I've tried 2-3 versions of this tool, but I keep getting this error:
     [xslt] Loading stylesheet C:\<some-path>\migrate.xslt
     [xslt] : Error! Connection timed out: connect
     [xslt] : Error! com.sun.org.apache.xml.internal.utils.WrappedRuntimeExcepti
on: Connection timed out: connect
     [xslt] Failed to process null

BUILD FAILED
C:\<some-path>\build.xml:2
4: javax.xml.transform.TransformerException: javax.xml.transform.TransformerExce
ption: com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: Connection
 timed out: connect

Also, the way I tried to run it is as follows:
In a command prompt, I changed to the directory where the zip file was extracted. Then I put in one of the SQL map files into the Source folder. Then I went back to the command prompt, and ran the command "ant". I tried this command with 2-3 options too, but none of them worked. All of them gave the same error. It seems like some kind of a proxy setting kind of issue, from what I've found so far. But I don't exactly know what the error is and what the solution is, beyond this. Any idea how to resolve this?

A: I found a solution to this:

*

*At first, I tried to run the Ant task by setting this property via the command prompt:
set ANT_OPTS="-Dhttp.proxyHost=proxy -Dhttp.proxyPort=8080"

And then ran in the same session: ant
But this continued to give me the same error.

*So, I took out the <!DOCTYPE..> line from the source file, and then did the above steps. It worked like magic!


text:
Q: How to get Access Token for Client Based Application for Zoho API? Does this mean Zoho API documentations are wrong?
I'm following the "client based applications" as my app is a ReactJS based app. Unfortuantely im getting a fetch failed type of error when trying to request an authentication token using response_type = token.
Very frustrating indeed.
What is the proper way to get an auth token for ReactJs apps?

A: You can get it by chrome(or firefox)
Get format (make single line)
https://accounts.zoho.com/oauth/v2/auth?
client_id={your client id}&
response_type=token&
scope=AaaServer.profile.Read&
redirect_uri={your app redirect URI}

This is steps

*

*Get client_id and redirect_uri from my Zoho Setting

https://api-console.zoho.com/

*Make single line string with upper format
put that string and enter from Chrome
The client id and redirect URI should be match your App settings.

Click the Accept button with checked Grant access checkbox

Will get  the access token at address editor in Chrome

*Get new access token with this format

http://localhost:3000/#&
access_token={get-new-access-token}&
expires_in=3600&
location=us&
api_domain=https%3A%2F%2Fwww.zohoapis.com&
granted_for_session=true

You can make your React app for getting access token with this steps.


text:
Q: Bootstrap drop down Navigation Menu in WordPress I am trying to build a Wordpress theme with boostrap.almost every part is complete but the nav menu is giving me some trouble for days. I would like the dropdown to work like boostraps dropdown, but I do not know how to do this.
So I need:
To add the class "dropdown", if a menu-item has child-items.
dropdown-toggle
sticky-top
also i need necessary bootstrap web srcs or download links and local src like this:  get_template_directory_uri() . '/js/scriptname.js'
Hope someone can help!
when i try https://github.com/wp-bootstrap/wp-bootstrap-navwalker , the page looks like:

A: You will want to extend the Walker_Nav_Menu class. This allows you to "walk" through the various states of a navigation menu. One of the first google searches I did for the term Walker_Nav_Menu led me to this Github repo with a class already built. wp-bootstrap-navwalker.


text:
Q: Why do I need to use [ and ] instead of ( and ) in regular expression? I want to use the re package in Python to search for some text in a big data set. Maybe I got something wrong, but if I'm using
(\w+,\s?)+

I would get a match for something like:
This, is, a, test,

Why isn't this the case in Python?
The following example works only with [] instead of ()
str = 'St. aureus°, unimportant_stuff, Strep. haemol.°'

will_fail = re.compile(r'(\w+\.?\s?)+°')
success = re.compile(r'[\w+\.?\s?]+°')

print(will_fail.findall(str))
print(success.findall(str))

This will result in the output:
['aureus', 'haemol.']             // THIS IS FAIL
['St. aureus°', 'Strep haemol.°'] // THIS IS OK

What am I doing wrong here?


text:
Q: PHP packet send in perl I have this code to send a packet in PHP, and I wanted to know how to do it in perl, I have tried sending via hex data, but it is not working. Here is the PHP code:
$sIPAddr = "37.221.175.211";
$iPort = 7777;
$sPacket = "";
$aIPAddr = explode('.', $sIPAddr);

$sPacket .= "SAMP";

$sPacket .= chr($aIPAddr[0]);
$sPacket .= chr($aIPAddr[1]);
$sPacket .= chr($aIPAddr[2]);
$sPacket .= chr($aIPAddr[3]);

$sPacket .= chr($iPort & 0xFF);
$sPacket .= chr($iPort >> 8 & 0xFF);

$sPacket .= 'c';

$rSocket = fsockopen('udp://'.$sIPAddr, $iPort, $iError, $sError, 2);
fwrite($rSocket, $sPacket);

fclose($rSocket);

How would I go about doing this in Perl? I want to use a raw socket as well to send it.
This is what I tried, but the server is not replying to it, which makes me think that the data is corrupted somewhere:
$packet = Net::RawIP->new({
                        ip => {
                              saddr => $saddr,
                              daddr => $dest,
                              },

                        udp => {
                              source => $rsport,
                              dest => $port,
                              data => "\x53\x41\x4d\x50\x25\xdd\xaf\xd3\x61\x1e\x63", # this is the data from the PHP file in HEX
                              },
                        });
  $packet->send;

A: Don't know about Net::RawIP, but here's the Perl variant that sends the exact same packet as your PHP code, using IO::Socket::INET module. For docs for it, see https://metacpan.org/pod/IO::Socket::INET
use strict;
use warnings;
use IO::Socket;

my $sIPAddr = '37.221.175.211';
my $iPort = 7777;
my $sPacket = 'SAMP' . join( '', map chr,
    split(/\./, $sIPAddr),
    $iPort & 0xFF,
    $iPort >> 8 & 0xFF,
) . 'c';

my $sock = IO::Socket::INET->new(
    Proto    => 'udp',
    PeerPort => $iPort,
    PeerAddr => $sIPAddr,
) or die "Could not create socket: $!\n";

$sock->send( $sPacket );


text:
Q: BizTalk SMTP send mail with attachments (no orchestration, custom send pipeline component) I hope someone can help me out with this since when I drop a JSON test file in my rcv-folder the only result is that in the BizTalk console (in 'Running instances'), the message only states 'Queued (Awaiting processing)'. I am not sure where my issue is in the code.
I am supposed to receive a JSON which will contain some info and possibly multiple attachments (in Base64 format) and then send the mail out (with attachments in correct format, i.e. PDF, txt, xls) to a certain email-address. One of the requirements is to not use an orchestration. But I am stuck and have no idea what I am doing anymore. What makes this question different from others is that I have no orchestration in my solution. Everything will be processed in a custom send pipeline  component.
The sendpipeline (in encode stage) does contain my custom component and also the MIME/SMIME encoder. I am using the SMTP-adapter.
I have created the custom pipeline component with a wizard and my initial plan was in the form below:

*

*Receive the file (in JSON-format. It will be transformed into XML for further processing). This will all be taken care of in my rcv-pipeline and this step already works for me.

*Pick out all the necessary variables from XML needed to send in the e-mail. These variables are the ones I want to show in the E-mail text. Not sure how to explain it better.

*Pick out all the attachments in base64, loop through them, convert to 'regular files' and then attach them to the mail (with correct filenames, extension etc.)

The XML looks like below:

ArchiveobjectsListErrands
  - ArchiveobjectErrand
      * UUID (Here are the variables I need to show in the E-mail. The plain text, so to say)
    - ArchiveobjectListPaper
      - Attachments
        * Name
        * Extension
        * Size
        * Base64String (Base64 string which will be needed to be fetched (in GetAttachments) and then processed in (ProcessAttachments))

The code I have is below:
public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pContext, Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
        {
            // 1) Read file with XPathNavigator (https://learn.microsoft.com/en-us/dotnet/standard/data/xml/extract-xml-data-using-xpathnavigator)
            XPathNavigator nav = ReadXmlFromMsgBox(pInMsg);

            var outMsg = pContext.GetMessageFactory().CreateMessage();
            outMsg.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);

            // 2) Pick out the necessary vars that the registrator requires
            GetRegistratorProperties(nav, pContext, outMsg);

            // 3) Read attachments
            var attachments = GetAttachments(pInMsg, nav);

            // 4) Processa attachments
            ProcessAttachments(pContext, outMsg, attachments);

            // 5) Send message along for further processing in the send pipeline
            return outMsg;
        }

        private void GetRegistratorProperties(XPathNavigator _nav, IPipelineContext _pContext, IBaseMessage _msg)
        {
            var bodyPart = _pContext.GetMessageFactory().CreateMessagePart();

            bodyPart.ContentType = "text/application";

            bodyPart.PartProperties.Write("EmailBodyText", "http://schemas.microsoft.com/BizTalk/2003/smtp-properties", "EmailBodyText.");
            bodyPart.PartProperties.Write("Subject", "http://schemas.microsoft.com/BizTalk/2003/smtp-properties", "Registratorsubject - Create errand");

            _msg.AddPart("Body", bodyPart, true); // True for body but false for attachments

        }

        private void ProcessAttachments(IPipelineContext _pContext, IBaseMessage _msg, IList<Attachment> _attachments)
        {

            var msgPart = _pContext.GetMessageFactory().CreateMessagePart();
            //outMsg.Context = PipelineUtil.CloneMessageContext(_msg.Context);

            int i = 0;
            foreach (var item in _attachments)
            {
                msgPart.PartProperties.Write("FileName", "http://schemas.microsoft.com/BizTalk/2003/mime-properties", item.filnamn+item.extension);
                msgPart.PartProperties.Write("ContentDescription", "http://schemas.microsoft.com/BizTalk/2003/mime-properties", item.contentType);
                msgPart.Data = new MemoryStream(BytesFromBase64String(item.base64));
                //bodyPart.Charset = "utf-8";
                msgPart.ContentType = item.contentType;

                //_pInMsg.AddPart("Attachment part " + i.ToString(), bodyPart, false);
                _msg.AddPart("Attachment part " + i.ToString(), msgPart, false);
                i++;
            }
        }

        private IList<Attachment> GetAttachments(IBaseMessage pInMsg, XPathNavigator _nav)
        {
            XPathNodeIterator iterator =  _nav.Select("Path to attachments in xml");
            IList<Attachment> myList = new List<Attachment>();

            while (iterator.MoveNext())
            {
                XPathNavigator node = iterator.Current;

                Attachment atttachments = new Attachment();

                atttachments.filenamne = node.SelectSingleNode("Name").Value;
                atttachments.extension = node.SelectSingleNode("Extension").Value;
                atttachments.contentType = node.SelectSingleNode("Mimetype").Value;
                atttachments.base64 = node.SelectSingleNode("Base64String").Value;

                myList.Add(atttachments);
            }

            return myList;
        }

        private XPathNavigator ReadXmlFromMsgBox(IBaseMessage pInMsg)
        {
            // Using XPathNavigator to avoid creating a XMLDoc in memory
            Stream originalMessage = pInMsg.BodyPart.GetOriginalDataStream();

            XPathNavigator _navigator = new XPathDocument(originalMessage).CreateNavigator();
            return _navigator;
        }

        [Serializable]
        private class FileStreamFactory : IStreamFactory
        {
            byte[] _data;

            public FileStreamFactory(byte[] data)
            {
                _data = data;
            }

            public Stream CreateStream()
            {
                return new MemoryStream(_data);
            }
        }

        private static byte[] BytesFromBase64String(string msg)
        {
            return Convert.FromBase64String(msg);
        }
        #endregion
        }

I can show some example file of the XML if deemed necessary. I avoided it due to brevity and also since it is quite large.
I would greatly appreciate if anyone could help out with how the code is supposed to look to achieve what is needed, a mail with some text and attachments named correctly regarding filename and extension.

A: Body text and Attachments are just different segments in a MIME encoded email, usually a plain text one is the first one.
If it has a status of 'Queued (Awaiting processing)', then it sounds like either

*

*the host instance that is expecting to process it is not in a running state. Fix: Start the host instance.

*the send port is not in a Started sate. Fix: set the send port to Started

*or the send port has a service window set on it.  Fix: disable the service window.


text:
Q: Trying to learn / understand Ruby setter and getter methods I'm just learning to program and have decided to try Ruby.  I'm sure this is a stupid question, but the instructor is talking about setter and getter methods, and I'm confused. Here is the example:
class Human
  def noise=(noise)
    @noise = noise
  end

  def noise
    @noise
  end
end

From this, the class is instantiated, and I can puts this out:
man = Human.new
man.noise=("Howdie!")
puts man.noise

This results in Howdie!
Now what confuses me is that the instructor is saying without the getter method (the 2nd of the two methods), there is no way to interact with the instance variable @noise.
But when I remove the getter method, I'm able to still access @noise, see example:
class Human
  def noise=(noise)
    @noise = noise
  end
end

man = Human.new
puts man.noise=("Howdie!")

This works the same as when the getter method it used.
So now I'm confused. Why is the getter needed? What does the instructor mean by not being able to access the instance variable without it? Is it possible he's using an older version of Ruby?
Thanks in advance for your help.

A: Surely they both return a value, but their behavior are different.
Let's say there is already a member @a   .
with getter, one obtains the current value of @a, without modifying it.
with setter, one modifies @a, and get its new value as return value.
when thinking about behavior of setter, note:

*

*the old value of @a can not be obtained with setter, and got overwritten.

*what returned by setter, is actually already known before invoking setter.

A: You can interact with that instance variable from other methods belonging to that instance, even if there is no getter:
def noise=(noise)
  @noise = noise
end

def last_noise
  @noise
end

There doesn't need to be a getter defined with the same name as the method; the two are not linked at all. The getter is needed to "get" the value of the instance variable, but only in a short syntax.
What's happening in your example is that you're initializing a new object (Human.new), and then using a method (noise=, yes the method name contains the = symbol) that just-so-happens to define an instance variable (that is, a variable just for that instance), and then finally retrieving that instance variable with another method call.
You can actually use instance_variable_get to get the instance variable without defining any getter at all:
man = Human.new
man.noise = "Howdie"
man.instance_variable_get("@noise")

This will return "Howdie", even though there is no getter defined.
And no, I don't think he's using an older version of Ruby.

A: The line of code
puts man.noise=("Howdie!")

does NOT use the getter method, so the getter method does not need to be defined for it to work.  That line just uses the setter method.  The return value of the setter method is automatically equal to whatever is on the right-hand side of the equal sign, so "Howdie!" gets passed to puts.
The line of code
puts man.noise

DOES use the getter method, and it would not work if you remove the getter method.

A: May be the attention for getters and setters is because some other languages allow you to access class variables directly. Python:
class k:
    i = 100

print k.i # 100
k.i = 200
print k.i # 200

In contrast, Ruby keeps all of its variables completely private to the class and only exposes them through accessor methods.
In your example, if you remove the getter, you can indeed interact with the variable (that is: change it) trough the setter, but you can't get it back (in a regular way) when you need it.


text:
Q: Multitenant app with single database I'm developing a multitenant application using Laravel. I've read different blogs, posts, sites for this and I decided to do it with a single database.
So, I know that I only need to filter every query with the tenant_id and that's it! But if I do it from every query, probably someday there'll be an error and I don't want to cause any information security issue for my tenants.
I read, probably, an old article for it, culttt.com/2014/03/31/multi-tenancy-laravel-4, and I found many concepts that I still don't understand because I'm new to Laravel.
Is this approach still the best for do it? Or has Laravel now its own solution to do it?
I like something similar to this: stackoverflow.com/questions/33219951/php-pdo-add-filter-to-all-queries but from Eloquent. How can I do this?
Thanks.

A: If I were you I would not go this way. I would create separate database for each client/each app - it's much safer solution and in addition in case you will need create Database backups or restore some client data it will be much simpler to do that than dealing with huge database when you have all your clients.


text:
Q: Rename all variables in C++ project by naming style How I can rename all variables and functions to suggested with name style in all C++ project?
I setup name style in ReSharper. I know that in C# project I could apply naming style for all project. But in C++ I don't see this setting:

A: Bulk rename is not supported yet in ReSharper C++.


text:
Q: cannot resolve method getdownloadurl in tasksnapshot private void storeFireStore(final UploadTask.TaskSnapshot taskSnapshot, final String name, final String usernameToCompare) {

    final Uri download_uri;

    if (taskSnapshot != null) {
        download_uri = taskSnapshot.getDownloadUrl();
    } else {
        download_uri = mainImageUri;
    }


text:
Q: timer not work when AlertDialog is showing i have activity that show AlertDialog when special event rises but i want a timer running
when this AlertDialog is showing to do something but timer not work.
AlertDialog and timer Within an activity
this is my AlertDialog code :
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("...");
alertDialog.setMessage("...");
alertDialog.show();

and before this AlertDialog i create and run timer like this :
final Handler handler = new Handler();
        timer = new Timer(false);
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if(light==0) light =1;
                        else light = 0;
                        WindowManager.LayoutParams lp = ac.getWindow().getAttributes();
                        lp.screenBrightness = light;
                        ac.getWindow().setAttributes(lp);
                    }
                });
            }
        };

this timer for change light of screen.
what is my problem?
is it possible to run timer with AlertDialog concurrent؟


text:
Q: if statment on installed script in sbin failing I have a simple block of code that seems to fail and I'm not 100% sure why,
if ! -h /usr/sbin/gitploy; then
    curl  https://raw.githubusercontent.com/jeremyBass/gitploy/master/gitploy | sudo sh -s -- install
    [ -h /usr/sbin/gitploy ] || echoerr "gitploy failed install"
else
    gitploy gitploy_update
fi

fails but if I do
[ -h /usr/sbin/gitploy ] || echoerr "gitploy failed install"

by itself it works fine.  I'm sure there is a simple reason why.  Any ideas?

A: You do nested if , So you need re-create your block such as:
if [ ! -h /usr/sbin/gitploy ]; then
    curl  https://raw.githubusercontent.com/jeremyBass/gitploy/master/gitploy | sudo sh -s -- install
    [ -h /usr/sbin/gitploy ] || echoerr "gitploy failed install"
else
    gitploy gitploy_update
fi


text:
Q: Show 3 different values of the same column and same table in the same row in results I use SQL Server 2014 for my project. I have three tables:
Table A:
Column: id
Table B:
Column: id, id_of_Table_A
Table C:
Column: id, id_of_Table_B, category

The relationship between A and B is one to many
The relationship between B and C is one to many

In Table C, there are 10 category values for the category column, but I am interested only in three categories (cat1, cat2, cat3). I hope to query and produce the following results for the three categories:
id_of_Table_A, category, category, category

I have the following statement:
select a.id, c.category from Table_C c
join Table_B b on b.id = c.id_of_Table_B
join Table_A a on a.id = b.id_of_Table_A
where c.category = 'cat1' and a.id in (1, 2, 3)

But this statement only lists
id_of_Table_A, cat1

which contains only cat1 of a given id_of_Table_A. I hope to have something like:
1, cat1, cat2, cat3

if cat1, cat2, and cat3 exists in Table C for the given id 1 in Table A.
If a single statement is unable to produce the desired results, then a stored procedure is okay.
Update
In the following example results,
1, cat1, cat2, cat3

cat1, cat2, cat3 must come from three different records in Table B. Suppose we have these tables and rows:
Table A: 1,2
Table B: (1,1), (2,1), (3,1), (4,2), (5,2), (6,2)
Table c: (1,1,'cat3'), (2,2,'cat1'), (3,3,'cat2'), (4,4,'cat1'), (5,5,'cat4'), (6,6,'cat2')

Then the expected results should be:
1, cat1, cat2, cat3

Basically, the relationships of the tables form a tree. I hope to find the root  (Table A) with leaves being cat1, cat2, and cat3 on non-overlapping paths from the root.

A: You can combine all categories for id_of_b in a single xml value and then show categories in columns. Something like this.
declare @a table(id int)
declare @b table(id int,id_of_a int)
declare @c table(id int,id_of_b int,category varchar(50))
insert @a values(1),(2)
insert @b values(1,1),(2,1),(3,2)
insert @c values(1,1,'cat1'),(2,1,'cat2'),(3,1,'cat3'),(4,2,'cat4')
;with cte as(
  select a.id,
    cast((select category from @c c where c.id_of_b = b.id for xml auto,root,type) as xml) xcat
  from @a a inner join @b b on a.id = b.id_of_a
)
select id,
  t.v.value('c[1]/@category','varchar(50)') cat1,
  t.v.value('c[2]/@category','varchar(50)') cat2,
  t.v.value('c[3]/@category','varchar(50)') cat3
from cte
cross apply xcat.nodes('root') t(v)

Updated answer for updated question
declare @a table(id int)
declare @b table(id int,id_of_a int)
declare @c table(id int,id_of_b int,category varchar(50))
insert @a values(1),(2)
insert @b values (1,1), (2,1), (3,1), (4,2), (5,2), (6,2)
insert @c values (1,1,'cat3'), (2,2,'cat1'), (3,3,'cat2'), (4,4,'cat1'), (5,5,'cat4'), (6,6,'cat2')

;with cte as(
  select a.id,
    cast((select category from @c c inner join @b b on c.id_of_b = b.id
       where b.id_of_a=a.id
       for xml auto,root,type) as xml) xcat
  from @a a
)
select id,
  t.v.value('c[1]/@category','varchar(50)') cat1,
  t.v.value('c[2]/@category','varchar(50)') cat2,
  t.v.value('c[3]/@category','varchar(50)') cat3
from cte
cross apply xcat.nodes('root') t(v)


text:
Q: Is there a way to inject a string in a linux application, so i can later read it somehow? I am writing code that looks up the active window with the help of xprop
So it's easy when the application is launched from the command line with a -- command
i can later read that window with _WM_COMMAND(STRING)... But the problem is.. not every software stores the command string..
I need to pass a string to the starting application and somehow read that later.
Thank you!


text:
Q: My Model is not called when page loads when new page loades I am trying to fetch data in my route but I am not getting any response from my model method. rest of all other methods called. what is wrong here?
here is my code :
import Ember from 'ember';

export default Ember.Route.extend({
    model(params){ //not calling
        console.log('got the model', params );
        return this.store.peekRecord('card-list', params.id );
    },

    setupController(controller,model) {//called
        console.log("super")
        this._super(...arguments);
        console.log("model is", controller,"\n", model );
    },

    init(){//called
        console.log("init calledx");
    }

});

UPDATE
Router.map(function() {
  this.route('review');
  this.route('confirmation');

  this.route('cs2i', function() {
    this.route('balance', function() {
      this.route('balanceDetails');
      this.route('balanceEdit', { path: '/balanceEdit/:id' });
      this.route('balanceReview', { path: '/balanceReview/:id' });
    });

    this.route('purchase', function() {
      this.route('purchaseDetails');
      this.route('purchaseEdit');
      this.route('purchaseReview');
    });
  });


text:
Q: What does it mean "orderby: other" in Dropbox SDK I'm using dropbox api to search files in a connected account. I need to implement feature to sort search result by selected criteria. For example, I need sort files by last modifying time or by title (in alphabetical order). In dropbox documentation I found that I can filter result by date. But It's unclear to me if I can filter results by title.
There is an option called "other". I could not find any information about what does the "other" option mean.
Here is the link for dropbox api I found: https://dropbox.github.io/dropbox-sdk-js/global.html#FilesSearchOrderBy
So here are my questions.

*

*What does "other" option mean?

*Can I sort files by last modified time using ASC and DESC ordering?

I'm using dropbox 5.2.1 so far.

A: The other tag indicates that the FilesSearchOrderBy object is an "open union", meaning more values may be added in the future. The other option doesn't indicate any more actual functional that can currently be accessed.
So, the only actual options are currently relevance and last_modified_time. This doesn't offer ascending/descending options. If you want to order by modified time, you should use last_modified_time, and reverse the results if they're not in the direction you want.


text:
Q: xmlHTTPrequest won't open ("GET" , url, true); I'm miffed! PHP I've been trying to get a url to open but I'm miffed as to why this hasn't worked. The code is listed and explained below. Any help will be deeply appreciated.
The object:
function getXMLHTTPRequest() {
   var req =  false;
   try {
      /* for Firefox */
      req = new XMLHttpRequest();
   } catch (err) {
      try {
         /* for some versions of IE */
         req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (err) {
         try {
            /* for some other versions of IE */
            req = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (err) {
            req = false;
         }
     }
   }

   return req;
}

The object is called like this:
<script type="text/javascript">
var myDelete = new getXMLHTTPRequest();
</script>

Now here's what I want to do:
function removeArticle(id) {

    if (myDelete) {

        try {
            var deletUrl = "delete.php";
            var query = deletUrl + "?theid=" + id;
            myDelete.open("GET", query, true);
            myDelete.onreadystatechange = removeArticleResponse;
            myDelete.send(null);
        } catch (e) {
            alert ("Unable to connect to the server:\n" + e.toString());
        }
    } else {
        alert ("Bad! Very BAD!");
    }
}

When I do this:
        if (myDelete.open("GET", query, true)) {
        myDelete.onreadystatechange = removeArticleResponse;
        myDelete.send(null);
        } else {
            alert ("No road!");
        }

The alert("No road!"); shows me that the code doesn't execute passed this point:
if (myDelete.open("GET", query, true)) {

This means that the if (myDelete) { works. The code passes this stage and for some reason stops here: myDelete.open("GET", query, true); It won't open the url. I'm not sure what the problem is.
Edit: Here's the function used to access the server response:
function removeArticleResponse () {
    if (myDelete.status == 4) {
        if (myDelete.status == 200) {
                        try {
                            response = myDelete.responseText;
                            document.getElementById('displaynewsletterarticleresult').innerHTML = response;
                        } catch(e) {
                            alert("An error occured while reading the response:" + e.toString());
                        }
        } else {
        alert ("An error occured when attempting to retrieve the data:\n" + myDelete.statusText);
        }
    }
}

A: According to this, XMLHttpRequest.open() has no return value, so your check will always fail.

A: In  your response function, do you mean to check .status == 4 instead of .readyState?

A: All xmlHTTPRequests are bound to the same origin policy. Maybe that's your issue.
You can read more about it at http://en.wikipedia.org/wiki/Same_origin_policy


text:
Q: What methods can be called on Docpad's Query tools? In Docpad's documentation it lists a series of Querying helpers. Here's the link. The following list appears at the bottom. Among these helpers are @getCollection, @getFiles, @getFilesAtPath, etc. But there is no indication anywhere that I have been able to locate about what kind of objects are returned by these helpers, and what sort of methods can be called on them, how does one retrieve data, etc? There are a few examples in the Docpad documentation, for example the beginner's guide shows how you'd loop through a collection of html pages in the section "ADDING A MENU LISTING FOR OUR PAGES". From this one can glean that the objects returned here have a method toJSON() that one can call on them. But what else? The documentation also explains that these helper functions are Query-Engine objects of some sort, but in the (Query-Engine documentation)[http://learn.bevry.me/queryengine/guide] I was unable to find any description of how to manipulate these objects. So my question is: does anyone know what the structure of these objects are and how they can be manipulated? Is there a document that I'm missing somewhere?

A: How I understand it using simple man words:
So in docpad documents are by default interpreted as yaml files (content+metadata). So your query returns object that is this yaml file that you parse to json.
Important to know is that this yaml file is not only "your" defined metadata + content but also some additional metadata defined here http://docpad.org/docs/meta-data. So this is a lot of additional data that you can access.
I assume you use ECO templating and you probably know that it is all about CoffeeScript. So toJSON() method is just one of javascript methods that you can use. I didn't try to check it but I just noticed that anything I want to solve with coffeescript is doable in ECO. So once you parse the object returned by your query to json, you can do anything and call any method you want on JSON object.
Whenever I query for docs of files, I add: <% console.log @document %> to my "for" loop. It returns in the console the whole json object. So you can easily see what objects are returned with your query and what data you can take out of them.
Hope that helps. Cheers


text:
Q: UITableView checkmark count I am using an UITableView with checkmarks and I want to set a label count which shows how many items are checkmarked in the table view. For example if the table contains 18 items with 2 checks,it shows 2/18. Can any one help me to code?

A: Assuming that this means that these cells will be selected, you could try this:
NSArray *array = [[NSArray alloc] initWithArray:tableView.indexPathsForSelectedRows];
myCount = [array count];

alternatively, you could keep a running tally of an integer and add to it or subtract from it every time a cell is selected or deselected.


text:
Q: What is the reason my function wont restart? Everything works fine but when i try to re run the function it is stuck on the alert box what did i do wrong and can anyone explain why its happening.You can look at the comment in the code to see the area im getting this probem
var userChoice = prompt("Do you choose rock, paper or scissors?");
 var computerChoice = Math.random();
    if (computerChoice < 0.34) {
            computerChoice = "rock";
        } else if(computerChoice <= 0.67) {
            computerChoice = "paper";
        } else {
            computerChoice = "scissors";
        } console.log("Computer: " + computerChoice);
        var compare = function(choice1,choice2){
            if (choice1 === choice2){
                return "The result is a tie!";

           }else if (choice1 === "rock"){
             if(choice2 === "scissors"){
                 return("rock wins");
             }else{
                return("paper wins");
             }

           }else if (choice1 === "paper"){
                if(choice2 === "rock"){
                    return("paper wins");
                }else{
                    return("scissors wins");
                }
           }else if(choice1 === "scissors"){
               if(choice2 === "rock"){
                   return("rock wins");
               }else{
                   return("scissors wins");
               }
           }else if (choice1 != "rock"&&"paper"&&"scissors"){
                    alert("not a viable input,please try again");
                    compare(userChoice,computerChoice);
    //calling the function here makes the alert box repeatedly pop up

           }

        };
        compare(userChoice,computerChoice);

A: You can set a flag and put everything in a while loop.
var finished = false;

var compare = function (choice1, choice2) {
   if (choice1 === choice2) {
       finished = true;
       return "The result is a tie!";
   } else if (choice1 === "rock") {
       if (choice2 === "scissors") {
       finished = true;
       return ("rock wins");
    } else {
       finished = true;
       return ("paper wins");
    }

} else if (choice1 === "paper") {
    if (choice2 === "rock") {
        finished = true;
        return ("paper wins");
    } else {
        finished = true;
        return ("scissors wins");
    }
} else if (choice1 === "scissors") {
    if (choice2 === "rock") {
        finished = true;
        return ("rock wins");
    } else {
        finished = true;
        return ("scissors wins");
    }
} else if (choice1 != "rock" && "paper" && "scissors") {
    alert("not a viable input,please try again");
    finished = false;
    //compare(userChoice, computerChoice); This causes recursion. Not necessary.

}

};

while (!finished) {
   var userChoice = prompt("Do you choose rock, paper or scissors?");
   var computerChoice = Math.random();

if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if (computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
}

console.log("Computer: " + computerChoice);

alert(compare(userChoice, computerChoice));
}

Take a look at this fiddle http://jsfiddle.net/7p94axhp/


text:
Q: Thickbox seems to have just stopped loading images, although iFrame still works I can't figure this one out!
Thickbox seems to have stopped loading images in it's default lightbox mode - I've made no changes and the clients just reported it.
Weird thing is the iFrame version works fine.
I'm seeing no errors, but using Tamper Data through Firefox there's no attempt to call the image either.
Example page is here: http://www.lens-wear.co.uk/details.php?AID=9&TID=0&BID=5&PID=645
If you click an image top right then they don't load, but if you click 'Add' it brings up the order wizard via Thickbox in an iFrame as expected.
I'm normally pretty good with this sort of thing, but with no error and no http traffic I can't work it out.
I guess I could just fix it by moving across to Shadowbox.
Yours,
Chris

A: Removing the rel attribute from the <a> tag did the trick for me.


text:
Q: Почему фоновая музыка не работает на сайте Всем привет, столкнулся с такой проблемой, пытаюсь включить музыку с рабочего стола на сайт, в консоли пишет вот это
такой код в html:
<audio  src="/Desktop/Chris Johnston & Craig Markva and Jamie Evans — Labradford (OST _Молодой Папа_ 1 сезон_).mp3"
  controls>
</audio>

Что я делаю не так?

A: У тебя путь прописан, неверно. Ты можешь закинуть песню к файлу index.html и указать путь
<audio  src="/Chris Johnston & Craig Markva and Jamie Evans — Labradford (OST _Молодой Папа_ 1 сезон_).mp3"
  controls>
</audio>

UPD: посмотри внимательней на путь: C:/Desktop я сомневаюсь, что у тебя на диске "C" создана папка Desktop


text:
Q: Coordinator Layout View prevents other layouts from being displayed? I have a CoordinatorLayout used for displaying an AppBarLayout. However, the issue is that my RelativeLayout and LinearLayout are hidden by my ListView. Moreover, my ListView does not show fully: rather, part of the first ListView element is cut off but I can scroll through and see the rest. Below was my attempt:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
    xmlns:fresco="http://schemas.android.com/tools"
    android:id="@+id/comments_coordinator_layout">

<android.support.design.widget.AppBarLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/comments_appbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:layout_below="@id/comments_coordinator_layout"
        android:id="@+id/view_post"
        android:layout_width="match_parent"
        android:paddingRight="5dp"
        android:paddingLeft="5dp"
        android:orientation="horizontal"
        android:layout_height="175dp"
        android:background="#e6e6e6">

        <com.facebook.drawee.view.SimpleDraweeView
            android:layout_marginTop="15dp"
            android:id="@+id/poster_picture"
            android:layout_width="75dp"
            android:layout_height="75dp"
            android:layout_marginLeft="10dp"
            fresco:placeholderImage="@mipmap/blank_prof_pic"
            fresco:roundedCornerRadius="5dp"
            />

        <TextView
            android:layout_marginLeft="5dp"
            android:layout_marginTop="15dp"
            android:layout_toRightOf="@id/poster_picture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            android:textStyle="bold"
            android:id="@+id/poster_name"/>

        <TextView
            android:layout_alignParentRight="true"
            android:layout_marginTop="15dp"
            android:layout_toRightOf="@id/poster_name"
            android:layout_marginLeft="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            android:id="@+id/post_date"/>

        <TextView
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@id/poster_picture"
            android:layout_below="@id/poster_name"
            android:textSize="20sp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/view_status" />

    </RelativeLayout>

            <ListView
                android:id="@+id/lv_comments_feed"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/send_message"
                android:layout_below="@id/view_post">
            </ListView>

        <LinearLayout
            android:id="@+id/send_message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal" >

            <EditText
                android:id="@+id/write_comment"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center_horizontal"
                android:layout_weight="5"
                android:gravity="top|left"
                android:hint="Comment back!"
                android:inputType="textMultiLine"
                android:background="@color/white"
                android:scrollHorizontally="false" />

            <Button
                android:id="@+id/send_comment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center_horizontal"
                android:gravity="center"
                android:text="send"
                android:textAppearance="?android:attr/textAppearanceMedium" />
        </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

One thing I don't understand is why when I click on the design tab of my layout, it just seems like all my layouts overlap each other as opposed to displaying below each other. Furthermore, I don't see why the ListView is prioritized being shown over my LinearLayout and RelativeLayout. Is there any way I can get it so that I have the following structure from top to bottom: AppBarLayout -> RelativeLayout -> ListView -> LinearLayout. Any help would be appreciated. Thanks!
If it means anything, in my AndroidManifest, I have android:windowSoftInputMode="stateVisible"

Block quote

EDIT: this is an example of what I want to achieve
Edit: After taking some advice from tiny sunshine, here is what I have so far:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
    xmlns:fresco="http://schemas.android.com/tools"
    android:id="@+id/comments_coordinator_layout">

<android.support.design.widget.AppBarLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/comments_appbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:layout_marginTop="?attr/actionBarSize"
        android:layout_below="@id/comments_coordinator_layout"
        android:id="@+id/view_post"
        android:layout_width="match_parent"
        android:paddingRight="5dp"
        android:paddingLeft="5dp"
        android:orientation="horizontal"
        android:layout_height="175dp"
        android:background="#e6e6e6">

        <com.facebook.drawee.view.SimpleDraweeView
            android:layout_marginTop="15dp"
            android:id="@+id/poster_picture"
            android:layout_width="75dp"
            android:layout_height="75dp"
            android:layout_marginLeft="10dp"
            fresco:placeholderImage="@mipmap/blank_prof_pic"
            fresco:roundedCornerRadius="5dp"
            />

        <TextView
            android:layout_marginLeft="5dp"
            android:layout_marginTop="15dp"
            android:layout_toRightOf="@id/poster_picture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            android:textStyle="bold"
            android:id="@+id/poster_name"/>

        <TextView
            android:layout_alignParentRight="true"
            android:layout_marginTop="15dp"
            android:layout_toRightOf="@id/poster_name"
            android:layout_marginLeft="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15sp"
            android:id="@+id/post_date"/>

        <TextView
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@id/poster_picture"
            android:layout_below="@id/poster_name"
            android:textSize="20sp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/view_status" />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:layout_marginTop="225dp"
            android:id="@+id/lv_comments_feed"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/send_message">
        </ListView>

        <LinearLayout
            android:id="@+id/send_message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal" >

            <EditText
                android:id="@+id/write_comment"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center_horizontal"
                android:layout_weight="5"
                android:gravity="top|left"
                android:hint="Comment back!"
                android:inputType="textMultiLine"
                android:scrollHorizontally="false" />

            <Button
                android:id="@+id/send_comment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center_horizontal"
                android:gravity="center"
                android:text="send"
                android:textAppearance="?android:attr/textAppearanceMedium" />
        </LinearLayout>

    </RelativeLayout>

</android.support.design.widget.CoordinatorLayout>

EDIT: Issue with EditText. As you can see, the layout only shows the ListView when I click the EditText and hides everything including the ActionToolBar and Status Bar.

Edit: Showing Android Manifest
    <activity android:name=".com.tabs.activity.Comments"
        android:label="View Post"
        android:theme="@style/AppTheme.NoActionBar"
        android:windowSoftInputMode="adjustPan">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".com.tabs.activity.news_feed"/>
    </activity>

Edit: Suggestion by Tiny Sunlight:
<FrameLayout>
  <ToolBar></ToolBar>
  <Relative Layout as List header></RelativeLayout as ListHeader>
  <ListView></ListView>
  <LinearLayout for Edit Text></LinearLayout for EditText>
</FrameLayout>

A: Just add a ScrollView and set softInputMode to adjustResize.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    android:fitsSystemWindows="true"
    android:layout_width="match_parent" android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent" android:fitsSystemWindows="true"
        xmlns:fresco="http://schemas.android.com/tools"
        android:id="@+id/comments_coordinator_layout">

        <android.support.v7.widget.Toolbar
            android:layout_alignParentTop="true"
            android:id="@+id/comments_appbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <RelativeLayout
            android:layout_below="@id/comments_appbar"
            android:id="@+id/view_post"
            android:layout_width="match_parent"
            android:paddingRight="5dp"
            android:paddingLeft="5dp"
            android:orientation="horizontal"
            android:layout_height="175dp"
            android:background="#e6e6e6">

            <com.facebook.drawee.view.SimpleDraweeView
                android:layout_marginTop="15dp"
                android:id="@+id/poster_picture"
                android:layout_width="75dp"
                android:layout_height="75dp"
                android:layout_marginLeft="10dp"
                fresco:placeholderImage="@mipmap/blank_prof_pic"
                fresco:roundedCornerRadius="5dp"
                />

            <TextView
                android:layout_marginLeft="5dp"
                android:layout_marginTop="15dp"
                android:layout_toRightOf="@id/poster_picture"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="15sp"
                android:textStyle="bold"
                android:id="@+id/poster_name"/>

            <TextView
                android:layout_alignParentRight="true"
                android:layout_marginTop="15dp"
                android:layout_toRightOf="@id/poster_name"
                android:layout_marginLeft="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="15sp"
                android:id="@+id/post_date"/>

            <TextView
                android:layout_marginLeft="5dp"
                android:layout_toRightOf="@id/poster_picture"
                android:layout_below="@id/poster_name"
                android:textSize="20sp"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/view_status" />

        </RelativeLayout>

        <ListView
            android:id="@+id/lv_comments_feed"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/send_message"
            android:layout_below="@id/view_post">
        </ListView>

        <LinearLayout
            android:id="@+id/send_message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal" >

            <EditText
                android:id="@+id/write_comment"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center_horizontal"
                android:layout_weight="5"
                android:gravity="top|left"
                android:hint="Comment back!"
                android:inputType="textMultiLine"
                android:background="@color/white"
                android:scrollHorizontally="false" />

            <Button
                android:id="@+id/send_comment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center_horizontal"
                android:gravity="center"
                android:text="send"
                android:textAppearance="?android:attr/textAppearanceMedium" />
        </LinearLayout>

    </RelativeLayout>
</ScrollView>


text:
Q: Django - Jinja2 caching of template variables Before Jinja2 i was using a custom context_processor for caching (objects list ) via memcached.
#context_processors.py
def pikto_studio_caching(request:None, sender:None, **kwargs):
        cache_time = 60*60*24
        cache_key_works = 'pikto_studio:works'

        works = cache.get(cache_key_works)

        if request:
            if not works:
                works = Work.objects.all()
                cache.set(cache_key_works, works, cache_time)
            return {'WORKS':works}
        else:
            cache._cache.flush_all()
            return None

With jinja2 i can't use context_processors. How can i solve this?
Thanks.

A: Create jinja2.py file, add your caching function to Jinja2 environment globals.
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from django.template import defaultfilters
from jinja2 import Environment

#CACHING
from django.core.cache import cache
from django.db.models.signals import post_save
from apps.web.models import Work, CategoryWork, BasicArticle, CategoryBasicArticle

def caching(request=None, sender=None, **kwargs):
    cache_time = 60*60*24
    cache_key_works = 'pikto_studio:works'

    works = cache.get(cache_key_works)

    if request:
        if not works:
            works = Work.objects.all()
            cache.set(cache_key_works, works, cache_time)
        return {'works':works}
    else:
        cache._cache.flush_all()
        return None

def environment(**options):
    env = Environment(**options)

    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
        'caching':caching,

    })
    return env

call the function in the template :
{% set works = caching(request)['works'] %}
    {% for work in works %}
     {{ work.title }}
{% endfor %}


text:
Q: Repeated Measures Analysis for a Single Treatment with Missing Data I have some data here that I am at a loss on how to analyze.
The following data set represents a subset of some data I have where a number of subjects (4 here, about fifty in the actual set) underwent a single treatment over a period of days (unequally spaced, for reasons I can't get into, and much longer than twenty days), and I'm interested in proving the hypotheses that a) the response for each subject is not significantly different from 20,000 (from theoretical considerations) over the time elapsed; and b) the subjects' responses to the treatment are not significantly different from each other.
Days Subject 1 Subject 2 Subject 3 Subject 4
0    18978.32  19820.70  19820.73  19865.00
1    19773.49  20986.11  20659.65  20706.34
5    22150.53  20323.14  19966.60  19966.56
10   21131.95  20815.21  20634.20  20769.92
18             21041.41  19336.45  19627.55
20             19178.02  19264.49  19178.03

I had the initial thought of using repeated measures ANOVA, but it is my understanding that that procedure is unable to cope with missing data. (That is, a number of subjects dropped out before the full period elapsed, but I figure I still want to account for these drop-outs in my analysis.)
I've heard a mixed linear model might be suited for this task, but I'm not sure how to go about it.
Any assistance would be appreciated. How to do this analysis in, say, R, would be welcome.

Edit:
I had the idea of doing a stationarity test for each subject (probably with augmented Dickey-Fuller) to test if the trend is essentially constant, but I don't know how to incorporate a way to test if the "constant trend" thus hypothesized is equal to the theoretical value of 20,000. I could also try doing a pairwise comparison of means, but I'm not sure the assumptions for that test would be fitting.


text:
Q: Pandas: Subset data frame using list, keeping duplicates multiple times I have a large list which includes duplicate values and I wish to subset a data frame using the list values. Usually I would use the .isin method, but I want to keep duplicate rows. Here is some example code:
df = pd.DataFrame(np.array([[1, 2, 'car'], [4, 5, 'bike'], [1, 2, 'train'], [1, 2, 'car'], [1, 2, 'train']]),columns=['a', 'b', 'c'])

lst = ['car', 'bike', 'car', 'car']

So I want to return a data frame that includes all rows each time they occur. Every time a item occurs in the list, I want to return the corresponding rows.
On a simple dataset such as the above I can loop through the list and append to a new data frame the returned values, but on a large dataset this seems to be taking an extremely long time. Any suggestions?
EDIT: So Chris' suggestion works, and provides the expected output using:
pd.concat([df[df['c'].eq(x)] for x in lst])

However, as with using a loop this is extremely slow when compared to something like the .isin method when working with much larger data. Added this edit so that the expected output can be created.

A: IIUC, use pandas.concat with a list comprehension:
df_new = pd.concat([df[df['c'].eq(x)] for x in lst], ignore_index=True)

An alternative approach could be to create a helper Series with value_counts method on your list and reduce original DataFrame size filtering using .isin method:
s = pd.Series(lst).value_counts()
df = df[df['c'].isin(set(lst))]

idx = np.concatenate([df[df['c'].eq(i)].index.repeat(r) for i, r in s.iteritems()])

df_new = df.loc[idx]

A: If I have correctly understood your question, groupby could help:
gr = df.groupby('c')
for i in lst:
    subset = gr.get_group(i)
    # process subset...

A: First step is filter only matched values:
df = df[df['c'].isin(lst)]

Then flatten index values what match condition and then use loc for repeat, np.repeat is also possible, but it convert all columns to strings, so not possible use here:
idx = [y for x in lst for y in df.index[df['c'].values == x]]
df_new = df.loc[idx].reset_index(drop=True)
print (df_new)
   a  b     c
0  1  2   car
1  1  2   car
2  4  5  bike
3  1  2   car
4  1  2   car
5  1  2   car
6  1  2   car

If many repeating values is possible filter only once and then repeat index values:
ser = pd.Series(lst)
idx = ser.map({k:df.index[df['c'].values == k] for k, v in ser.value_counts().items()})
df_new = df.loc[list(chain.from_iterable(idx))].reset_index(drop=True)
print (df_new)
   a  b     c
0  1  2   car
1  1  2   car
2  4  5  bike
3  1  2   car
4  1  2   car
5  1  2   car
6  1  2   car

Another solution:
from  itertools import chain
from collections import Counter

d = {k:df.index[df['c'].values == k] for k, v in Counter(lst).items()}
idx = [y for x in lst for y in d[x]]
df_new = df.loc[idx].reset_index(drop=True)


text:
Q: Vue.js отслеживание клика вне элемента Есть следующая разметка:

        <input type="text" v-model="currentPrice" @change="changePrice" @keyup.enter="changingPrice">

    {{currentPrice}} руб

По умолчанию показывается цена товара. При двойном клике инициализируется changingPrice, который меняет переменную isChangingPrice = !isChangingPrice.
Таким образом, после двойного клика, я получаю возможность редактирования данного поля.
Каким образом я могу менять переменную isChangingPrice по клику ВНЕ input'a?

A: Можно использовать кастомную директиву:
Vue.directive('click-outside', {
    bind(el, binding) {
        el.addEventListener('click', e => e.stopPropagation());
        document.body.addEventListener('click', binding.value);
    },
    unbind(el, binding) {
        document.body.removeEventListener('click', binding.value);
    }
});

Использование:

Только в этом примере значением может быть только функция.


text:
Q: Linux remove a occurrence of sentence from a file and add add start and end I have a script that curl a command to sms gateway to send sms and get xml as response. Each response are appended to a single file for future xsltproc process for creating csv.
A single response is like:
<?xml version='1.0' encoding='ISO-8859-1' ?><REPLY><PARAMETER>OK</PARAMETER><LOGIN>SUCCESSFULL</LOGIN><PUSHAPI>ACTIVE</PUSHAPI><STAKEHOLDERID>OK</STAKEHOLDERID><PERMITTED>OK</PERMITTED><SMSINFO><MSISDN>xxxxxxxxxxxxx</MSISDN><SMSTEXT>Test+SMS+Check</SMSTEXT><CSMSID>113426778</CSMSID><REFERENCEID>2020050321383271896124009</REFERENCEID></SMSINFO></REPLY>

Now each time the script runs it appends the same response with separate values with duplicate <?xml version='1.0' encoding='ISO-8859-1' ?><REPLY> and </REPLY>
so after 2nd time execution the file will be:
<?xml version='1.0' encoding='ISO-8859-1' ?><REPLY><PARAMETER>OK</PARAMETER><LOGIN>SUCCESSFULL</LOGIN><PUSHAPI>ACTIVE</PUSHAPI><STAKEHOLDERID>OK</STAKEHOLDERID><PERMITTED>OK</PERMITTED><SMSINFO><MSISDN>xxxxxxxxxxxxx</MSISDN><SMSTEXT>Test+SMS+Check</SMSTEXT><CSMSID>113426778</CSMSID><REFERENCEID>2020050321383271896124009</REFERENCEID></SMSINFO></REPLY><?xml version='1.0' encoding='ISO-8859-1' ?><REPLY><PARAMETER>OK</PARAMETER><LOGIN>SUCCESSFULL</LOGIN><PUSHAPI>ACTIVE</PUSHAPI><STAKEHOLDERID>OK</STAKEHOLDERID><PERMITTED>OK</PERMITTED><SMSINFO><MSISDN>xxxxxxxxxxxxx</MSISDN><SMSTEXT>Test+SMS+Check</SMSTEXT><CSMSID>113426778</CSMSID><REFERENCEID>2020050321383271896124009</REFERENCEID></SMSINFO></REPLY>

which have 2 <?xml version='1.0' encoding='ISO-8859-1' ?><REPLY> and </REPLY>.
But xsltproc can not process multiple <?xml version='1.0' encoding='ISO-8859-1' ?><REPLY> and </REPLY>
So I need to remove all <?xml version='1.0' encoding='ISO-8859-1' ?><REPLY> and </REPLY> and just keep or add a <?xml version='1.0' encoding='ISO-8859-1' ?><REPLY> at beginning of file and </REPLY> end of file while final processing.
So my file while processing for xsltproc after 2nd run should be like:
<?xml version='1.0' encoding='ISO-8859-1' ?><REPLY><PARAMETER>OK</PARAMETER><LOGIN>SUCCESSFULL</LOGIN><PUSHAPI>ACTIVE</PUSHAPI><STAKEHOLDERID>OK</STAKEHOLDERID><PERMITTED>OK</PERMITTED><SMSINFO><MSISDN>xxxxxxxxxxxxx</MSISDN><SMSTEXT>Test+SMS+Check</SMSTEXT><CSMSID>113426778</CSMSID><REFERENCEID>2020050321383271896124009</REFERENCEID></SMSINFO><PARAMETER>OK</PARAMETER><LOGIN>SUCCESSFULL</LOGIN><PUSHAPI>ACTIVE</PUSHAPI><STAKEHOLDERID>OK</STAKEHOLDERID><PERMITTED>OK</PERMITTED><SMSINFO><MSISDN>xxxxxxxxxxxxx</MSISDN><SMSTEXT>Test+SMS+Check</SMSTEXT><CSMSID>113426778</CSMSID><REFERENCEID>2020050321383271896124009</REFERENCEID></SMSINFO></REPLY>

So how to remove all <?xml version='1.0' encoding='ISO-8859-1' ?><REPLY> except the first one in the file and remove all </REPLY> except the last one.
Or is there any other way to create the csv or xlx for record.

A: With GNU sed, it will start as simple as
sed 's/...//g2' file

In GNU sed, asking for a general (g) substitution followed by a number means that all the repetitions starting with the number will be replaced.
sed 's@<?xml version='1.0' encoding='ISO-8859-1' ?><REPLY>@@g2' file

Of course that doesn't change the </REPLY> tags, this would:
sed 's@</REPLY>@@g' file; echo '</REPLY>' >> file


text:
Q: Twins in Prolog will repeat answer Let's say that I have 3 childrens
person(pet,fox,date(5,may,2004),unemployed).
person(jim,fox,date(5,may,2004),unemployed).
person(george,fox,date(9,december,2002),unemployed).

child(X):-X=person(pet,fox,date(5,may,2004),unemployed).
child(X):-X=person(jim,fox,date(5,may,2004),unemployed).
child(X):-X=person(george,fox,date(9,december,2002),unemployed).

I want to get the twins of these childrens
twins(Child1,Child2) :-
    child(Child1),child(Child2),
    Child1=person(Fname1,_,Date1,_),
    Child2=person(Fname2,_,Date2,_),
    Fname1\=Fname2,
    Date1=Date2.

The problem is when I ask prolog twins(X,Y). I will get some answers again. How to prevent that?
?- twins(X,Y).
X = person(pet, fox, date(5, may, 2004), unemployed),
Y = person(jim, fox, date(5, may, 2004), unemployed) ;
X = person(jim, fox, date(5, may, 2004), unemployed),
Y = person(pet, fox, date(5, may, 2004), unemployed) ;
false.

A: You can prevent generation of all permutations by imposing a non-symmetrical order on the elements of the pair:
?- twins(X, Y), X @< Y.
X = person(jim, fox, date(5, may, 2004), unemployed),
Y = person(pet, fox, date(5, may, 2004), unemployed) ;
false.

This only eliminates unwanted solutions from this query, but to achieve this on every call to twins/2 you can just replace \= inside the definition of twins/2 by @<. (Two terms in the @< relation are automatically unequal in the sense of \= unless one of them is a variable.)
As another comment, the duplication of your database as both person/4 facts and as data inside the clauses of child/1 is strange, unnecessary, and very error-prone. You could replace your three-clause definition of child/1 with this single clause that refers to your person/4 database:
child(X) :-
    person(FirstName, LastName, DOB, Status),
    X = person(FirstName, LastName, DOB, Status).


text:
Q: Add Xib file as CameraOverlay to create a Custom Camera UI (XAMARIN.iOS) I m trying to create a camera Custom UI (somewhat like Instagram camera view )
Can Some one help me with adding .xib (layout for my cameraOverlayView) as cameraOverlayView .
inside -> ViewDidLoad()
        base.ViewDidLoad();
        var imagePickerControl = new UIImagePickerController();
        imagePickerControl.SourceType =  UIImagePickerControllerSourceType.Camera;
        imagePickerControl.ShowsCameraControls = true;
        //Code lines needed to add the xib "CameraOverlayView.xib" as uiview to pass next line
        imagePickerControl.CameraOverlayView = ;

        var imagePickerDelegate = new CameraImagePicker(this);
        imagePickerControl.Delegate = imagePickerDelegate;
        NavigationController.PresentModalViewController(imagePickerControl, true);

I was refering to
https://developer.xamarin.com/recipes/ios/general/templates/using_the_ios_view_xib_template/
But I was unable to add the xib as my CameraOverlay
Ask for related code if needed ..
thanks in advance


text:
Q: ImportError: import apache_beam as beam. Module not found I've installed apache_beam Python SDK and apache airflow Python SDK in a Docker.
Python Version: 3.5
Apache Airflow: 1.10.5
I'm trying to execute apache-beam pipeline using **DataflowPythonOperator**.
When I run a DAG from airflow UI at that time I get

Import Error: import apache_beam as beam. Module not found

With the same setup I tried **DataflowTemplateOperator** and it's working perfectly fine.
When I tried same docker setup with Python 2 and apache airflow 1.10.3, two months back at that time operator didn't returned any error and was working as expected.
After SSH into docker when I checked the installed libraries (using pip freeze) in a docker container I can see the installed versions of apache-beam and apache-airflow.
apache-airflow==1.10.5
apache-beam==2.15.0
Dockerfile:
RUN pip install --upgrade pip
RUN pip install --upgrade setuptools
RUN pip install apache-beam
RUN pip install apache-beam[gcp]
RUN pip install google-api-python-client
ADD . /home/beam

RUN pip install apache-airflow[gcp_api]

airflow operator:
new_task = DataFlowPythonOperator(
 task_id='process_details',
 py_file="path/to/file/filename.py",
 gcp_conn_id='google_cloud_default',
 dataflow_default_options={
             'project': 'xxxxx',
             'runner': 'DataflowRunner',
             'job_name': "process_details",
             'temp_location': 'GCS/path/to/temp',
             'staging_location': 'GCS/path/to/staging',
             'input_bucket': 'bucket_name',
             'input_path': 'GCS/path/to/bucket',
             'input-files': 'GCS/path/to/file.csv'
     },
     dag=test_dag)

A: This look like a known issue: https://github.com/GoogleCloudPlatform/DataflowPythonSDK/issues/46

please run pip install six==1.10. This is a known issue in Beam (https://issues.apache.org/jira/browse/BEAM-2964) which we are trying to get fixed upstream.

So try installing six==1.10 using pip

A: This may not be an option for you, but I was getting the same error with python 2. Executing the same script with python 3 resolved the error.
I was running through the dataflow tutorial:
https://codelabs.developers.google.com/codelabs/cpb101-simple-dataflow-py/
and when I follow the instructions as specified:
python grep.py
I get the error from the title of your post. I hit it with:
python3 grep.py

and it works as expected. I hope it helps. Happy hunting if it doesn't. See the link for details on what exactly I was running.

A: From this github link will help you to solve your problem. Follow below steps.

*

*Read following nice article on virtualenv, this will help in later steps,
https://www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/?utm_source=feedly

*Create virtual environment ( Note I created it in cloudml-samples folder & named it env)
titanium-vim-169612:~/cloudml-samples$ virtualenv env

*Activate virtual env
@titanium-vim-169612:~/cloudml-samples$ source env/bin/activate

*Install cloud-dataflow using following link: (this brings in apache_beam)
https://cloud.google.com/dataflow/docs/quickstarts/quickstart-python

*Now u can check that apache_beam is present in env/lib/python2.7/site-packages/
@titanium-vim-169612:~/cloudml-samples/flowers$ ls ../env/lib/python2.7/site-packages/
Run the sample
At this point, I got an error about missing tensorflow. I installed tensorflow in my virtualenv by using the link below (use installation steps for virtualenv),
https://www.tensorflow.org/install/install_linux#InstallingVirtualenv

The sample seems to work now.


text:
Q: python nested for to print out the position and name of a column in a dataframe I am trying to use a nested for to print out the position and name of a column in a dataframe. I do that because the .csv contains 185 columns and find it easier to print out 0 -> columnName.
With this code:
df = pd.read_csv('./data.csv', encoding='utf_8', usecols=[0,1,2,3,4])
[print(e,"->",col) for e,col in enumerate(df.columns)]

I try to get this output:
0 -> colName0
1 -> colName1
2 -> colName2
3 -> colName3
4 -> colName4

However, this is what I get
0 -> colName0
1 -> colName1
2 -> colName2
3 -> colName3
4 -> colName4

[None,
None,
None,
None,
None]

If I use a for loop with a print inside the output is how I expected.
for (e,col) in enumerate(df.columns):
   print(e,"->",col)

I am using:

*

*Anaconda 5.1.0 build py36_2

*Anaconda-client 1.6.9

*Anaconda-navigator  1.7.0

*Browser: Opera 52.0.2871.99

What I'm missing?

A: You're using a list comprehension to call print. This evaluates to a list of None's (which is the return value for print).

A: When you write
[print(e,"->",col) for e,col in enumerate(df.columns)]

you perform a list comprehension. While you print, you also create a list. Since print function returns None, you end up creating a list of None types. This is what you see at the end.


text:
Q: URL not opening on device yet it opens in Xcode I have a simple TabBar app which contains a button. Pressing the button opens a URL when running the app in the Simulator.
EDIT:
The app runs in both iPhone & iPad simulators (ver 5.1).
It also works when downloaded onto an iPhone (iOS 5.1.1)
But when I run the app on an iPad - whether it is tethered to Xcode or standalone - the URL does not open. In fact the breakpoint set in the event handler is never reached.
Xcode ver 4.4
iOS 5.1.1
It seems like the button containing the URL is not connected to an event handler in the storyboard. Yet I have double-checked it.
Any suggestions are welcome.

A: I found the problem. I had created a clear button which I laid over a UILabel. Clicking the button opens the URL. However, I did not have the struts configured the same for both objects. So when I rotated the device the button no longer aligned with the UILabel. Hence, I could press on the UILabel but nothing would happen. It was not an issue on the iPhone, because the app does not support rotation on that device.
Thanks for your input.