问:
How to programatically create order in woocommerce and redirect to payment gateway
I'm very new to payment gateway integration. I learned that, orders can be created programmatically without adding products in woocommerce and done that.

Problem now is, I'm not sure how to automate the payment process once submit order button is clicked.

Currently when the order form is submitted, I create order programmatically into woocommerce and expect the user to redirected to selected(currently by default is billPlz) payment gateway page to make payment.

I already had woocomerce and billPlz payment gateway installed. And WC()->payment_gateways->get_available_payment_gateways() does return me the billPlz.

However the payment form is not shown from the payment gateway for users to submit the payment into the billPlz.

I see 'success' message and redirected to mydomain/order-received/72?key=wc_order_5a0f8f3ead251

I assume this is the Thank you page?

How to redirect to payment gateway when order is created?

Order form (my own, not from woocomerce)

```<code><form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="POST">
    <input type="text" name="action" value="createOrder">
    <input type="text" name="booking_id" value="123">
    <input type="text" name="customer_id" value="1006">
    <input type="text" name="order_amount" value="180.00">
    <input type="text" name="order_status" value="1">

    <input type="submit" value="PROCEED TO MAKE PAYMENT">
</form>
</code>```

create order function

```<code>public function createOrder()
    {

        $product_id = 222;
        $quantity = 1;

        $args = array(
         'variation' => array( 'attribute_color' => 'red'),
         'status' => 'complete',
         'customer_id'=> 23
        );

        $order = wc_create_order();
        $order_id = trim(str_replace('#', '', $order->get_order_number()));

        $order->add_product( get_product( $product_id ), $quantity, $args );

        $order->set_status( $args['status'] );
        $order->set_customer_id( is_numeric( $args['customer_id'] ) ? absint( $args['customer_id'] ) : 0 );
        $order->set_total( ($discount['amount']/100) , 'order_discount'); // not pennies (use dollar amount)

        update_post_meta( $order_id, '_payment_method', 'billplz' );
        update_post_meta( $order_id, '_payment_method_title', 'Billplz Payment Gateway' );

        $order->calculate_totals();

        // Process Payment
        $available_gateways = WC()->payment_gateways->get_available_payment_gateways();

        $result = $available_gateways[ 'billplz' ]->process_payment( $order_id );

        // Redirect to success/confirmation/payment page
        if ( $result['result'] == 'success' ) {

            $result = apply_filters( 'woocommerce_payment_successful_result', $result, $order_id );
            $return_url = $available_gateways[ 'billplz' ]->get_return_url( $order );

            wp_redirect($return_url);
            exit;
        }
    }
</code>```

答:
You can generate a payment URL for unpaid orders like it appears in your My Account page under the Orders TAB by using the following orders function.</p>

```<code>$order->get_checkout_payment_url()
</code>```

Body:
I'm very new to payment gateway integration. I learned that, orders can be created programmatically without adding products in woocommerce and done that.

Problem now is, I'm not sure how to automate the payment process once submit order button is clicked.

Currently when the order form is submitted, I create order programmatically into woocommerce and expect the user to redirected to selected(currently by default is billPlz) payment gateway page to make payment.

I already had woocomerce and billPlz payment gateway installed. And WC()->payment_gateways->get_available_payment_gateways() does return me the billPlz.

However the payment form is not shown from the payment gateway for users to submit the payment into the billPlz.

I see 'success' message and redirected to mydomain/order-received/72?key=wc_order_5a0f8f3ead251

I assume this is the Thank you page?

How to redirect to payment gateway when order is created?

Order form (my own, not from woocomerce)

<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="POST">
    <input type="text" name="action" value="createOrder">
    <input type="text" name="booking_id" value="123">
    <input type="text" name="customer_id" value="1006">
    <input type="text" name="order_amount" value="180.00">
    <input type="text" name="order_status" value="1">

    <input type="submit" value="PROCEED TO MAKE PAYMENT">
</form>

create order function

public function createOrder()
    {

        $product_id = 222;
        $quantity = 1;

        $args = array(
         'variation' => array( 'attribute_color' => 'red'),
         'status' => 'complete',
         'customer_id'=> 23
        );

        $order = wc_create_order();
        $order_id = trim(str_replace('#', '', $order->get_order_number()));

        $order->add_product( get_product( $product_id ), $quantity, $args );

        $order->set_status( $args['status'] );
        $order->set_customer_id( is_numeric( $args['customer_id'] ) ? absint( $args['customer_id'] ) : 0 );
        $order->set_total( ($discount['amount']/100) , 'order_discount'); // not pennies (use dollar amount)

        update_post_meta( $order_id, '_payment_method', 'billplz' );
        update_post_meta( $order_id, '_payment_method_title', 'Billplz Payment Gateway' );

        $order->calculate_totals();

        // Process Payment
        $available_gateways = WC()->payment_gateways->get_available_payment_gateways();

        $result = $available_gateways[ 'billplz' ]->process_payment( $order_id );

        // Redirect to success/confirmation/payment page
        if ( $result['result'] == 'success' ) {

            $result = apply_filters( 'woocommerce_payment_successful_result', $result, $order_id );
            $return_url = $available_gateways[ 'billplz' ]->get_return_url( $order );

            wp_redirect($return_url);
            exit;
        }
    }

Body:
You can generate a payment URL for unpaid orders like it appears in your My Account page under the Orders TAB by using the following orders function.

$order->get_checkout_payment_url()


来源: stackexchange

问:
How to use pym.js
I'm a Java programmer, so I'm not just coming in here (completely)n00b-like. My boss just asked me to work on a project and after speaking with an engineer for the client company, I need to create a responsive iframe using pym.js. Problem is, I've never learned JavaScript. After reading through some docs and taking some udemy courses, I have the basics down. But there are only 6 questions regarding this pym.js on StackOverflow. I cannot for the life of me figure out how to use it.

Do I need to do something like this in the ...:

Also, I don't have access to the source files for the site that this is going to. Can still make my "child" iframe responsive based on "parent" width?

Any help would be much appreciated.

EDIT

This is what I have so far, hoping this is right.

index.html

iframe.html

答: Its seems you  are doing correctly but i am just new at stackoverflow but after doing your code over my system and tested on different OS (ubuntu, Windows and Mac) they all are working fine.</p>

ContentLicense: CC BY-SA 3.0

Title: How to use pym.js


问:
Rails getter on primary_key issue on update record
Greetings fellow devs,

I'm having an issue regarding the use of getter on table's id (primary_key), I encountered update records not working as expected, I'm new to ruby, I've been searching for the same issue but couldn’t find one.

I created a method in MainController

```<code>def do_the_hash_thingy(id)
  return id + 10
end

def do_the_unhash_thingy(id)
  return id.to_i - 10
end
</code>```

and this is the Model

```<code>def id
    if self[:id].present?
        MainController.new.do_the_hash_thingy(self[:id])
    end
end
</code>```

Let say the id is 4, after the hash process, it should be 14, and return back to 4 after unhash process

```<code>SampleTable.find(MainController.new.do_the_unhash_thingy(params[:id]))
SampleTable.column1 = 'new data'
SampleTable.save
</code>```

Log result

```<code>UPDATE `sample_table` SET `column1` = 'new data', `updated_at` = '2017-11-18 00:00:00' WHERE `sample_table`.`id` = 14
</code>```

weird that it still update on id 14 instead of 4

I've check the value of hash and unhash are returns as expected

Ruby version: 2.4.1

Rails Version: 5.0.6

答: This is resolved in rails 5.1.0. Please consider upgrading to 5.1.x. </p>

Body:
Greetings fellow devs,

I'm having an issue regarding the use of getter on table's id (primary_key), I encountered update records not working as expected, I'm new to ruby, I've been searching for the same issue but couldn’t find one.

I created a method in MainController

def do_the_hash_thingy(id)
  return id + 10
end

def do_the_unhash_thingy(id)
  return id.to_i - 10
end

and this is the Model

def id
    if self[:id].present?
        MainController.new.do_the_hash_thingy(self[:id])
    end
end

Let say the id is 4, after the hash process, it should be 14, and return back to 4 after unhash process

SampleTable.find(MainController.new.do_the_unhash_thingy(params[:id]))
SampleTable.column1 = 'new data'
SampleTable.save

Log result

UPDATE `sample_table` SET `column1` = 'new data', `updated_at` = '2017-11-18 00:00:00' WHERE `sample_table`.`id` = 14

weird that it still update on id 14 instead of 4

I've check the value of hash and unhash are returns as expected

Ruby version: 2.4.1

Rails Version: 5.0.6


问:
My Custom jsColor onfinechange function resets colors when clicking from background to color
So I have been working on my own "onfinechange" function and I have run into a bug that I just can not see why it is happening.

What I Expect

I want to be able to change the background or color of a div with jscolor and keep the color.

What is Happening

For Example: If I click in and change the background color, then try to click in and change the text color it kicks the background color back to the original color. This works visa-versa.

I cut out a sample of the bigger picture and documented it to make what is happening more clear.

The problem clearly lives in the jQuery somewhere, it's probably something tiny I am overlooking.

$(document).ready(function () {
    $('input').on('click', function (ev) {
        var inputPiece = $(this);
        var value = $(this).val(); //what in the input box that was clicked
        var clazz = $(this).attr('data-c'); //the div to change
        var bORc = $(this).attr('data-d'); //is it a background or color
        $('div').on('mousemove', function () {
            value = $(inputPiece).val(); //if the mouse is moving check the input value
        });
        var checkColor = setInterval(function () {

            if (bORc === 'b') {// if we are changing background
                $(clazz).attr("style", "background: #" + value + ' !important');
            }
            if (bORc === 'c') {//if we are changing color
                $(clazz).attr('style', 'color: #' + value + ' !important');
            }
        }, 50);
        $('input').on('blur', function () {
            clearInterval(checkColor);// shut down the interval
        });
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#fot {
  float:right;
}</code>```

<input type="text" data-t="" data-c="#fot" data-d="c" class="jscolor" name='footer_color' id='footer_color' value="FFF" />
<input type="text" data-t="" data-c="#fot" data-d="b" class="jscolor" name='footer_background' id='footer_background' value="FFF" />

text
```

答:
The issue is you're writing to a the style attribute directly, this means you are wiping out all other information inside the style.  However, if you use jQuery's .css you should avoid overriding previously set style information.

$(document).ready(function () {
    $('input').on('click', function (ev) {
        var inputPiece = $(this);
        var value = $(this).val(); //what in the input box that was clicked
        var clazz = $(this).attr('data-c'); //the div to change
        var bORc = $(this).attr('data-d'); //is it a background or color
        $('div').on('mousemove', function () {
            value = $(inputPiece).val(); //if the mouse is moving check the input value
        });
        var checkColor = setInterval(function () {

            if (bORc === 'b') {// if we are changing background
                $(clazz).css("background", '#' + value);
            }
            if (bORc === 'c') {//if we are changing color
                $(clazz).css("color", '#' + value);
            }
        }, 50);
        $('input').on('blur', function () {
            clearInterval(checkColor);// shut down the interval
        });
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#fot {
  display:inline-block;
  font-size:40px;
  background-color:black;
  color:red;
  margin:10px;
  padding:10px;
}</code>```

text

<input type="text" data-t="" data-c="#fot" data-d="c" class="jscolor" name='footer_color' id='footer_color' value="FFF" />
<input type="text" data-t="" data-c="#fot" data-d="b" class="jscolor" name='footer_background' id='footer_background' value="FFF" />```

Body:
So I have been working on my own "onfinechange" function and I have run into a bug that I just can not see why it is happening.

What I Expect

I want to be able to change the background or color of a div with jscolor and keep the color.

What is Happening

For Example: If I click in and change the background color, then try to click in and change the text color it kicks the background color back to the original color. This works visa-versa.

I cut out a sample of the bigger picture and documented it to make what is happening more clear.

The problem clearly lives in the jQuery somewhere, it's probably something tiny I am overlooking.

$(document).ready(function () {
    $('input').on('click', function (ev) {
        var inputPiece = $(this);
        var value = $(this).val(); //what in the input box that was clicked
        var clazz = $(this).attr('data-c'); //the div to change
        var bORc = $(this).attr('data-d'); //is it a background or color
        $('div').on('mousemove', function () {
            value = $(inputPiece).val(); //if the mouse is moving check the input value
        });
        var checkColor = setInterval(function () {

            if (bORc === 'b') {// if we are changing background
                $(clazz).attr("style", "background: #" + value + ' !important');
            }
            if (bORc === 'c') {//if we are changing color
                $(clazz).attr('style', 'color: #' + value + ' !important');
            }
        }, 50);
        $('input').on('blur', function () {
            clearInterval(checkColor);// shut down the interval
        });
    });
});

#fot {
  float:right;
}

<input type="text" data-t="" data-c="#fot" data-d="c" class="jscolor" name='footer_color' id='footer_color' value="FFF" />
<input type="text" data-t="" data-c="#fot" data-d="b" class="jscolor" name='footer_background' id='footer_background' value="FFF" />

text

Body:
The issue is you're writing to a the style attribute directly, this means you are wiping out all other information inside the style.  However, if you use jQuery's .css you should avoid overriding previously set style information.

$(document).ready(function () {
    $('input').on('click', function (ev) {
        var inputPiece = $(this);
        var value = $(this).val(); //what in the input box that was clicked
        var clazz = $(this).attr('data-c'); //the div to change
        var bORc = $(this).attr('data-d'); //is it a background or color
        $('div').on('mousemove', function () {
            value = $(inputPiece).val(); //if the mouse is moving check the input value
        });
        var checkColor = setInterval(function () {

            if (bORc === 'b') {// if we are changing background
                $(clazz).css("background", '#' + value);
            }
            if (bORc === 'c') {//if we are changing color
                $(clazz).css("color", '#' + value);
            }
        }, 50);
        $('input').on('blur', function () {
            clearInterval(checkColor);// shut down the interval
        });
    });
});

#fot {
  display:inline-block;
  font-size:40px;
  background-color:black;
  color:red;
  margin:10px;
  padding:10px;
}

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.js"></script>
<div id="fot">text</div><br />
<input type="text" data-t="" data-c="#fot" data-d="c" class="jscolor" name='footer_color' id='footer_color' value="FFF" />
<input type="text" data-t="" data-c="#fot" data-d="b" class="jscolor" name='footer_background' id='footer_background' value="FFF" />


问:
Java: equals check on interface instead of class
I have a case, where I have a Java-Interface representing an entity. This interface is implemented in 2 different classes.
As a consequence, I need a method that tests
- if 2 classes have a common interface
- if all Getter-Values of these 2 classes are the same

if both is true, then they pass as equal, in the case I need.
(note, that I do not know which interface they implement, there are a few possible)

Is that somehow possible, or do I need to give the interface and then check if the two classes implement it?

Thanks for your help,
Michael

答:
If you have no way of knowing which interface an object might be implementing I would suggest you make an umbrella interface.

```<code>public interface MyGeneralInterface {}
public interface SpecificInterface1 implements MyGeneralInterface {}
public interface SpecificInterface2 implements MyGeneralInterface {}
public class SpecificClass1 implements SpecificInterface1 {}
public class SpecificClass2 implements SpecificInterface2 {}
</code>```

Then as Jigar said, use instanceof.

```<code>if(myobj instanceof MyGeneralInterface) {}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you have no way of knowing which interface an object might be implementing I would suggest you make an umbrella interface.

public interface MyGeneralInterface {}
public interface SpecificInterface1 implements MyGeneralInterface {}
public interface SpecificInterface2 implements MyGeneralInterface {}
public class SpecificClass1 implements SpecificInterface1 {}
public class SpecificClass2 implements SpecificInterface2 {}

Then as Jigar said, use instanceof.

if(myobj instanceof MyGeneralInterface) {}


答:
An other iterative paint algorithm implementation, with  arrays for vectored exploration, and sets for selection.

```<code>around =array([[[ 0,  1]],[[-1,  0]],[[ 1,  0]],[[ 0, -1]]])

def grow(seed,color):
    filled=set()
    current = set(tuple(x) for x in seed)
    while current :
        seed=np.vstack(current)
        x,y = (around+seed).reshape(-1,2).T
        np.clip(x,0,m.shape[0]-1,x)
        np.clip(y,0,m.shape[1]-1,y)
        good = (m[x,y]==color)
        win = np.vstack((x[good],y[good])).T
        front=set(tuple(x) for x in win)
        current = front - filled
        filled |= current
    return np.vstack(filled) if filled else None

mout=m
seed=(vstack(np.where(m==1)).T)[:,None]
areas=dict()
n=4

for color in (0,2,0,3):
     next=[ grow(s,color) for s in seed]
     areas[n]=next
     st=np.vstack(s for s in next if not s is None)
     x,y=st.T
     mout[x,y] = n
     n +=1
     seed = [ x if x is not None else y for (x,y) in zip(next,seed) ]

imshow(mout)
</code>```

For :

Edit

A pure set solution, simpler and faster on this example:

```<code>def grows(current,color,m):
    ra,rb=m.shape
    filled=set()
    while current :
        next0={(a-1,b) for (a,b) in current if a>0}\
        | {(a,b-1) for (a,b) in current if b>0}\
        | {(a+1,b) for (a,b) in current if a<ra-1}\
        | {(a,b+1) for (a,b) in current if b<rb-1}
        next = { p for p in next0 if m[p]==color}
        current = next - filled
        filled |= current
    return filled

seed2=[set([p]) for p in zip(*np.where(m==1))]

def m2(seed,m):
    mout=m.copy()
    areas=dict()
    for i,color in enumerate((0,2,0,3)):
        next = [grows(s,color,mout) for s in seed]
        areas[i]=next
        for s in next :
            for p in s:
                mout[p] = 4+i
        seed=[x or y for x,y in zip(next,seed)]
    return mout,areas

mout,areas = m2(seed2,m)
imshow(mout)
</code>```

Title: Get all coordinates points within known boundaries in a numpy matrix for each dot

Body:
Given the following numpy matrix

import numpy as np

np_matrix = np.array(
[[0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,2,0,0,1,0,0,0,0,0,0]
,[0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,2,2,0,0,0,0,0,0,0,0]
,[0,0,0,3,0,0,0,0,2,2,2,0,0,0,0,0,3,0,0,0,3,0,0,2,2,2,2,2,2,2,2,2]
,[0,0,0,3,0,0,0,2,0,0,0,2,0,0,0,0,3,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,3,0,0,2,0,1,0,0,0,2,0,0,0,3,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0]
,[0,0,0,3,0,0,2,0,0,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3]
,[0,0,0,3,0,0,2,0,0,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,3,0,0,2,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,3,0,0,0,2,2,2,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[3,3,3,3,0,0,0,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,3,0,0,0,0,3,3,3,3,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,3,3,3,3,0,0,0,0,0,0,0,0]
,[0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0]
,[0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,2,2,2,0,0,3,0,0,0,0,0,0,0,0]
,[2,2,2,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,2,1,2,0,0,3,0,0,0,0,0,0,0,0]
,[0,0,2,2,0,3,3,0,0,0,0,0,0,0,0,3,3,0,2,2,2,0,0,3,0,0,0,0,0,0,0,0]
,[0,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0]
,[1,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0]
,[0,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,0,3,3,0,3,3,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,2,2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[2,2,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3]
,[0,0,0,0,0,3,0,0,0,0,0,0,3,3,3,3,3,3,3,3,0,0,0,0,3,0,0,0,0,0,0,0]
,[0,0,0,3,3,0,0,0,0,3,3,3,3,2,2,2,2,2,2,3,3,0,0,0,3,0,0,0,0,0,2,2]
,[3,3,3,3,0,0,0,0,0,3,2,2,2,0,0,0,0,0,2,2,3,0,0,0,3,0,0,0,2,2,2,0]
,[0,0,0,0,0,0,0,0,0,3,2,0,0,0,0,0,0,0,0,2,3,0,0,0,3,0,0,2,2,0,0,0]
,[0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,0,0,0,0,2,3,0,0,0,3,0,0,2,0,0,0,1]]
)

Which can be presented visually in a picture like this:

Where the red dots are numbered from left to right and can be identified in the matrix using the following function. Thanks to @DanielF in this answer

def getRedDotsCoordinatesFromLeftToRight(np_matrix, red_dor_number=1):
    red_dots = np.where(np_matrix == red_dor_number)
    red_dots = tuple(g[np.argsort(red_dots[-1])] for g in red_dots)
    red_dots = np.stack(red_dots)[::-1].T
    return red_dots

red_dots = getRedDotsCoordinatesFromLeftToRight(np_matrix)
print(red_dots)

red_dots = np.array(
    [[ 0, 25],
    [ 4,  8],
    [16, 19],
    [19,  0],
    [29, 14],
    [29, 31]]
)

Two questions:

Question 1: How can we identify all the white points coordinates (marked with
0) within the green boundaries (marked with 2) which are located with red dots (marked with 1) ?

Question 2:  How can we identify all the white points coordinates (marked with
0) between black boundaries (marked with 3)  and the green
boundaries (marked with 2) which are located with red dots (marked
with 1) ?

I am looking for this result for this example matrix:

space_within_greenDots = np.array(
    [[[17,  0], [17,  1], [18,  0], [18,  1], [18,  2], [19,  1], [19,  2], [20,  0], [20,  1], [20,  2], [21,  0], [21,  1], [21,  2], [22,  0], [22,  1]],
    [[ 3,  8], [ 3,  9], [ 3, 10], [ 4,  7], [ 4,  9], [ 4, 10], [ 4, 11], [ 5,  7], [ 5,  8], [ 5,  9], [ 5, 10], [ 5, 11], [ 6,  7], [ 6,  8], [ 6,  9], [ 6, 10], [ 6, 11], [ 7,  8], [ 7,  9], [ 7, 10]],
    [[27, 13], [27, 14], [27, 15], [27, 16], [27, 17], [28, 11], [28, 12], [28, 13], [28, 14], [28, 15], [28, 16], [28, 17], [28, 18], [29, 11], [29, 12], [29, 13], [29, 15], [29, 16], [29, 17], [29, 18]],
    [],
    [[ 0, 23], [ 0, 24], [ 0, 26], [ 0, 27], [ 0, 28], [ 0, 29], [ 0, 30], [ 0, 31], [ 1, 24], [ 1, 25], [ 1, 26], [ 1, 27], [ 1, 28], [ 1, 29], [ 1, 30], [ 1, 31]],
    [[27, 31], [28, 29], [28, 30], [28, 31], [29, 28], [29, 29], [29, 30]]],
)

space_between_darkDots_and_greenDots = np.array(
    [ [[12,  0], [12,  1], [12,  2], [13,  0], [13,  1], [13,  2], [13,  3], [14,  0], [14,  1], [14,  2], [14,  3], [15,  0], [15,  1], [15,  2], [15,  3], [15,  4], [16,  3], [16,  4], [17,  4], [18,  4], [18,  5], [19,  4], [19,  5], [20,  4], [20,  5], [21,  4], [21,  5], [22,  4], [22,  5], [23,  3], [23,  4], [23,  5], [24,  0], [24,  1], [24,  2], [24,  3], [24,  4], [25,  0], [25,  1], [25,  2], [25,  3], [25,  4], [26,  0], [26,  1], [26,  2]],
    [[ 0,  4], [ 0,  5], [ 0,  6], [ 0,  7], [ 0,  8], [ 0,  9], [ 0, 10], [ 0, 11], [ 0, 12], [ 0, 13], [ 0, 14], [ 0, 15], [ 1,  4], [ 1,  5], [ 1,  6], [ 1,  7], [ 1,  8], [ 1,  9], [ 1, 10], [ 1, 11], [ 1, 12], [ 1, 13], [ 1, 14], [ 1, 15], [ 2,  4], [ 2,  5], [ 2,  6], [ 2,  7], [ 2, 11], [ 2, 12], [ 2, 13], [ 2, 14], [ 2, 15], [ 3,  4], [ 3,  5], [ 3,  6], [ 3, 12], [ 3, 13], [ 3, 14], [ 3, 15], [ 4,  4], [ 4,  5], [ 4, 13], [ 4, 14], [ 4, 15], [ 5,  4], [ 5,  5], [ 5, 13], [ 5, 14], [ 5, 15], [ 6,  4], [ 6,  5], [ 6, 13], [ 6, 14], [ 6, 15], [ 7,  5], [ 7,  6], [ 7, 12], [ 7, 13], [ 7, 14], [ 8,  5], [ 8,  6], [ 8,  7], [ 8, 11], [ 8, 12], [ 8, 13], [ 8, 14], [ 9,  6], [ 9,  7], [ 9,  8], [ 9,  9], [ 9, 10], [ 9, 11], [ 9, 12], [ 9, 13], [10,  7], [10,  8], [10,  9], [10, 10], [10, 11], [10, 12], [11,  8], [11,  9], [11, 10], [11, 11]],
    [],
    [[13, 18], [13, 19], [14, 16], [14, 17], [14, 18], [14, 19], [14, 20], [14, 21], [14, 22], [15, 16], [15, 17], [15, 21], [15, 22], [16, 16], [16, 17], [16, 21], [16, 22], [17, 17], [17, 21], [17, 22], [18, 17], [18, 18], [18, 19], [18, 20], [18, 21], [18, 22], [19, 18], [19, 19], [19, 20], [19, 21], [20, 19]],
    [[ 0, 21], [ 1, 21], [ 2, 21], [ 2, 22], [ 3, 22], [ 3, 23], [ 3, 24], [ 3, 25], [ 3, 26], [ 3, 27], [ 3, 28], [ 3, 29], [ 3, 30], [ 3, 31], [ 4, 26], [ 4, 27], [ 4, 28], [ 4, 29], [ 4, 30], [ 4, 31]],
    [[25, 25], [25, 26], [25, 27], [25, 28], [25, 29], [25, 30], [25, 31], [26, 25], [26, 26], [26, 27], [26, 28], [26, 29], [27, 25], [27, 26], [27, 27], [28, 25], [28, 26], [29, 25], [29, 26]],
    ]
)

A few assumptions:

The matrix shape can vary. It is not a fixed size.

The number of red dots varies from matrix to matrix. But there is
always at least one red dot in the matrix.¨

Body:
An other iterative paint algorithm implementation, with  arrays for vectored exploration, and sets for selection.

around =array([[[ 0,  1]],[[-1,  0]],[[ 1,  0]],[[ 0, -1]]])

def grow(seed,color):
    filled=set()
    current = set(tuple(x) for x in seed)
    while current :
        seed=np.vstack(current)
        x,y = (around+seed).reshape(-1,2).T
        np.clip(x,0,m.shape[0]-1,x)
        np.clip(y,0,m.shape[1]-1,y)
        good = (m[x,y]==color)
        win = np.vstack((x[good],y[good])).T
        front=set(tuple(x) for x in win)
        current = front - filled
        filled |= current
    return np.vstack(filled) if filled else None

mout=m
seed=(vstack(np.where(m==1)).T)[:,None]
areas=dict()
n=4

for color in (0,2,0,3):
     next=[ grow(s,color) for s in seed]
     areas[n]=next
     st=np.vstack(s for s in next if not s is None)
     x,y=st.T
     mout[x,y] = n
     n +=1
     seed = [ x if x is not None else y for (x,y) in zip(next,seed) ]

imshow(mout)

For :

Edit

A pure set solution, simpler and faster on this example:

def grows(current,color,m):
    ra,rb=m.shape
    filled=set()
    while current :
        next0={(a-1,b) for (a,b) in current if a>0}\
        | {(a,b-1) for (a,b) in current if b>0}\
        | {(a+1,b) for (a,b) in current if a<ra-1}\
        | {(a,b+1) for (a,b) in current if b<rb-1}
        next = { p for p in next0 if m[p]==color}
        current = next - filled
        filled |= current
    return filled

seed2=[set([p]) for p in zip(*np.where(m==1))]

def m2(seed,m):
    mout=m.copy()
    areas=dict()
    for i,color in enumerate((0,2,0,3)):
        next = [grows(s,color,mout) for s in seed]
        areas[i]=next
        for s in next :
            for p in s:
                mout[p] = 4+i
        seed=[x or y for x,y in zip(next,seed)]
    return mout,areas

mout,areas = m2(seed2,m)
imshow(mout)


问:
Object of type 'function' has no len() in python
I have been searching for a solution for this error for a while but the solutions that have helped others have not been much help for me.

Here is the code that I've wrote.

```<code>def main():
    while True:
        userInput()
        characterCount(userInput)
        middleLetter()
        spaceCount()
        letterReplace()
        displayOutput()

def userInput():
    sentence = str(input('Enter a sentence at least 10 letters long, or type STOP to quit:'))
    if sentence == 'STOP':
        quit()
    return sentence

def characterCount(sentence):
    characterCount = len(sentence) - sentence.count(' ')
    if characterCount < 10:
        print('Sorry that is less than 10 letters')
    return characterCount

def middleLetter(sentence):
    sentence = len(sentence)/2
    middleLetter = [sentence +1]
    return middleLetter

def spaceCount(sentence):
    spaceCount = sentence.count(' ')
    return spaceCount

def letterReplace(sentence):
    letterReplace= sentence.replace("a", "&")
    return letterReplace

def displayOutput(characterCount,middleLetter,spaceCount,letterReplace):
    print('Number of letters: '(characterCount))
    print('Middle letter: '(middleLetter))
    print('Spaces counted: '(spaceCount))
    print('Sentence with letter replaced: '(letterReplace))

main()
</code>```

The problem I have is that when I run the program I get the error.

```<code>Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 18, in main
    characterCount(userInput)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 32, in characterCount
    characterCount = len(sentence) - sentence.count(' ')
TypeError: object of type 'function' has no len()
</code>```

Most of the times I have seen this error is because of a int being used instead of a string but I can not see what would be causing this error. Any help would be appreciated.

Using some of the given suggestions I have fixed the original error but now when I try to run it I receive the error.

```<code>Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 22, in main
    displayOutput(characterCount,middleLetter,spaceCount,letterReplace)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 53, in displayOutput
    print('Number of letters:'(characterCount))
TypeError: 'str' object is not callable
</code>```

答:
You are trying to call the function here with a function as an argument.

```userInput()
characterCount(<b>userInput</b>)```

Instead capture the return value in a variable and call the other function with the variable as an argument.

Example:

```<code>def f():
    return 4

def c(f):
    return f

x = c(f) # <function f at 0x00000231D4063A60>
print(dir(x))

# ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
</code>```

which doesn't have len()

Body:
I have been searching for a solution for this error for a while but the solutions that have helped others have not been much help for me.

Here is the code that I've wrote.

def main():
    while True:
        userInput()
        characterCount(userInput)
        middleLetter()
        spaceCount()
        letterReplace()
        displayOutput()

def userInput():
    sentence = str(input('Enter a sentence at least 10 letters long, or type STOP to quit:'))
    if sentence == 'STOP':
        quit()
    return sentence

def characterCount(sentence):
    characterCount = len(sentence) - sentence.count(' ')
    if characterCount < 10:
        print('Sorry that is less than 10 letters')
    return characterCount

def middleLetter(sentence):
    sentence = len(sentence)/2
    middleLetter = [sentence +1]
    return middleLetter

def spaceCount(sentence):
    spaceCount = sentence.count(' ')
    return spaceCount

def letterReplace(sentence):
    letterReplace= sentence.replace("a", "&")
    return letterReplace

def displayOutput(characterCount,middleLetter,spaceCount,letterReplace):
    print('Number of letters: '(characterCount))
    print('Middle letter: '(middleLetter))
    print('Spaces counted: '(spaceCount))
    print('Sentence with letter replaced: '(letterReplace))

main()

The problem I have is that when I run the program I get the error.

Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 18, in main
    characterCount(userInput)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 32, in characterCount
    characterCount = len(sentence) - sentence.count(' ')
TypeError: object of type 'function' has no len()

Most of the times I have seen this error is because of a int being used instead of a string but I can not see what would be causing this error. Any help would be appreciated.

Using some of the given suggestions I have fixed the original error but now when I try to run it I receive the error.

Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 22, in main
    displayOutput(characterCount,middleLetter,spaceCount,letterReplace)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 53, in displayOutput
    print('Number of letters:'(characterCount))
TypeError: 'str' object is not callable

Body:
You are trying to call the function here with a function as an argument.

userInput()
characterCount(userInput)

Instead capture the return value in a variable and call the other function with the variable as an argument.

Example:

def f():
    return 4

def c(f):
    return f

x = c(f) # <function f at 0x00000231D4063A60>
print(dir(x))

# ['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

which doesn't have len()


问:
How to pass a value into system call XV6
I am attempting to create a system call that will increment a number that was added to the cpu struct. However I believe that a sys call has to be void so how can I pass in a value when calling it for example.

incrementNum(3);

答:
Xv6 has its own functions for passing arguments from user space to kernel space (system call). You can use argint() to retrieve integer arguments in your system call and argstr() to retrieve string arguments.

Passing arguments can be done the traditional way but for retrieving the arguments, you must use these methods. In your case:

In syscall.c :

```<code>extern int incrementNum(int);

static int (*syscalls[])(void) = {
...
[SYS_incrementNum]  sys_incrementNum,
};
</code>```

In syscall.h

```<code>#define SYS_incrementNum 22
</code>```

In user.h

```<code>int incrementNum(int);
</code>```

In Usys.S

```<code>SYSCALL(incrementNum);
</code>```

In sysproc.c (where you want to retrieve the argument)

```<code>int
sys_incrementNum(int num)
{
    argint(0,&num); //retrieving first argument
    cprintf("%d - Inside system call!",num);
}
</code>```

Calling the system call can now be done via:

```<code>incrementNum(3);
</code>```

Body:
Xv6 has its own functions for passing arguments from user space to kernel space (system call). You can use argint() to retrieve integer arguments in your system call and argstr() to retrieve string arguments.

Passing arguments can be done the traditional way but for retrieving the arguments, you must use these methods. In your case:

In syscall.c :

extern int incrementNum(int);

static int (*syscalls[])(void) = {
...
[SYS_incrementNum]  sys_incrementNum,
};

In syscall.h

#define SYS_incrementNum 22

In user.h

int incrementNum(int);

In Usys.S

SYSCALL(incrementNum);

In sysproc.c (where you want to retrieve the argument)

int
sys_incrementNum(int num)
{
    argint(0,&num); //retrieving first argument
    cprintf("%d - Inside system call!",num);
}

Calling the system call can now be done via:

incrementNum(3);


问:
Fail to add and delete fields in a json object
Usually I would do this:

```<code>var res = {};
res =   {   _id: 'test@tester.com',
            password: 'ABCDEF',
            phone: '123123123',
            name: 'Torben Tester',
            userLog: [
                { date: 1510561026, text: 'was CREATED' },
                { date: 1510593431, text: 'was UPDATED' }
            ]
        }

res.foo = "bar";
delete res.password
delete res.userLog
</code>```

And I would end up with:

```<code>{   _id: 'test@tester.com',
    phone: '123123123',
    name: 'Torben Tester',
    foo: 'bar'
}
</code>```

But... if I get the record from MongoDB

```<code>usersTable.findOne (
    { _id: 'test@tester.com' }
,function (err, data) {
    res = data
}
</code>```

Then res is still the exactly the same as before

But none of the modifications work

```<code>res.foo = "bar";
delete res.password
delete res.userLog
</code>```

The do absolutely nothing. They dont return any errors and res remains the same before and after.

What am I missing?  Is there a chance that res is of a different type when it comes from mongodb?  (no its not an array, I checked that already)

when doing console.log(res) the structure is exactly the same in both cases.

Any ideas would be very helpful, completely stuck for hours on this one.

Just to make it more clear....  This is the actual code...

```<code>usersTable.findOne (
    { _id: userID }
,function (err, data) {

    show("============BEFORE================")
    show({data})
    data.agentName = agentName + "XXXX";
    delete data.password
    delete data.userLog
    show("============AFTER================")
    show({data})

    return resolve(data);
}
</code>```

答:
How I solved it...

```<code>data = data.toJSON();
</code>```

And thats all... then it worked perfectly.

So dont get fooled by console.log(data) cause it will show the EXACT same weather or not your result is an actual Json object.

Just sucks that it did not give any errors like "This is not a json object" or something similar.

Body:
Usually I would do this:

var res = {};
res =   {   _id: 'test@tester.com',
            password: 'ABCDEF',
            phone: '123123123',
            name: 'Torben Tester',
            userLog: [
                { date: 1510561026, text: 'was CREATED' },
                { date: 1510593431, text: 'was UPDATED' }
            ]
        }

res.foo = "bar";
delete res.password
delete res.userLog

And I would end up with:

{   _id: 'test@tester.com',
    phone: '123123123',
    name: 'Torben Tester',
    foo: 'bar'
}

But... if I get the record from MongoDB

usersTable.findOne (
    { _id: 'test@tester.com' }
,function (err, data) {
    res = data
}

Then res is still the exactly the same as before

But none of the modifications work

res.foo = "bar";
delete res.password
delete res.userLog

The do absolutely nothing. They dont return any errors and res remains the same before and after.

What am I missing?  Is there a chance that res is of a different type when it comes from mongodb?  (no its not an array, I checked that already)

when doing console.log(res) the structure is exactly the same in both cases.

Any ideas would be very helpful, completely stuck for hours on this one.

Just to make it more clear....  This is the actual code...

usersTable.findOne (
    { _id: userID }
,function (err, data) {

    show("============BEFORE================")
    show({data})
    data.agentName = agentName + "XXXX";
    delete data.password
    delete data.userLog
    show("============AFTER================")
    show({data})

    return resolve(data);
}

Body:
How I solved it...

data = data.toJSON();

And thats all... then it worked perfectly.

So dont get fooled by console.log(data) cause it will show the EXACT same weather or not your result is an actual Json object.

Just sucks that it did not give any errors like "This is not a json object" or something similar.


问:
How to count estimated time and show in table using angular js?
i have one list for show data in table and i am work in angularjs. and i am getting success for show data. and in my data one filed have nama follower count. so on page load table is show and in the background my one process is running for the get followers form the instagram api.so in the process i have settimeout for 1 - 1 followers take and take 5 sec wit and then after go 2nd followers take. that type one by one followers take in to 5 sec interval after.so i am show followers count in the table so here i need show also estimated time in which time period your followers is download.

for ex=> i have 16 followers and in the background 1 followers take and after wit for the 5 sec so my 16 followers in which time period after download. for ex. 1min, 1hours,1 day, etc...

Here is my table html =>

```<code><table>
    <tr>
      <th>Target UserName</th>
      <th>Followers</th>
      <th>Status</th>
     <th>Estimated time</th>
    </tr>
    <tr ng-repeat="r in Result">
        <td>{{r.target_username}}</td>
        <td>{{r.followres_count}}</td>
        <td>{{r.Flage ? "Done" : "running"}}</td>
        <td>{{r.followres_count * 5 }}</td> // here i have try like this but not get propare answer.
    </tr>
</table>
</code>```

here my data look like =>

```<code>TARGET      FOLLOWERS   STATUS  ESTIMATED TIME
 abc           16       Done             80
 t            3000       Done           15000
</code>```

答:
var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
    $scope.setValue = function(){
     var x = 11111150000;
     var time = moment.duration(x);
     var day = time.days();
     var hr = time.hours();
     var min = time.minutes();
     var sec = time.seconds();
     var y = (day ? day +' days ' : '') + (hr ? hr +' hours ' : '') + (min ? min +' min ':'' ) + ( sec ? sec +' sec':'');
     return y;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.angularjs.org/angular-1.0.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.js"></script>
<body ng-app="myApp">
  <div ng-controller="MyCtrl">
    <table>
      <tr>
          <td ng-bind="setValue()"></td>
      </tr>
  </table>
  </div>
</body></code>```

Use moment.duration to get the time in time format, if you know specific time.

Body:
i have one list for show data in table and i am work in angularjs. and i am getting success for show data. and in my data one filed have nama follower count. so on page load table is show and in the background my one process is running for the get followers form the instagram api.so in the process i have settimeout for 1 - 1 followers take and take 5 sec wit and then after go 2nd followers take. that type one by one followers take in to 5 sec interval after.so i am show followers count in the table so here i need show also estimated time in which time period your followers is download.

for ex=> i have 16 followers and in the background 1 followers take and after wit for the 5 sec so my 16 followers in which time period after download. for ex. 1min, 1hours,1 day, etc...

Here is my table html =>

      Target UserName
      Followers
      Status
     Estimated time

        {{r.target_username}}
        {{r.followres_count}}
        {{r.Flage ? "Done" : "running"}}
        {{r.followres_count * 5 }}	 // here i have try like this but not get propare answer.

here my data look like =>

TARGET      FOLLOWERS   STATUS  ESTIMATED TIME
 abc           16       Done             80
 t            3000       Done           15000

Body:
var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
    $scope.setValue = function(){
     var x = 11111150000;
     var time = moment.duration(x);
     var day = time.days();
     var hr = time.hours();
     var min = time.minutes();
     var sec = time.seconds();
     var y = (day ? day +' days ' : '') + (hr ? hr +' hours ' : '') + (min ? min +' min ':'' ) + ( sec ? sec +' sec':'');
     return y;
    }
}

<script src="https://code.angularjs.org/angular-1.0.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.js"></script>
<body ng-app="myApp">
  <div ng-controller="MyCtrl">
    <table>
      <tr>
          <td ng-bind="setValue()"></td>
      </tr>
  </table>
  </div>
</body>

Use moment.duration to get the time in time format, if you know specific time.


问:
how to get latest text file after searching all drive of a computer
I am trying to get the latest text file in my computer.
I need to go to each each drive of computer and searching for all the text file and need to get only one file which is latest.

I tried some code, getting one error and also not sure latest file from all of the drive will work or not

```<code>try
        {
            foreach (DriveInfo d in DriveInfo.GetDrives())
            {
                var X = GetLatestFiles(d.Name, "*.txt");

            }
        }
        catch (Exception ex) { Console.WriteLine(ex); }

public static FileInfo GetLatestFiles(string path, string searchPattern)
    {
        return Directory.EnumerateFiles(path, searchPattern).Union(
            Directory.EnumerateDirectories(path).SelectMany(d =>
            {
                try
                {
                    return GetLatestFiles(d, searchPattern);
                }
                catch (UnauthorizedAccessException)
                {
                    return Enumerable.Empty<String>();
                }
            })).OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime)).FirstOrDefault();
    }
</code>```

Error

The type arguments for method 'Enumerable.SelectMany(IEnumerable, Func>)'
  cannot be inferred from the usage. Try specifying the type arguments
  explicitly.   ConsoleApp1 C:\Users\H190733\source\repos\ConsoleApp1\ConsoleApp1\Program.cs    43  Active

答:
```<code>        FileInfo newestTextFile = null;
        foreach (DriveInfo d in DriveInfo.GetDrives())
        {
            var root = d.RootDirectory;
            var files = root.EnumerateFiles("*.txt", SearchOption.AllDirectories);
            forearch (var file in files)
            {
               if (newestTextFile == null || file.LastAccessTime > newestTextFile.LastAccessTime)
               {
                  newestTextFile = file;
               }
            }
        }
</code>```

Body:
I am trying to get the latest text file in my computer.
I need to go to each each drive of computer and searching for all the text file and need to get only one file which is latest.

I tried some code, getting one error and also not sure latest file from all of the drive will work or not

try
        {
            foreach (DriveInfo d in DriveInfo.GetDrives())
            {
                var X = GetLatestFiles(d.Name, "*.txt");

            }
        }
        catch (Exception ex) { Console.WriteLine(ex); }

public static FileInfo GetLatestFiles(string path, string searchPattern)
    {
        return Directory.EnumerateFiles(path, searchPattern).Union(
            Directory.EnumerateDirectories(path).SelectMany(d =>
            {
                try
                {
                    return GetLatestFiles(d, searchPattern);
                }
                catch (UnauthorizedAccessException)
                {
                    return Enumerable.Empty<String>();
                }
            })).OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime)).FirstOrDefault();
    }

Error

The type arguments for method 'Enumerable.SelectMany(IEnumerable, Func>)'
  cannot be inferred from the usage. Try specifying the type arguments
  explicitly.   ConsoleApp1 C:\Users\H190733\source\repos\ConsoleApp1\ConsoleApp1\Program.cs    43  Active


问:
Java adding issue
I have an issue with my java program displaying every number it is adding, what can I do so that it only displays the total. I am guessing since I have "element" in the last part of the code it showing every single addition: Here is what I have written:</p>

```<code>import java.util.Scanner;

public class SomeClass {
    public static void main(String[]args){
        int ans = 0;
        int num;
        Scanner keyboard = new Scanner(System.in);
        System.out.println("How many integers do you have? (Max 20)");
        int x= keyboard.nextInt();

        int [] element = new int[x];

        for(int subscript = 0; subscript < element.length; subscript++){
            System.out.println("Enter element for subscript " + (subscript));
            element[subscript] = keyboard.nextInt();
        }
        System.out.println("Here are all of those numbers");

        for(int subscript = 0; subscript < element.length; subscript++){

            num = element[subscript];
            System.out.println(num);

        }

        for (int i = 0; i < element.length; i++){
            ans += element[i];
            System.out.println("The sum of these numbers is " + ans);
        }
    }
}
</code>```

答:
Because You print out the 'num' as many as length of element. You have to delete that line if your intention is to show only the summed ans which is result of sumation. If you wanna show inputs then its fine

Also

Take this sentence out of the for loop

```<code>System.out.println("The sum of these numbers is " + ans);
</code>```

Everytime for loops working, that line works too. So make it works once after you add all the numbers with for loop.

Title: Java adding issue

Body:
I have an issue with my java program displaying every number it is adding, what can I do so that it only displays the total. I am guessing since I have "element" in the last part of the code it showing every single addition: Here is what I have written:

import java.util.Scanner;

public class SomeClass {
    public static void main(String[]args){
        int ans = 0;
        int num;
        Scanner keyboard = new Scanner(System.in);
        System.out.println("How many integers do you have? (Max 20)");
        int x= keyboard.nextInt();

        int [] element = new int[x];

        for(int subscript = 0; subscript < element.length; subscript++){
            System.out.println("Enter element for subscript " + (subscript));
            element[subscript] = keyboard.nextInt();
        }
        System.out.println("Here are all of those numbers");

        for(int subscript = 0; subscript < element.length; subscript++){

            num = element[subscript];
            System.out.println(num);

        }

        for (int i = 0; i < element.length; i++){
            ans += element[i];
            System.out.println("The sum of these numbers is " + ans);
        }
    }
}

Body:
Because You print out the 'num' as many as length of element. You have to delete that line if your intention is to show only the summed ans which is result of sumation. If you wanna show inputs then its fine

Also

Take this sentence out of the for loop

System.out.println("The sum of these numbers is " + ans);

Everytime for loops working, that line works too. So make it works once after you add all the numbers with for loop.


问:
When to use getX method
Coming from a C# background we use properties for something that would not take long to retrieve and a getX method if something would take long (msdn link). In Java, since there are no properties, do you use getX for both cases or is there some other convention to indicate a quick access from a not so quick access (other than documenting it)?

Edit:
For example would you use a different naming convention for a time consuming get operation like database access or also use the getX naming convention?

答:
As a rule of thumb, create a private member field for local access to your property and a getter / setter for external access.

Lots of 3rd party libs such as Spring rely on public methods for dependency injection (inversion of control), and and aspect oriented programming so using getter / setters facilitates that style of programming.

For example, Spring might be used to associate two objects together. Or you might use AOP to put some caching behaviour around a somewhat expensive get operation.

It also allows you to set breakpoints when the property is changed or retrieved, add logging etc. which can be useful for debugging.

Title: When to use getX method


问:
Update and flashdata message not working on CodeIgniter
I've been working on a new CodeIgniter application and so far I've been able to create "page_categories" into the table, now my problem is when I try to update a certain category.

Let's say that I have two records on page_categories table:

Ok, now to be more specific when I try to change the name of "Page Category Two" rather than changing that name, my form updates the first record "Page Category One". Any idea how to fix this?

This is what I have on my controller:

```<code>public function edit($id){
    $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]');

    if($this->form_validation->run() == FALSE){
        // Get Current Subject
        $data['item'] = $this->Pages_categories_model->get($id);

        // Load template
        $this->template->load('admin', 'default', 'pages_categories/edit', $data);
    } else {
        $old_name = $this->Pages_categories_model->get($id)->name;
        $new_name = $this->input->post('name');

        // Create Post Array
        $data = array(
            'name'  => $this->input->post('name')
        );

        // Insert Subject
        $this->Pages_categories_model->update($id, $data);

        // Activity Array
        $data = array(
            'resource_id'   => $this->db->insert_id(),
            'type'          => 'subject',
            'action'        => 'updated',
            'user_id'       => 1,
            'message'       => 'A page category ('.$old_name.') was renamed to ('.$new_name.')'
        );

        // Insert Activity
        $this->Activity_model->add($data);

        // Set Message
        $this->session->set_flashdata('success', 'Page category has been updated');

        //Redirect
        redirect('admin/pages_categories');
    }
}
</code>```

and this is what I have on my model:

```<code><?php
class Pages_categories_model extends CI_MODEL{
    function __construct(){
        parent::__construct();
        $this->table = 'pages_categories';
    }

    public function get_list(){
        $query = $this->db->get($this->table);
        return $query->result();
    }

    public function get($id){
        $query = $this->db->get($this->table);
        $this->db->where('id', $id);
        return $query->row();
    }

    public function add($data){
        $this->db->insert($this->table, $data);
    }

    public function update($id, $data){
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id){
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }
}
</code>```

and finally my view:

```<code><h2 class="page-header">Edit Page Category</h2>

<?php echo form_open('admin/pages_categories/edit/'.$item->id); ?>
    <div class="form-group">
        <?php echo form_label('Page Category Name', 'name'); ?>
        <?php
            $data = array(
                'name' => 'name',
                'id'    => 'name',
                'maxlength' => '100',
                'class'     => 'form-control',
                'value'     => $item->name,
            );
        ?>
        <?php echo form_input($data); ?>
    </div>

    <?php echo form_submit('mysubmit', 'Update Page Category', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>
</code>```

I would like to say that my flash data message is not working as I expected. (It's not that important though.)

I want the flash-data message to be displayed in a different view; here it is my view:

Page Categories

<?php $CI =& get_instance(); if($CI->session->flashdata('success'){ ?>

              Success!! <?php echo $this->session->flashdata('success'); ?>

     <?php } ?>
<?php if($this->session->flashdata('error')) : ?>
 <?php echo '
'.$this->session->flashdata('error').'
'; ?>
<?php endif; ?>

<?php if($subjects) : ?>

  ID
  Name
  Date Created

 <?php foreach($subjects as $subject) : ?>
 <?php $date = strtotime($subject->create_date); ?>
 <?php $formatted_date = date('F j, Y, g:i a', $date); ?>

   <?php echo $subject->id; ?>
   <?php echo $subject->name; ?>
   <?php echo $formatted_date; ?>

    <?php echo anchor('admin/pages_categories/edit/'.$subject->id.'', 'Edit', 'class="btn btn-default"'); ?>
    <?php echo anchor('admin/pages_categories/delete/'.$subject->id.'', 'Delete', 'class="btn btn-danger"'); ?>

 <?php endforeach; ?>

<?php else : ?>

No Page Category Found

<?php endif; ?>```

答:
Add the where clause before the query in this code in your model

```<code>public function get($id){
    $this->db->where('id', $id);  // Give where clause before query
    $query = $this->db->get($this->table);

    return $query->row();
}
</code>```

EDIT: Adding answer for flashdata

Well, for flashdata, You have to call $_SESSION directly. Source: codeigniter documentation here

so instead of

```<code><?php $CI =& get_instance(); if($CI->session->flashdata('success'){ ?>
</code>```

write

```<code><?php if(isset($_SESSION['success']) { ?>
</code>```

Body:
I've been working on a new CodeIgniter application and so far I've been able to create "page_categories" into the table, now my problem is when I try to update a certain category.

Let's say that I have two records on page_categories table:

Ok, now to be more specific when I try to change the name of "Page Category Two" rather than changing that name, my form updates the first record "Page Category One". Any idea how to fix this?

This is what I have on my controller:

public function edit($id){
    $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]');

    if($this->form_validation->run() == FALSE){
        // Get Current Subject
        $data['item'] = $this->Pages_categories_model->get($id);

        // Load template
        $this->template->load('admin', 'default', 'pages_categories/edit', $data);
    } else {
        $old_name = $this->Pages_categories_model->get($id)->name;
        $new_name = $this->input->post('name');

        // Create Post Array
        $data = array(
            'name'  => $this->input->post('name')
        );

        // Insert Subject
        $this->Pages_categories_model->update($id, $data);

        // Activity Array
        $data = array(
            'resource_id'   => $this->db->insert_id(),
            'type'          => 'subject',
            'action'        => 'updated',
            'user_id'       => 1,
            'message'       => 'A page category ('.$old_name.') was renamed to ('.$new_name.')'
        );

        // Insert Activity
        $this->Activity_model->add($data);

        // Set Message
        $this->session->set_flashdata('success', 'Page category has been updated');

        //Redirect
        redirect('admin/pages_categories');
    }
}

and this is what I have on my model:

<?php
class Pages_categories_model extends CI_MODEL{
    function __construct(){
        parent::__construct();
        $this->table = 'pages_categories';
    }

    public function get_list(){
        $query = $this->db->get($this->table);
        return $query->result();
    }

    public function get($id){
        $query = $this->db->get($this->table);
        $this->db->where('id', $id);
        return $query->row();
    }

    public function add($data){
        $this->db->insert($this->table, $data);
    }

    public function update($id, $data){
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id){
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }
}

and finally my view:

Edit Page Category

<?php echo form_open('admin/pages_categories/edit/'.$item->id); ?>

        <?php echo form_label('Page Category Name', 'name'); ?>
        <?php
            $data = array(
                'name' => 'name',
                'id'    => 'name',
                'maxlength' => '100',
                'class'     => 'form-control',
                'value'     => $item->name,
            );
        ?>
        <?php echo form_input($data); ?>

    <?php echo form_submit('mysubmit', 'Update Page Category', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>

I would like to say that my flash data message is not working as I expected. (It's not that important though.)

I want the flash-data message to be displayed in a different view; here it is my view:

Page Categories

<?php $CI =& get_instance(); if($CI->session->flashdata('success'){ ?>

              Success!! <?php echo $this->session->flashdata('success'); ?>

     <?php } ?>
<?php if($this->session->flashdata('error')) : ?>
 <?php echo '
'.$this->session->flashdata('error').'
'; ?>
<?php endif; ?>

<?php if($subjects) : ?>

  ID
  Name
  Date Created

 <?php foreach($subjects as $subject) : ?>
 <?php $date = strtotime($subject->create_date); ?>
 <?php $formatted_date = date('F j, Y, g:i a', $date); ?>

   <?php echo $subject->id; ?>
   <?php echo $subject->name; ?>
   <?php echo $formatted_date; ?>

    <?php echo anchor('admin/pages_categories/edit/'.$subject->id.'', 'Edit', 'class="btn btn-default"'); ?>
    <?php echo anchor('admin/pages_categories/delete/'.$subject->id.'', 'Delete', 'class="btn btn-danger"'); ?>

 <?php endforeach; ?>

<?php else : ?>

No Page Category Found

<?php endif; ?>

Body:
Add the where clause before the query in this code in your model

public function get($id){
    $this->db->where('id', $id);  // Give where clause before query
    $query = $this->db->get($this->table);

    return $query->row();
}

EDIT: Adding answer for flashdata

Well, for flashdata, You have to call $_SESSION directly. Source: codeigniter documentation here

so instead of

<?php $CI =& get_instance(); if($CI->session->flashdata('success'){ ?>

write

<?php if(isset($_SESSION['success']) { ?>


问:
Need help to make C# code simpler
I need to work with a lot of calculation with C#.

I wonder if possible to make the code simpler by calling the code fragments.

For example:

I have 3 calculation:

a -> x = (x + 2)/0.4

b -> x = 2x + (5*(x^2))

c -> x = 0.435 + 0.5x

I want to do calculation with that.

So, instead of writing all the calculation,

I want to just calling them whenever I need them for example

```<code>{
x = 3.5
result = a + c
}
</code>```

or

```<code>{
x = 3.5
result = (b/a + c) + 2b
}
</code>```

If u are familiar with Ev3 lego mindstorm. Its the thing that we call MyBlock.

Thanks in advance

答:
you can declare some properties.</p>

```<code>    double x
    {
        get;
        set;
    }
    double a
    {
        get
        {
            return (x + 2) / 0.4;
        }
    }
    double b
    {
        get
        {
        return 2*x + (5*(x*x));
        }
    }
    double c
    {
        get
        {
            return 0.435 + 0.5 * x;
        }
    }
</code>```

Title: Need help to make C# code simpler

Body:
I need to work with a lot of calculation with C#.

I wonder if possible to make the code simpler by calling the code fragments.

For example:

I have 3 calculation:

a -> x = (x + 2)/0.4

b -> x = 2x + (5*(x^2))

c -> x = 0.435 + 0.5x

I want to do calculation with that.

So, instead of writing all the calculation,

I want to just calling them whenever I need them for example

{
x = 3.5
result = a + c
}

or

{
x = 3.5
result = (b/a + c) + 2b
}

If u are familiar with Ev3 lego mindstorm. Its the thing that we call MyBlock.

Thanks in advance

Body:
you can declare some properties.

    double x
    {
        get;
        set;
    }
    double a
    {
        get
        {
            return (x + 2) / 0.4;
        }
    }
    double b
    {
        get
        {
        return 2*x + (5*(x*x));
        }
    }
    double c
    {
        get
        {
            return 0.435 + 0.5 * x;
        }
    }


问:
Send mail with attachment using mailjet in GAS
I am trying to send mail with a PDF attachment using Mailjet from Google Apps Script. I can send regular mail without issue, but not quite sure how to include an attachment.

Mailjet documentation: https://dev.mailjet.com/guides/#sending-with-attached-files

I think my problem is the Base64Content. I don't really understand how to encode the attachment. When I execute the below code, an email is being sent with a PDF attachment, but when I try and open the PDF it displays: "Cannot display PDF (test.pdf is of invalid format)".

```<code>var newDoc = DocumentApp.openById(newDocid)

var attachment = newDoc.getAs(MimeType.PDF);

var mailjeturl = "https://api.mailjet.com/v3.1/send";

var mailjetparams = {
    "Messages":[{
      "From": {"Email": 'myemail@domain.com',"Name": 'Robert'},
      "To": [{"Email": 'theiremail@domain.com'}],
      "Subject": 'subject',
      "HTMLPart": 'this message',
      "Attachments": [{"ContentType": "application/pdf",
                       "Filename": "test.pdf",
                       "Base64Content": Utilities.base64Encode(attachment)}]
    }]
  }

var mailjetoptions = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(mailjetparams),
    'headers': {'Authorization': 'Basic ' + Utilities.base64Encode(MAILJET_KEY)}
  };

var response = JSON.parse(UrlFetchApp.fetch(mailjeturl, mailjetoptions))
</code>```

答:
How about the following modification? I thought that the reason of the error may be Utilities.base64Encode(attachment).

Modification points :

attachment retrieved by newDoc.getAs(MimeType.PDF) is Blob. The Blob cannot be directly converted to base64 using Utilities.base64Encode(). So please convert Blob to byte array, and convert to base64.

When this is reflected to your script. The modification part is as follows.

From :

```<code>var attachment = newDoc.getAs(MimeType.PDF);
</code>```

To :

```<code>var attachment = newDoc.getAs(MimeType.PDF).getBytes();
</code>```

or

```<code>var attachment = newDoc.getBlob().getBytes();
</code>```

When Google Document is retrieved as a Blob, Google converts automatically to PDF. You can also use this.

Reference :

base64Encode()

If I misunderstand your question, I'm sorry.

Body:
I am trying to send mail with a PDF attachment using Mailjet from Google Apps Script. I can send regular mail without issue, but not quite sure how to include an attachment.

Mailjet documentation: https://dev.mailjet.com/guides/#sending-with-attached-files

I think my problem is the Base64Content. I don't really understand how to encode the attachment. When I execute the below code, an email is being sent with a PDF attachment, but when I try and open the PDF it displays: "Cannot display PDF (test.pdf is of invalid format)".

var newDoc = DocumentApp.openById(newDocid)

var attachment = newDoc.getAs(MimeType.PDF);

var mailjeturl = "https://api.mailjet.com/v3.1/send";

var mailjetparams = {
    "Messages":[{
      "From": {"Email": 'myemail@domain.com',"Name": 'Robert'},
      "To": [{"Email": 'theiremail@domain.com'}],
      "Subject": 'subject',
      "HTMLPart": 'this message',
      "Attachments": [{"ContentType": "application/pdf",
                       "Filename": "test.pdf",
                       "Base64Content": Utilities.base64Encode(attachment)}]
    }]
  }

var mailjetoptions = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(mailjetparams),
    'headers': {'Authorization': 'Basic ' + Utilities.base64Encode(MAILJET_KEY)}
  };

var response = JSON.parse(UrlFetchApp.fetch(mailjeturl, mailjetoptions))

Body:
How about the following modification? I thought that the reason of the error may be Utilities.base64Encode(attachment).

Modification points :

attachment retrieved by newDoc.getAs(MimeType.PDF) is Blob. The Blob cannot be directly converted to base64 using Utilities.base64Encode(). So please convert Blob to byte array, and convert to base64.

When this is reflected to your script. The modification part is as follows.

From :

var attachment = newDoc.getAs(MimeType.PDF);

To :

var attachment = newDoc.getAs(MimeType.PDF).getBytes();

or

var attachment = newDoc.getBlob().getBytes();

When Google Document is retrieved as a Blob, Google converts automatically to PDF. You can also use this.

Reference :

base64Encode()

If I misunderstand your question, I'm sorry.


问:
Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract
I'm trying to sort a collection of loans where the statuses of loans are  Active, Rejected, Pending and Approved.Active loans should get the highest priority and the others in any order.I implemented the Comparator interface's compare().

here 's the implementation of compare()

```<code>@Override
public int compare(Object o1, Object o2) {
    LoanAccountData loanAccountData1 = (LoanAccountData) o1;
    LoanAccountData loanAccountData2 = (LoanAccountData) o2;

    if (loanAccountData1.getStatusStringValue().equals("Active")) {
        return -1;
    } else {
        return 1;
    }
}
</code>```

答:
According to the contract of compare: here

Your code violates this rule:

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

If the status of x is active, and y's status is also active, then compare(x, y) will say that x is smaller, while compare(y, x) will say that y is smaller.

I think what you want to do here is to sort all the active accounts to the start of the list. This means that if both accounts are active or both are something else, they are equal. If one account is active, that is considered smaller.

```<code>LoanAccountData loanAccountData1 = (LoanAccountData) o1;
LoanAccountData loanAccountData2 = (LoanAccountData) o2;
boolean o1Active = loanAccountData1.getStatusStringValue().equals("Active");
boolean o2Active = loanAccountData2.getStatusStringValue().equals("Active");
if (o1Active == o2Active) {
    return 0;
} else if (o1Active) {
    return -1;
} else {
    return 1;
}
</code>```

Body:
I'm trying to sort a collection of loans where the statuses of loans are  Active, Rejected, Pending and Approved.Active loans should get the highest priority and the others in any order.I implemented the Comparator interface's compare().

here 's the implementation of compare()

@Override
public int compare(Object o1, Object o2) {
    LoanAccountData loanAccountData1 = (LoanAccountData) o1;
    LoanAccountData loanAccountData2 = (LoanAccountData) o2;

    if (loanAccountData1.getStatusStringValue().equals("Active")) {
        return -1;
    } else {
        return 1;
    }
}

Body:
According to the contract of compare: here

Your code violates this rule:

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

If the status of x is active, and y's status is also active, then compare(x, y) will say that x is smaller, while compare(y, x) will say that y is smaller.

I think what you want to do here is to sort all the active accounts to the start of the list. This means that if both accounts are active or both are something else, they are equal. If one account is active, that is considered smaller.

LoanAccountData loanAccountData1 = (LoanAccountData) o1;
LoanAccountData loanAccountData2 = (LoanAccountData) o2;
boolean o1Active = loanAccountData1.getStatusStringValue().equals("Active");
boolean o2Active = loanAccountData2.getStatusStringValue().equals("Active");
if (o1Active == o2Active) {
    return 0;
} else if (o1Active) {
    return -1;
} else {
    return 1;
}


问:
Error #1062 Mysql Duplicate Entry for the key primary
I have big MySql table 'docs' (above 3 000 000 rows).

This table have column id --- primary key unsigned and did ----- unsigned.

Sometimes some rows deleted. But I need that autoincrement go 1234 and not 1479.

I perform sql request:

```<code>update docs set id=@num:=@num+1 where 0 in(select @num:=0)
</code>```

and receive error #1062.

2 questions:
1. Why I have duplicate entry for the key primary?
2. How I can delete them?

答:
My idea is more easy (remove and add primary):

ALTER TABLE docsDROP id;

ALTER TABLE docs ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id);

Body:
I have big MySql table 'docs' (above 3 000 000 rows).

This table have column id --- primary key unsigned and did ----- unsigned.

Sometimes some rows deleted. But I need that autoincrement go 1234 and not 1479.

I perform sql request:

update docs set id=@num:=@num+1 where 0 in(select @num:=0)

and receive error #1062.

2 questions:
1. Why I have duplicate entry for the key primary?
2. How I can delete them?


问:
python sqlite fetchall not returning correct data type
I am having an issue with having fetchall return being the correct data type. fetchone does work?!?!

```<code>con = sqlite3.connect('test.db', detect_types=sqlite3.PARSE_DECLTYPES)
</code>```

with con:

```<code>cur = con.cursor()
cur.execute("SELECT df1 FROM PLCValues")

rows = cur.fetchall()
#print(rows)
for row in rows:
    print (row)
print(row)
</code>```

Returns

```<code>================= RESTART: C:/Users/zippo/Desktop/Graphit.py =================
(44.64769744873047,)
(44.691650390625,)
(44.691650390625,)
(44.471900939941406,)
(44.64769744873047,)
</code>```

FETCHONE

```<code>con = sqlite3.connect('test.db', detect_types=sqlite3.PARSE_DECLTYPES)
</code>```

with con:

```<code>cur = con.cursor()
cur.execute("SELECT df1 FROM PLCValues")

rows = cur.fetchone()
#print(rows)
for row in rows:
    print (row)
print(row)
</code>```

Returns:

```<code>================= RESTART: C:/Users/zippo/Desktop/Graphit.py =================
44.64769744873047
44.64769744873047
</code>```

答: cur.fetchall() returns a tuple of tuples. According to https://docs.python.org/2/library/sqlite3.html it seems to be returning the correct type. You might want to iterate through individual tuple to get a single element.

Body:
I am having an issue with having fetchall return being the correct data type. fetchone does work?!?!

con = sqlite3.connect('test.db', detect_types=sqlite3.PARSE_DECLTYPES)

with con:

cur = con.cursor()
cur.execute("SELECT df1 FROM PLCValues")

rows = cur.fetchall()
#print(rows)
for row in rows:
    print (row)
print(row)

Returns

================= RESTART: C:/Users/zippo/Desktop/Graphit.py =================
(44.64769744873047,)
(44.691650390625,)
(44.691650390625,)
(44.471900939941406,)
(44.64769744873047,)

FETCHONE

con = sqlite3.connect('test.db', detect_types=sqlite3.PARSE_DECLTYPES)

with con:

cur = con.cursor()
cur.execute("SELECT df1 FROM PLCValues")

rows = cur.fetchone()
#print(rows)
for row in rows:
    print (row)
print(row)

Returns:

================= RESTART: C:/Users/zippo/Desktop/Graphit.py =================
44.64769744873047
44.64769744873047


问:
Django Login with preset single Username and Password
I am trying to create a simple login page, for anyone who has the username and password should be able access to some specific links.

I found some tutorials which teach registration, login, logout using auth templates, but they need me to do user registration first.
I could not find any basic tutorial, which can just help me set a default username and password, without creating a signup page.

I know this question is not specific, but any heads up will be very helpful!

答:
If you don't want to create a signup page, simply don't create it.

Only create a login page.

Another thing, you want to give access to specific links only to those who have a username password,

I do it by this way,

```<code> {% if user.is_authenticated %}
     <li><a href="{% url 'logout' %}"><span class="glyphicon glyphicon-log-out"></span> Sign Out</a></li>
 {% else %}
     <li><a href="{% url 'signup' %}"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
     <li><a href="{% url 'login' %}"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
 {% endif %}
</code>```

Its simple enough. Don't create the signup view and template. Just create the login,logout view and template.

Body:
If you don't want to create a signup page, simply don't create it.

Only create a login page.

Another thing, you want to give access to specific links only to those who have a username password,

I do it by this way,

 {% if user.is_authenticated %}
     <li><a href="{% url 'logout' %}"><span class="glyphicon glyphicon-log-out"></span> Sign Out</a></li>
 {% else %}
     <li><a href="{% url 'signup' %}"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
     <li><a href="{% url 'login' %}"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
 {% endif %}

Its simple enough. Don't create the signup view and template. Just create the login,logout view and template.


问:
Need help in Google Analytics tool on a Windows 10 app that uses Ionic 2
I am using Ionic 2 with Angular 2 as my base. Can anyone suggest me a good analytics tool that can be used that can work for all 3 mobile platforms i.e. Windows, iOS, & Android.

I did check Google Analytics but for some reason it did not work well with Windows 10 app. Is there any other tool that can help me on this.

In case you think Google Analytics is the tool to go for how do I go about using it.

答:
We are using Google firebase for our analytics with Google big query to track the custom events for Android and IOS apps. Ionic provides plugin to integrate with firebase. Its very simple to integrate and use firebase with Ionic. Other than analytics you can use firebase for authentication, storage and database also.

Note : We never worked with windows 10 platform


问:
cpio is not working properly in repacking initrd.lz for live
If I unpack initrd.lz and then repack it without making any changes, then replace it with my new initrd.lz in Casper directory for live CD. It is structed. While packing of initrd I got a warning message as below:

cpio: ./usr/share/plymouth/themes/text.plymouth: Cannot stat: No such file or directory.

Finally my question is, what is the utility to pack and unpack the initrd.lz?

Thanks.

答:
Extract the contents of the initrd:

```<code>  mkdir temp
  cd temp
  lzma -dc -S .lz /mnt/casper/initrd.lz | cpio -id
</code>```

Modify and Repack them into a new initrd:

```<code>  find . | cpio --quiet --dereference -o -H newc | lzma -7 > ~/new-initrd.lz
</code>```

and for the text.plymouth check if the file is present

Body:
Extract the contents of the initrd:

  mkdir temp
  cd temp
  lzma -dc -S .lz /mnt/casper/initrd.lz | cpio -id

Modify and Repack them into a new initrd:

  find . | cpio --quiet --dereference -o -H newc | lzma -7 > ~/new-initrd.lz

and for the text.plymouth check if the file is present


问:
How can I find the measured height of views?
I need to calculate the measured height of my views without measuring all views, because these views contain images fetched from the internet. When I measure the views, they download images to memory and I an catch out of memory exception. I use custom ScrollViews, which work like ListViews, display some part of views and when scroll, add to bottom or top.

How can I calculate the height of all my views without throwing out of memory exceptions?

Or how can I make ListView calculate its height before rendering views?

答:
You can use getLeft(), getTop(), getRight() and getBottom() these method's on view. for more information . see following link
http://developer.android.com/reference/android/view/View.html


问:
Passing an Array to Jade/Pug Route in Express
I'm new to express and pug so forgive me if this is a noob question but how do I pass the array I created in one function to the route that will render the pug template. I ultimately want to loop though the array and render it as a table.

My code - first I create the array from the data received from a file with the lodash map method. *EDIT - added full code structure -

```<code>  fs.readFile(file, 'utf8', function (err, data) {
   if (err) {
   console.log('Error: ' + err);
   return;
   }

  var data = JSON.parse(data);

  var newEventList = data.events.map(events => ({
   id: events.id ,
   name: events.name ,
   venue: events.place.name ,
   address: events.place.location.street + " " +
   events.place.location.city + " " + events.place.location.zip ,
   coverPicture: events.coverPicture ,
   description: events.description ,
   startTime: events.startTime ,
   endTime: events.endTime
   }));
 });
</code>```

So now I have an array of objects called newEventList.

My route for pug is

```<code>app.get('/', function (req, res, newEventList) {
 res.render('index', { title: 'Hey', message: 'Hello there!',
     newEventList
 })
})
</code>```

I added title and message to test my pug template.
in my Pug Template I have

```<code>h1= message
p= newEventList
</code>```

but in the paragraph that is rendered I get a long error message -

```<code>function next(err) { // signal to exit route if (err && err === 'route') { return done(); } // signal to exit router if (err && err === 'router') { return done(err) } var layer = stack[idx++]; if (!layer) { return done(err); } if (layer.method && layer.method !== method) { return next(err); } if (err) { layer.handle_error(err, req, res, next); } else { layer.handle_request(req, res, next); } }
</code>```

What am I doing wrong please?

答:
From your route definition's callback, remove or rename newEventList as your third param.

In your example, newEventList is getting assigned to the done/next callback. Hence you're seeing a function being printed in your paragraph.

```<code>var newEventList = // Whatever value;

app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!',
    newEventList
  })
})
</code>```

Body:
I'm new to express and pug so forgive me if this is a noob question but how do I pass the array I created in one function to the route that will render the pug template. I ultimately want to loop though the array and render it as a table.

My code - first I create the array from the data received from a file with the lodash map method. *EDIT - added full code structure -

  fs.readFile(file, 'utf8', function (err, data) {
   if (err) {
   console.log('Error: ' + err);
   return;
   }

  var data = JSON.parse(data);

  var newEventList = data.events.map(events => ({
   id: events.id ,
   name: events.name ,
   venue: events.place.name ,
   address: events.place.location.street + " " +
   events.place.location.city + " " + events.place.location.zip ,
   coverPicture: events.coverPicture ,
   description: events.description ,
   startTime: events.startTime ,
   endTime: events.endTime
   }));
 });

So now I have an array of objects called newEventList.

My route for pug is

app.get('/', function (req, res, newEventList) {
 res.render('index', { title: 'Hey', message: 'Hello there!',
     newEventList
 })
})

I added title and message to test my pug template.
in my Pug Template I have

h1= message
p= newEventList

but in the paragraph that is rendered I get a long error message -

function next(err) { // signal to exit route if (err && err === 'route') { return done(); } // signal to exit router if (err && err === 'router') { return done(err) } var layer = stack[idx++]; if (!layer) { return done(err); } if (layer.method && layer.method !== method) { return next(err); } if (err) { layer.handle_error(err, req, res, next); } else { layer.handle_request(req, res, next); } }

What am I doing wrong please?

Body:
From your route definition's callback, remove or rename newEventList as your third param.

In your example, newEventList is getting assigned to the done/next callback. Hence you're seeing a function being printed in your paragraph.

var newEventList = // Whatever value;

app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!',
    newEventList
  })
})


问:
Read Chronicle Bytes multiple times and concurrently as stream
I am using Chronicle Bytes version 1.7.22. I would like to use Bytes for off-heap caching and persistence of large media (e.g. images, videos). Currently I am creating the Bytes as follows:

```<code>Bytes.elasticByteBuffer();
</code>```

OR (for persistence)

```<code>MappedBytes.mappedBytes(file, 64);
</code>```

I have used Bytes.outputStream() to write the media content and used Bytes.inputStream() to read the media content. However, I can only read the InputStream once. It does not seem to support reset. How can I read the media content multiple times and concurrently without allocation of extra memory?

答:
I would suggest you upgrade to the latest 1.9.x version though thus wont fix you problem as such it will fix many bugs.

Bytes is intended to be single threaded however with care the underlying bytes can be shared. You need to create a BytesStore whuch has the shared data and wrap thus with a Bytes eg NativeBytes so you can have a thread local pointer to that data.

If you need to share how long the data is you must store that in the underlying bytes using a thread safe operation.

Body:
I am using Chronicle Bytes version 1.7.22. I would like to use Bytes for off-heap caching and persistence of large media (e.g. images, videos). Currently I am creating the Bytes as follows:

Bytes.elasticByteBuffer();

OR (for persistence)

MappedBytes.mappedBytes(file, 64);

I have used Bytes.outputStream() to write the media content and used Bytes.inputStream() to read the media content. However, I can only read the InputStream once. It does not seem to support reset. How can I read the media content multiple times and concurrently without allocation of extra memory?


问:
Select column index in pandas dataframe based on values
I have a csv file like so:

```<code>Id               col1    col2    col3
a                 7.04   0.3     1.2
b                 0.3    1.7     .1
c                 0.34   0.05    1.3
d                 0.4    1.60    3.1
</code>```

I want to convert it to a data frame thresholding on 0.5 . If the values is greater than or equal to 0.5 then the column is counted , otherwise it is not counted.

```<code>Id               classes
a                 col1,col3
b                 col2
c                 col3
d                 col2,col3
</code>```

The closest solution I found is this one. However it deals with single rows, not multiple rows. For multiple rows, the best I have is iterate through all the rows. I need a succinct expression without for loop.

答:
Use set_index first and then numpy.where for extract columns by condition. Last remove empty strings by list comprehension:

```<code>df = df.set_index('Id')
s = np.where(df > .5, ['{}, '.format(x) for x in df.columns], '')
df['new'] = pd.Series([''.join(x).strip(', ') for x in s], index=df.index)
print (df)
    col1  col2  col3         new
Id
a   7.04  0.30   1.2  col1, col3
b   0.30  1.70   0.1        col2
c   0.34  0.05   1.3        col3
d   0.40  1.60   3.1  col2, col3
</code>```

Similar for new DataFrame:

```<code>df1 = pd.DataFrame({'classes': [''.join(x).strip(', ') for x in s],
                    'Id': df.index})
print (df1)
  Id     classes
0  a  col1, col3
1  b        col2
2  c        col3
3  d  col2, col3
</code>```

And if necessary remove empty with ,:

```<code>df1 = pd.DataFrame({'classes': [''.join(x).strip(', ').replace(', ',',') for x in s],
                    'Id': df.index})
print (df1)

  Id    classes
0  a  col1,col3
1  b       col2
2  c       col3
3  d  col2,col3
</code>```

Detail:

```<code>print (s)
[['col1, ' '' 'col3, ']
 ['' 'col2, ' '']
 ['' '' 'col3, ']
 ['' 'col2, ' 'col3, ']]
</code>```

Alternative with apply (slowier):

```<code>df1 = (df.set_index('Id')
         .apply(lambda x: ','.join(x.index[x > .5]), 1)
         .reset_index(name='classes'))
print (df1)
  Id    classes
0  a  col1,col3
1  b       col2
2  c       col3
3  d  col2,col3
</code>```

Body:
I have a csv file like so:

Id               col1    col2    col3
a                 7.04   0.3     1.2
b                 0.3    1.7     .1
c                 0.34   0.05    1.3
d                 0.4    1.60    3.1

I want to convert it to a data frame thresholding on 0.5 . If the values is greater than or equal to 0.5 then the column is counted , otherwise it is not counted.

Id               classes
a                 col1,col3
b                 col2
c                 col3
d                 col2,col3

The closest solution I found is this one. However it deals with single rows, not multiple rows. For multiple rows, the best I have is iterate through all the rows. I need a succinct expression without for loop.

Body:
Use set_index first and then numpy.where for extract columns by condition. Last remove empty strings by list comprehension:

df = df.set_index('Id')
s = np.where(df > .5, ['{}, '.format(x) for x in df.columns], '')
df['new'] = pd.Series([''.join(x).strip(', ') for x in s], index=df.index)
print (df)
    col1  col2  col3         new
Id
a   7.04  0.30   1.2  col1, col3
b   0.30  1.70   0.1        col2
c   0.34  0.05   1.3        col3
d   0.40  1.60   3.1  col2, col3

Similar for new DataFrame:

df1 = pd.DataFrame({'classes': [''.join(x).strip(', ') for x in s],
                    'Id': df.index})
print (df1)
  Id     classes
0  a  col1, col3
1  b        col2
2  c        col3
3  d  col2, col3

And if necessary remove empty with ,:

df1 = pd.DataFrame({'classes': [''.join(x).strip(', ').replace(', ',',') for x in s],
                    'Id': df.index})
print (df1)

  Id    classes
0  a  col1,col3
1  b       col2
2  c       col3
3  d  col2,col3

Detail:

print (s)
[['col1, ' '' 'col3, ']
 ['' 'col2, ' '']
 ['' '' 'col3, ']
 ['' 'col2, ' 'col3, ']]

Alternative with apply (slowier):

df1 = (df.set_index('Id')
         .apply(lambda x: ','.join(x.index[x > .5]), 1)
         .reset_index(name='classes'))
print (df1)
  Id    classes
0  a  col1,col3
1  b       col2
2  c       col3
3  d  col2,col3


问:
How to do parameter encoding in Alamofire 4?
having trouble getting my head around parameter encoding in Alamofire 4. Before I would use the ParameterEncoding enumeration and do something like this:

```<code>Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0
</code>```

However this has since been replaced with the ParameterEncoding protocol:

```<code>public typealias Parameters = [String: Any]

public protocol ParameterEncoding {
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}
</code>```

How could I intergrate this into my current code? How do I encode my current mutableURLRequest?

EDIT:

```<code>static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, Any>, data:Data?, contentType: ContentType, parameterName: String) -> (URLRequestConvertible, Data) {

        var urlRequest = URLRequest(url: URL(string: urlString)!)
        urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
        urlRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue
        let boundaryConstant = "multipart-boundary";
        let multipartContentType = "multipart/form-data;boundary="+boundaryConstant
        urlRequest.setValue(multipartContentType, forHTTPHeaderField: "Content-Type")

        // Create upload data to send
        var uploadData = Data()

        if data != nil {
            // Add multipart data
            uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
            if contentType == .Image_JPEG {
                uploadData.append("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"file.jpeg\"\r\n".data(using: String.Encoding.utf8)!)
                uploadData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
            } else if contentType == .Audio {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "MMyyyyddsshhmmA" // superset of OP's format
                let audioFileName = "recording-\(dateFormatter.string(from: Date())).mp4"
                uploadData.append("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"\(audioFileName)\"\r\n".data(using: String.Encoding.utf8)!)
                uploadData.append("Content-Type: audio/mpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
            }
            uploadData.append(data!)
        }

        // Add parameters
        for (key, value) in parameters {
            uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
            uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!)
        }
        uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!)

        // return URLRequestConvertible and Data
        return (urlRequest, uploadData)
    }
</code>```

When doing a request:

```<code>let urlRequest = urlRequestWithComponents(urlString: url, parameters: parameters, data: imageData, contentType: .Image_JPEG, parameterName: "question_img")

    alamoManager.upload(urlRequest.1, with: urlRequest.0).responseObject { (response: DataResponse<CustomResponse>) in

     //Some code
    }
</code>```

答:
```<code>do {
    let alamofireRequest = try Alamofire.URLEncoding().encode(urlRequest as URLRequestConvertible, with: parameters)
    Alamofire.request(alamofireRequest).response { (dataResponse) in

    }
} catch {

}
</code>```

Body:
having trouble getting my head around parameter encoding in Alamofire 4. Before I would use the ParameterEncoding enumeration and do something like this:

Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0

However this has since been replaced with the ParameterEncoding protocol:

public typealias Parameters = [String: Any]

public protocol ParameterEncoding {
    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}

How could I intergrate this into my current code? How do I encode my current mutableURLRequest?

EDIT:

static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, Any>, data:Data?, contentType: ContentType, parameterName: String) -> (URLRequestConvertible, Data) {

        var urlRequest = URLRequest(url: URL(string: urlString)!)
        urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
        urlRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue
        let boundaryConstant = "multipart-boundary";
        let multipartContentType = "multipart/form-data;boundary="+boundaryConstant
        urlRequest.setValue(multipartContentType, forHTTPHeaderField: "Content-Type")

        // Create upload data to send
        var uploadData = Data()

        if data != nil {
            // Add multipart data
            uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
            if contentType == .Image_JPEG {
                uploadData.append("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"file.jpeg\"\r\n".data(using: String.Encoding.utf8)!)
                uploadData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
            } else if contentType == .Audio {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "MMyyyyddsshhmmA" // superset of OP's format
                let audioFileName = "recording-\(dateFormatter.string(from: Date())).mp4"
                uploadData.append("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"\(audioFileName)\"\r\n".data(using: String.Encoding.utf8)!)
                uploadData.append("Content-Type: audio/mpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
            }
            uploadData.append(data!)
        }

        // Add parameters
        for (key, value) in parameters {
            uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
            uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!)
        }
        uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!)

        // return URLRequestConvertible and Data
        return (urlRequest, uploadData)
    }

When doing a request:

let urlRequest = urlRequestWithComponents(urlString: url, parameters: parameters, data: imageData, contentType: .Image_JPEG, parameterName: "question_img")

    alamoManager.upload(urlRequest.1, with: urlRequest.0).responseObject { (response: DataResponse<CustomResponse>) in

     //Some code
    }