text:
Q: How should I define my XSD to have dynamic types used as elements? I am defining a XSD schema for the SOAP requests to be sent to a Web Service that accepts requests like these:
<generic.GenericObject.configureInstanceWithResult xmlns="xmlapi_1.0">
    [..]
    <configInfo>
        <lte.Cell>
            <actionMask>
                <bit>modify</bit>
            </actionMask>
            <spare1>1</spare1>
        </lte.Cell>
    </configInfo>
</generic.GenericObject.configureInstanceWithResult>
<generic.GenericObject.configureInstanceWithResult xmlns="xmlapi_1.0">
    [...]
    <configInfo>
        <lte.LteNeighboringCellRelation>
            <actionMask>
                <bit>modify</bit>
            </actionMask>
            <cellIndividualOffset>-1</cellIndividualOffset>
        </lte.LteNeighboringCellRelation>
    </configInfo>
</generic.GenericObject.configureInstanceWithResult>

In order to achieve this result, I have tried with this schema definition:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="xmlapi_1.0" xmlns:tns="xmlapi_1.0" elementFormDefault="qualified">

<complexType name="Generic.GenericObject.configureInstanceWithResult">
    <sequence>
        [...]
        <element name="configInfo" type="tns:ConfigInfo" />
    </sequence>
</complexType>

<complexType name="ConfigInfo">
    <sequence>
        <element name="payload" type="anyType" />
    </sequence>
</complexType>

<complexType name="lte.Cell">
    <sequence>
        <element name="spare" type="string" />
    </sequence>
</complexType>

<complexType name="lte.LteNeighboringCellRelation">
    <sequence>
        <element name="qOffsetCell" type="string" />
        <element name="cellIndividualOffset" type="string" />
    </sequence>
</complexType>

<element name="generic.GenericObject.configureInstanceWithResult" type="tns:Generic.GenericObject.configureInstanceWithResult" />

But the result I get is this one:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<generic.GenericObject.configureInstanceWithResult xmlns="xmlapi_1.0">
    <configInfo>
        <payload xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="lte.Cell">
            <spare>-1</spare>
        </payload>
    </configInfo>
</generic.GenericObject.configureInstanceWithResult>

Do you see any way in which I could have xsi:type="lte.Cell" as <lte.Cell> instead of <payload>?
Note: Using anyType in ConfigInfo is no good as <configInfo> gets removed and the request is no longer compliant.

A: As commented, I think that they best approach here is to have any as element in <ConfigInfo>:
<complexType name="ConfigInfo">
    <sequence>
       <any minOccurs="0" maxOccurs="1"/>
    </sequence>
</complexType>

This allows you to have any type of object marked with @XmlRootElementintroduced in your XML.
In this particular case where I had two classes defined in the schema as eligible for "payload", element declarations need to be introduced so they are marked correctly as @XmlRootElement:
<element name="lte.Cell" type="tns:Lte.Cell" />
<element name="lte.LteNeighboringCellRelation" type="tns:Lte.LteNeighboringCellRelation" />

A: Make payload into a global element declaration (preferably with abstract="true"), and create element declarations for lte.Cell and lte.LteNeighboringCellRelation that specify substitutionGroup="payload".


text:
Q: Amplitude of a transfer function I'm looking to calculate the amplitude of a transfer function which is defined in a symbolic way :
T=(1 + 2 I r λ)/(1 - r^2 + 2 I r λ)

I try this, i doesn't work
Assuming[{λ > 0, r > 0}, Simplify[Abs[TAdimen]]] r λ)

Do you have ideas so as to calculate the amplitude of a transfer function in a symbolic manner?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Параллельное выполнение циклов в Python 3 В програмке есть два цикла while, как сделать так, чтобы они работали одновременно?

A: Используйте модуль threading:
from threading import Thread

def f():
    for i in range(3):
        print('Я из функции f и я несу ', i)

def f_2():
    for i in range(3):
        print('Я из функции f_2 и я несу ', i)

th_1, th_2 = Thread(target=f), Thread(target = f_2)

if __name__ == '__main__':
    th_1.start(), th_2.start()
    th_1.join(), th_2.join()

Результат:
Я из функции f и я несу  0
Я из функции f_2 и я несу  0
Я из функции f и я несу  1
Я из функции f_2 и я несу  1
Я из функции f и я несу  2
Я из функции f_2 и я несу  2

A: from asyncio import coroutine, ensure_future, gather, get_event_loop
import time, random

def func1(a):
    while a < 3:
        print('func1', a)
        a += 1
        time.sleep(random.randrange(3))
    return 'func1 = %s' % a

def func2(a):
    while a < 5:
        print('func2', a)
        a += 1
        time.sleep(random.randrange(3))
    return 'func2 = %s' % a

@coroutine
def async_worker(fn, a):
    r = yield from LOOP.run_in_executor(None, fn, a)
    return r

@coroutine
def async_map():
    workers = [ensure_future(async_worker(func1, 0), loop=LOOP),
               ensure_future(async_worker(func2, 0), loop=LOOP)]
    result = yield from gather(*workers, loop=LOOP)
    return result

if __name__ == '__main__':
    LOOP = get_event_loop()
    result = LOOP.run_until_complete(async_map())
    print(result)

out:
func1 0
func2 0
func2 1
func1 1
func2 2
func1 2
func2 3
func2 4
['func1 = 3', 'func2 = 5']

--
def func1():
    a = 0
    while a < 2:
        a += 1
        print('func1', a)
        yield a

def func2():
    b = 0
    while True:
        a = yield
        print('func2', a)
        b += a
        yield b

if __name__ == '__main__':
    fn2 = func2()
    next(fn2)

    for a in func1():
        b = fn2.send(a)
        print('b = %s' % b)
        next(fn2)

out:
func1 1
func2 1
b = 1
func1 2
func2 2
b = 3


text:
Q: FPDF and text wrappig OUTSIDE of cells Everyone, been using FPDF, and would like to render a multicell with some text in it that the rest of the text on the page wraps around.  As it is, if I render a log multicell ad position it on the right of the page, it shows up, but the text won't begin until the cell is finished.  I've done a good amount of searching and can't quite work out a way to make this work.  Ideas?
Thanks in advance!

A: you have to use multicell in fpdf so you can wrap your data i n one column
$pdf->SetXY(10,40);
$pdf->MultiCell(100,7 , "".$row['data'] ,1,'L',false);

it is helpfull


text:
Q: wso2 api - Cannot retrieve response with content type [application/xml] I've created an api which uses http azure function as endpoint and once the api is invoked I return the response of xml type but it throws an error
" <am:description>Cannot retrieve response with content type [application/xml]</am:description>"

when I execute it via WSO2 API dev portal.
could someone help me to figure out where it goes wrong or is there any document for help?
below is my api definition
/processdata:
    post:
      consumes:
        - application/xml
      produces:
        - application/xml
      parameters:
        - in: body
          name: input
          description: Request data
          required: false
          schema:
            type: object
            properties:
              input:
                type: string
      responses:
        '200':
          description: ok

A: It seems that you'll need to debug this situation to move forward. Here are some suggestions:

*

*Review the apim logs to see if that has any more information that might help.

*If 1) didn't help then dig in deeper with Wire Logs.

Use of Wire Logs will allow you to see what the incoming payload load is like before APIM does anything with it. From there you can see if this is really xml or something else like json and adjust things from there.


text:
Q: obtain an authorization token of an endpoint I need to obtain an authorization token of an endpoint that is in an api1, passing a user and password as a parameter, this endpoint would call it from an api2 in spring boot, could someone help me ??

A: you can just provide a RestController endpoint:
@PostMapping(value = "/getToken", consumes = APPLICATION_JSON_VALUE)
public String getToken(HttpServletRequest request, @RequestBody String json)

In this example you can pass a JSON with username/password and any other extra attributes you might need. You can replace the string above with a DTO if you find easier. Another option is to pass the 2 parameters
@PostMapping(value = "/getToken", consumes = APPLICATION_JSON_VALUE)
public String getToken(HttpServletRequest request, @RequestParam String username, @RequestParam String password)


text:
Q: Error on JPA many-to-many relationship between entity table and join table I want a many-to-many relationship between an entity table and a join table. Invoices consist of a set of subscriptions. A subscription can be a part of multiple invoices (e.g. monthly subscription). Subscriptions consist of a user and a service. I am already using the subscriptions table as a join table for the many-to-many relationship between users and services (e.g. a user can subscribe to multiple services and a single service has multiple users). I have a table, "invoice_subscription," with IDs for both the invoice and subscription. Every table has its own ID. Below is the relevant snippet in the invoice object:
@ManyToMany
@JoinTable(
        name = "invoice_subscription",
        joinColumns = @JoinColumn(name = "invoice_id"),
        inverseJoinColumns = @JoinColumn(name = "subscription_id")
)
public Set<Subscription> getSubscriptions() {
    return subscriptions;
}

I am using the following in the subscription object:
@ManyToMany(mappedBy = "subscriptions")
public Set<Invoice> getInvoices() {
    return invoices;
}

For the above, I am receiving the error below:
org.hibernate.MappingException: Foreign key (FKfe5yu82iapjynsdyfitclkri4:invoice_subscription [subscription_id])) must have same number of columns as the referenced primary key (subscription [user_id,service_id])

When I switch to two "@JoinColumn" annotations with the IDs in the error, I get the following error:
org.hibernate.AnnotationException: A Foreign key refering com.example.model.Subscription from com.example.model.Invoice has the wrong number of column. should be 1

I agree with this, but it seems to contradict the previous error. I've read documentation, guides, and other questions, but I have not found any useful information. I'm clearly missing something obvious.


text:
Q: Showing that $f : (0,2)\to \mathbb{S}^1$ defined by $f(x) := e^{2\pi i x}$ is not a covering map I am currently solving exercise 11.9 in the excellent book topological manifolds by John M. Lee.

Let $f : (0,2)\to \mathbb{S}^1$ be defined by $f(x) := e^{2\pi i x}$.
  Show that $f$ is not a covering map.

We do this by showing that $1 \in \mathbb{S}^1$ does not possess an evenly covered neighborhood. Assume that $U$ is an evenly covered neighborhood of $1$. Thus we find $\varepsilon > 0$ such that $B_\varepsilon(1) \subseteq U$. The idea is now to calculate $f^{-1}(U)$. Obviously, we have $$f^{-1}(U) = (0,t) \cup (1 - t, 1 + t) \cup (2 - t,2)$$ for some appropriate choice of $t$. Now it is obvious, that for example $(0,t)$ is not homomorphically mapped onto $U$. I have some problem determining $t$. I mean, we have that $$|e^{2\pi i x} - 1| = 2 - 2\cos(2 \pi x) + \sin^2(2\pi x)$$ but this is a pain to solve. Hence my question:

*

*Is there another way of doing this?

*If no, how can I determine $f^{-1}(U)?$

A: As pointed out above by k.stm, observe that $\left\{ 1\right\} = f^{-1}(1)\not\cong f^{-1}(i) = \left\{ 1/2 , 3/2\right\} $ in which $\not\cong $ means that there is no bijection.
You can follow other ideas as well. For instance, if $g:(0,2)\to \mathbb{S} ^1 $  is a covering map, then it is a universal cover. In particular, it is isomorphic to $\mathbb{R}\to\mathbb{S} ^1 $, $t\mapsto e ^{2\pi i t} $. Thereby the fibres of $g$ need to have infinite elements.
That is to say, every covering map $g:(0,2)\to \mathbb{S} ^1 $ needs to be such that $g^{-1}(x) $ has infinite elements (of course, for every $x\in \mathbb{S} ^1$).


text:
Q: Why is this basic Canvas animation not smooth? The only thing that I do inside the animation loop is update the x and y coordinates but the circle is still not moving as smoothly as it should. This is the fiddle. I am using CraftyJS to animate the circle. Here is the code that does the animation:
.bind("EnterFrame", function (eventData) {
     this.x += this.xDirection;
     this.y += this.yDirection;
     if (this.x < 0) this.xDirection *= -1;
     if (this.y < 0) this.yDirection *= -1;
     if (this.x > (0.96*gWidth)) this.xDirection *= -1;
     if (this.y > (0.96*gHeight)) this.yDirection *= -1;
});

Rest of the calculations are done just once and I don't think just a bunch of multiplications should make the animation lag. Any help on how to make the animation smooth will be appreciated.
I failed to mention earlier that xDirection is equal to 0.005*gWidthand yDirection is equal to 0.005*gHeight. If gWidth is 600 the ball is still moving just 3px. Is it really that fast? I don't want to specify the width in pixels (gWidth is the screen size) because then the gameplay will be different on different devices. Is there some way to move the circle quickly while still keeping the animation smooth?

A: Changing from 'fixed' to 'variable' steptype smoothed things out for me.
After Crafty.init, call Crafty.timer.steptype():
const _step = 20;
Crafty.init(gWidth, gHeight, document.getElementById('game'));
Crafty.timer.steptype('variable', _step);
// ...

You may also want to update your EnterFrame to take in to account time elapsed since the last frame:
.bind("EnterFrame", function (eventData) {
    let dt = eventData.dt;
    this.x += this.xDirection * dt / _step;
    this.y += this.yDirection * dt / _step;
    // ...


text:
Q: C# method out parameter list initialization doesn't works with Clear() I found, that construction
Method(out List<T>list)
{
    list.Clear();      // doesn't allowed to initialyze List<T>list
    list = null;       // is accepted by VSTO, however, is not so good
}

Any suggestion please?

A: You cannot use unassigned parameter withing this method. There is simple rule: use out whether parameter is not initialized or use ref if you pass initialized parameter to method.
This code will run correctly:
void Method<T>(ref List<T> list)
{
    list.Clear();
    list = null;
}

Read more about differencies in this question: What's the difference between the 'ref' and 'out' keywords?

A: If you want to use out semantics, not ref, you have to instantiate your list:
Method(out List<T>list)
{
    list = new List<T>();
}


text:
Q: How to insert multiple images into a single post within a CPT I have created a Custom Post Type to publish multiple images together.
--->>> title <<<---
--->>> image default - thumbnail <<<---
--->>> cotent <<<---
--->>>images<<<---
--->>>images<<<---
.....
The first three sections (title, image default and content) is the basics. Is ready.
I thought about using custom metabox and add each image URL. However, add url by url is nothing intuitive and a lot more work for the user, be it newbie or advanced. Furthermore, the amount will vary pictures can be 1, may be 5 may be 10 and so on....
So, how do I add multiple images within a single post CPT?
The Dashboard would look like this:
--->>> title <<<---
--->>> image default - thumbnail <<<---
--->>> cotent <<<---
--->>> add images<<<---
How can I do this? Be a plugin or direct in function.php.

A: As I understand it, you will need create a meta box with fields and use jQuery to add/remove the image boxes. You can also use jQuery UI to make the fields draggable if you like.
Your meta box code will look something like this
// Fields
$prefix = 'your_prefix_';

$custom_meta_fields = array(
array(
   'label' => 'Gallery Images',
   'desc' => 'Add additional images for this portfolio item.',
   'id' => $prefix.'gallery_images',
   'scope' => array('your_custom_post_type'),
   'type' => 'repeatable_image',
),
);

// Add the Meta Box
function add_custom_meta_box()
{
    $post_types = array('your_custom_post_type', 'page', 'post');
    foreach ($post_types as $post_type) {
        add_meta_box(
            'custom_meta_box', // $id
            'Additional Information', // $title
            'show_custom_meta_box', // $callback
             $post_type,
            'normal', // $context
            'high' // $priority
        );
    }
}
add_action('add_meta_boxes', 'add_custom_meta_box');
// The Callback
function show_custom_meta_box()
{
    global $custom_meta_fields, $post;

// Use nonce for verification
echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
// Begin the field table and loop
echo '
';

    foreach ($custom_meta_fields as $field) {
        //Check if scope matches post type
$scope = $field[ 'scope' ];
        $field_output = false;
        foreach ($scope as $scopeItem) {
            switch ($scopeItem) {
default: {
if ($post->post_type == $scopeItem) {
    $field_output = true;
}
break;
}
}
            if ($field_output) {
                break;
            }
        }
        if ($field_output) {
            // get value of this field if it exists for this post
$meta = get_post_meta($post->ID, $field['id'], true);
            $row = 0;
// begin a table row with
echo '

'.$field['label'].'
';
            switch ($field['type']) {
// text
case 'text':
echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />

'.$field['desc'].'';
break;
// repeatable
case 'repeatable_image':
 echo '+

';
 $i = 0;
 if ($meta) {
     foreach ($meta as $row) {
         echo '
|||
                     <input type="text" class="img_field" name="'.$field['id'].'['.$i.']" id="'.$field['id'].'" value="'.$row.'" size="30" />
                     -
';
         ++$i;
     }
 } else {
     echo '
|||
                 <input class="img_field" type="text" name="'.$field['id'].'['.$i.']" id="'.$field['id'].'" value="" size="30" />
                 -
';
 }
 echo '

     '.$field['desc'].'';
break;
} //end switch
echo '
';
        }
    } // end foreach
echo '
'; // end table
}

// Save the Data
function save_custom_meta($post_id)
{
    global $custom_meta_fields;
// verify nonce
if (!isset($_POST['custom_meta_box_nonce']) || !wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) {
    return $post_id;
}
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return $post_id;
}
// check permissions
if ('page' == $_POST['post_type']) {
    if (!current_user_can('edit_page', $post_id)) {
        return $post_id;
    } elseif (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
}
// loop through fields and save the data
foreach ($custom_meta_fields as $field) {
    $old = get_post_meta($post_id, $field['id'], true);
    if (isset($_POST[$field['id']])) {
        $new = $_POST[$field['id']];
        if ($field['type'] === 'repeatable_ad' || $field['type'] === 'repeatable_image') {
            $new = array_values($new);
        }
    }
    if ($new && $new != $old) {
        update_post_meta($post_id, $field['id'], str_replace('"', "'", $new));
    } elseif ('' == $new && $old) {
        delete_post_meta($post_id, $field['id'], $old);
    }
} // end foreach
}
add_action('save_post', 'save_custom_meta');

and your js will need to be something like this
jQuery(document).on('click', '.img_field', function(e) {

var clicked_field = e.target.name;

var custom_uploader;

    e.preventDefault();

    //If the uploader object has already been created, reopen the dialog
    if (custom_uploader) {
        custom_uploader.open();
        return;
    }

    //Extend the wp.media object
    custom_uploader = wp.media.frames.file_frame = wp.media({
        title: 'Select Image',
        button: {
            text: 'Select Image'
        },
        multiple: false
    });

    //When a file is selected, grab the URL and set it as the text field's value
    custom_uploader.on('select', function() {
        attachment = custom_uploader.state().get('selection').first().toJSON();
        jQuery('input[name="'+ clicked_field +'"]').val(attachment.url);
        jQuery('.custom_preview_image').attr('src', attachment.url);
        jQuery('.custom_media_image').attr('src',attachment.url);
    });

    //Open the uploader dialog
    custom_uploader.open();

});

jQuery('.repeatable-add').click(function() {
    field = jQuery(this).closest('td').find('.custom_repeatable li:last').clone(true);
    fieldLocation = jQuery(this).closest('td').find('.custom_repeatable li:last');
    jQuery('input', field).val('').attr('name', function(index, name) {
        return name.replace(/(\d+)/, function(fullMatch, n) {
            return Number(n) + 1;
        });
    })
    field.insertAfter(fieldLocation, jQuery(this).closest('td'))
    return false;
});

jQuery('.repeatable-remove').click(function(){
    jQuery(this).parent().remove();
    return false;
});

jQuery('.custom_repeatable').sortable({
    opacity: 0.6,
    revert: true,
    cursor: 'move',
    handle: '.sort'
});

I haven't tested this, so let me know if it doesn't work but it should give you a good head start. Having said all that, it's much easier to use ACF or CMB2 to do this sort of thing. Anyway, I hope this helps.

A: As you rightly note storing URL is inconvenient for users. Also it is inconvenient for code, since it is hard to perform such operations as outputting different size of image when URL is all you have. It is rather challenging to do a generic reversal from image URL to its attachment data.
For storage typical practice is to store attachment IDs. They are friendly for storage, querying, output, and resilient to changes like image sizes being replaced.
Unfortunately natively WP only provides interface to store a single image — featured image aka post thumbnail.
For the structure you describe basic approaches would be:

*

*Store thumbnail as featured image and rest of images in content, using native or plugin-extended gallery functionality. This just works and is convenient/familiar to users, but leaves more space for them to break it.

*Implement a custom meta box with custom interface for images. Core is of little help in this, but there are multiple custom field frameworks around that can be helpful, it's obviously a common use case. This makes development more challenging, but interface more specialized and with less room for user error.

A:
                      UPDATED
I got it! I made this way, I created a gallery within the wordpress editor. And with foreach, I took the ID of each image and display in the Loop:
<?php
global $post;
$gallery = get_post_gallery_images( $post );

foreach( $gallery as $image_url ) {
?>

      <a href="<?php echo $image_url ?>" itemprop="contentUrl" data-size="1800x1200" data-index="0">
          <img src="<?php echo $image_url ?>" class="image" itemprop="thumbnail" alt="">

<?php
}
?>

A: Advanced custom field plugin provides this functionality through an additional add on named acf repeater field www.advancedcustomfields.com/resources/repeater
in which you can add the same field multiple times in a post


text:
Q: computed column or indexed view? I have a column part # that can contain many non-alphanumeric characters.  I frequently need to compare part #'s from customers or vendors to our data.  I've been doing this successfully with a user-defined function that returns only alpha-Numeric.  I improved performance by creating a computed column called stripPartNum on an indexed view.  I would like to move this computed column to the table.
I cannot create the computed column as persisted so I can create an index on the column.
Error:
Computed column 'stripPartNum' in table 'inventory' cannot be persisted because the column is non-deterministic.
I created a new user-defined function not using patIndex, but still have the same problem.
Here is the function:
Create FUNCTION [dbo].[anOnly]
(
@string VARCHAR(900)
)
RETURNS VARCHAR(900)

AS
BEGIN

Declare @pos int,@newString varchar(1000),@charAt char(1)
Set @pos = 0
Set @newString = ''

while @pos <= len(@string)
    begin
    Set @charAt = substring(@string,@pos,1)
    if @charAt not like '[^0-9A-Za-z]'
        Set @newString = @newString + @charAt
    Set @pos = @pos + 1
    end

return @newString
END

Why am I able to create an index on the computed column in the view but not on the table?  Is there a solution I am overlooking?

A: Ah, I just found the answer.  My function must be schema bound.


text:
Q: variable does not print in a function as expected I have this:
And I was hoping that in f1() I will be able to access the variable $pid. But my script does not print the value from function f1(). Can you explain that ?
#!/bin/sh

f1()
{
    echo in f1 pid is $pid
}

f2()
{
    sleep 1
    f1
}

f2 &

pid=$!

echo f2 bg pid is $pid

output
f2 bg pid is 15095
in f1 pid is

A: You are assigning pid in the parent process after you've forked f2 into its own process, thus there is no way to access it across processes. You can access your own process' pid as $$.


text:
Q: How do I find all ObjectAs that Don't have an ObjectP? Sounds so simple, but has me stymied:
class A(models.Model):
    various fields

class P(models.Model):
    various fields
    a = models.ForeignKey(A)

object_a = A.objects.get(pk=1)
p_objects = P.objects.filter(a=objecta)    # one way
p_objects = A.p_set.all()                  # other way

to get all the P's that belong object_a is easy.  What I can't figure out is how to get all the A objects that have no associated P object.
I can't reverse the ForeignKey relation because each A might have more than one P.

A: This will work
A.objects.filter(p__isnull=True)


text:
Q: How to view the table structure in workbench in mysql database without quotes I need to view the structure(i.e table scripts without quotes) of tabes from mysql work bench
Thanks

A: You can get the DDL via the context menu for an object. So, right click on e.g. your table and let it send the DDL to your current editor or to the clipboard:

A: R click on table name then click Table inspector. It shows table like columns, indexes, triggers, foreign keys, ... All structure info about table.


text:
Q: Cumulative distribution function in powerlaw distribution I am trying to fit the power law distribution to continuous sample (x) which has a sample size n = 360
I'm using the methodology proposed by Aaron Clauset in the python package
power-law: A Python Package for Analysis of Heavy-Tailed Distributions
My steps for power-law distribution are as follows:

*

*I fix the lower bound (xmin) by myself and estimate the parameter α of the power-law model using ML by applying powerlaw.Fit function. I get α= 2.11 at xmin = 1.89

 fit = powerlaw.Fit(x,discrete=False,xmin=`1.89, xmax=None,verbose=False, fit_method='Likelihood',estimate_discrete=False,discrete_approximation='round',sigma_threshold=None,parameter_range=None,fit_optimizer=None,xmin_distance='D',xmin_distribution='power_law')

*I use the fit.plot_ccdf function to plot the Cumulative distribution function (CCDF).

 ax1 = fit.plot_ccdf(original_data=False,survival=True,linewidth = 3,linestyle = '--',label = 'Obs' ) fit.power_law.plot_ccdf(ax = ax1, color = 'r', linestyle = '--', label = 'powerlaw').
According to the theory mentioned in Aaron Clauset (2009), it seems I can calculate cumulative distribution only for those values where (x> xmin). As you can see in the figure below, here: I plot the ccdf function for values above the xmin.It works perfectly for the values above the threshold (i.e xmin) as shown below.

I want to calculate the cdf also for the values where x < xmin (i.e., for whole distribution).When I use the method proposed by Aaron Clauset (2009) to calculate the exceedance for whole sample. It changes the probability of also large values as shown in Figure 2.

*I tried modifying the equation as ccdf =1- (x)^(1-α) to calculate the CCDF for the whole sample instead of using build in function function ccdf = 1-(x/xmin)^(1-α)  but do not get desired results.
I would appreciate any help regarding this issue. Thanks


text:
Q: Puppeteer: error al obtener url Estoy intentando simular un login a través de puppeteer para poder automatizar una serie de tests os dejo aquí el link a la documentación.
En este login que debo realizar hay 3 pasos:

1.- Rellenar formulario con credenciales, pulsar "Login" -> FUNCIONA OK
2.- Redirección a otra web al hacer login donde se debe pulsar "Continuar" para iniciar sesión -> FUNCIONA OK
3.- Redirección a una última web SIN CONTENIDO, donde en la URL aparece un parámeto con el valor que necesito, de esta forma: "https://XXXXXXX.com?PARAMETRO=MI_VALOR_DESEADO" -> NO OK
Os comparto el código, por motivos de seguridad las URLs no son las reales:
import * as puppeteer from "puppeteer";

const bot = async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

/*PASO 1 - LOGIN*/
    await page.goto('https://access_page_login.com')

    const user = await page.$('#documento');
    await user?.type('USERNAME');

    const password = await page.$('#inputpassword');
    await password?.type('USERPASSWORD');

    let url = await page.url();
    await console.log(url); // --> FUNCIONA OK, IMPRIME BIEN URL

    await page.screenshot({path: '1-credentialsForm.png'}); //  --> FUNCIONA OK, APARECE IMAGEN CON FORM RELLENO

    let btn = await page.$('#loginForm > div > div:nth-child(2) > div > button');

    await Promise.all([
        page.waitForNavigation(),
        btn?.click()
    ]);

/*PASO 2 - CONTINUAR */
    btn = await page.$('body > div > div > div > main > div > div > div._bottom30._display-flex._top30 > button');

    url = await page.url();
    await console.log(url); // --> FUNCIONA OK, IMPRIME BIEN URL

    await page.screenshot({path: '2-continue.png'}); // --> FUNCIONA OK, APARECE IMAGEN CON BTN CONTINUAR

    await Promise.all([
        page.waitForNavigation(),
        btn?.click()
    ]);

/* PASO 3 - OBTENCIÓN PARÁMETRO */
    url = await page.url();
    await console.log(url); // ERROR -> IMPRIME: chrome-error://chromewebdata/

    await page.screenshot({path: '3-end.png'}); // ERROR -> APARECE IMAGEN EN BLANCO

    console.log(await browser.pages());
    await browser.close();

};

bot();

Veo 3 comportamientos que no son los deseados:
1.- No obtengo URL en el paso 3 -> En vez de la URL recibo: chrome-error://chromewebdata/
2.- Screenshot del paso 3 -> Debería obtener un screenshot como este:
[![introducir la descripción de la imagen aquí][1]][1]
Pero obtengo un screenshot en blanco.
3.- Ejecución de console.log(await browser.pages()); obtengo un array de objetos como este:
[
  Page {
    eventsMap: Map(0) {},
    emitter: {
      all: Map(0) {},
      on: [Function: on],
      off: [Function: off],
      emit: [Function: emit]
    }
  },
  Page {
    eventsMap: Map(0) {},
    emitter: {
      all: Map(0) {},
      on: [Function: on],
      off: [Function: off],
      emit: [Function: emit]
    }
  }
]

Es decir, solo está realizando un redireccionamiento. Debería haber 3 Pages.
Destacar que todos los selectores para los botones, los obtengo abriendo las herramientas de desarrollador y copiando el selector directamente.
Además, todo este proceso de login se lo realizo de forma manual, funciona correctamente y sin problemas desde Edge, Chrome, Firefox...
Si has llegado hasta aquí, gracias por molestarte.
Cualquier ayuda es bienvenida, un saludo.
EDIT 1
Si añado la siguiente configuración al launcher:
const browser = await puppeteer.launch({
        headless: false,
        slowMo: 100,
        defaultViewport: {
            width: 1200,
            height: 768
        }
 });

Puedo ir viendo lo que el bot realiza en tiempo real con un navegador que se abre automáticamente. Y aquí SI aparece la URL que necesito, con el parámetro que necesito, pero al intentar obtener la URL, aparece el chrome-error://chromewebdata/
¿A qué se debe este comportamiento? ¿Por qué no puedo recoger la URL con el comando page.url() pero en el navegador que abre el bot en tiempo real SI puedo ver dicha URL?
[1]: https://i.stack.imgur.com/6JW4p.png

A: Hola buenas conseguí dar con la solución.
Os comparto a la solución que llegué por si os es de ayuda:
No fui capaz de conseguir captar la url a la que era redireccionado a través de await page.url(). Para mi caso concreto esta URL también podía obtenerla a través de los headers de una respuesta HTTP, por lo tanto añadí el siguiente bloque de código:
page.on('response', async response => {
    console.log(await response.headers());
  });

Esto tampoco me funcionó, al haber demasiadas peticiones http puppeteer tardaba demasiado en realizar todas las peticiones y recoger sus respuestas, tanto que siempre obtenía un error de timeout. Por lo tanto después de muchos intentos realicé lo siguiente:
 try {
        const browser = await puppeteer.launch({
            headless: false,
            args: ['--headless']
        });
        const page = await browser.newPage();

        await page.goto('https://access_page_login.com');

        const user = await page.$('#documento');
        await user?.type('USERNAME');

        const password = await page.$('#inputpassword');
        await password?.type('USERPASSWORD');

        let btn = await page.$('#loginForm > div > div:nth-child(2) > div > button');

        await Promise.all([
            page.waitForNavigation(),
            btn?.click()
        ]);

        /*****/
        btn = await page.$('body > div > div > div > main > div > div > div._bottom30._display-flex._top30 > button');

        await btn?.click();
        const finalResponse = await page.waitForResponse(async (response) => {
            return response.status() === 303;
        });

        const location = finalResponse.headers().location;// Aquí está la url que necesito

        browser.close();

        return location;
    } catch(e) {
        return e;
    }

Como podéis ver eliminé el código:
await Promise.all([
      page.waitForNavigation(),
      btn?.click()
]);

y lo sustituí por:
await btn?.click();
const finalResponse = await page.waitForResponse(async (response) => {
      return response.status() === 303;
});

Anteriormente parece que puppeteer me redireccionaba demasiado rápido por lo que no llegaba a recoger la URL que necesitaba. A través de la función waitForResponse() obligamos a puppeteer a esperar el tiempo que sea necesario hasta que reciba todas las respuestas a las peticiones HTTP de esta página (incluyendo las que se realizan al hacer click en el botón que redirecciona a la tercera página). Por lo tanto una vez esperamos a todas las peticiones que finalicen, filtramos la que necesitamos por código de estado, en mi caso 303, y BINGO! Obtuve la respuesta, con el header de redireccionamiento, con la URL que necesito.
Fui incapaz de llegar al resultado a través de await page.url() que entiendo que sería la forma más óptima y limpia. Estuve leyendo en muchos foros y parece que las páginas SPA a veces no se comportan como deberían a la hora de obtener redireccionamientos.
Espero que os sea de ayuda.


text:
Q: How to let libpng16.so.16 use libz.so.1 in the local directory ? (Another ZLIB_1.2.9 issue) When I run a django project, I got the following error:
ImportError: /lib64/libz.so.1: version `ZLIB_1.2.9' not found (required by /home/ec2-user/anaconda3/lib/./libpng16.so.16)
I found that that directory /home/ec2-user/anaconda3/lib/./ already contains a correct version of
libz.so.1,
libz.so.1 -> libz.so.1.2.11
But it seems that libpng16.so.16 is using libz.so.1 in /usr/lib64.
How to let libpng16.so.16 use libz.so.1 in the local directory ?
Is this related to Anaconda library setting ?


text:
Q: PayPal Smart Button Debit or Credit Card Functionality- Display Amount We recently added PayPals Smart Buttons to our website and hid or deactivated the PayPal Credit button so that only the blue PayPal and the black Debit or Credit Card remain. When a user pays by clicking on the PayPal button, the user can log onto PayPal or select Pay with Debit or Credit Card (as a Guest Checkout). In both situations, PayPal displays the amount being charged in the upper righthand corner of a new window.
When a user clicks on the black Debit or Credit Card, rather than open into a new window, PayPal expands embedded fields right in the website itself (which is pretty cool).  However, on our configuration it doesn't display the amount being charged.  While we display the amount charged in other places in our website, depending on the size of the users' screens, they often have to scroll up to view such amount.
I'm trying to figure out how to display the amount PayPal will charge if a user clicks on the black Debit or Credit Card (similar to how PayPal displays such amount when the blue PayPal button is selected). PayPal has this information which we display after payment with a pop-up message (and via a follow-up receipt sent by email), but it would give a customer confidence to see something official from PayPal contemporaneously as they click "Pay Now" (especially if the price we've listed isn't viewable because of screen size).
Thanks,

A: The black "Debit or Credit" card button expands inline with the rest of your web page, rather than opening a new window. Since it expands credit card fields inline on your page, it is designed to use minimal space on your page.
There is no option for PayPal to display the amount being charged. Since all this is happening on your page, you can display the amount yourself -- right there, wherever you want to show it. It's your page and you have full control over it.


text:
Q: Shiny DataTable row selection responding to user input I'm having problems selecting a row in a DataTable via user input. I'm using dev versions of Shiny and DT because row selection isn't working in non-dev versions. Specifically, I'm using Shiny '0.13.2.9004' and DT '0.1.56'. Consider this app:
library(DT)
library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textOutput('row'),
      numericInput('selectRow', 'selectRow', 3)
    ),
    mainPanel(
      DT::dataTableOutput('testTable')
    )
  )
)

server <- function(input, output, session) {
  output$testTable <- DT::renderDataTable(iris,
                                          selection = list(mode = 'single',
                                                           target = 'row',
                                                           selected = as.character(input$selectRow)),
                                          server = TRUE)
}

shinyApp(ui = ui, server = server)

When it runs, the third row of testTable is selected because that's the default value of selectRow. But changing the value of selectRow does nothing to the row selection in testTable. Bug? Or am I doing something wrong?

A: The selected option only works for pre-selection. To update selection after table is created, you need to use dataTableProxy and selectRows. Add the following to your server code.
proxy = dataTableProxy("testTable")

observeEvent(input$selectRow, {
    selectRows(proxy, as.numeric(input$selectRow))
})


text:
Q: Testing WPF application with Coded UI I have to test a WPF application using Coded UI and have edited the CodedUITestBuilder.exe.config file to increase the MaxLevelsForItemContainer level to 10 but the changes do not reflect in the TestBuilder itself.

A: Your problem sounds the same as this bug already raised with Microsoft.
There, the user states

I edited the MaxLevelsForItemContainer keys [...but] the CodedUIBuilder still uses the default MaxLevelsForItemContainer.

Microsoft answers:

The behavior is expected per our design. MaxLevelsForItemContainer
  config is applied only on Item containers such as ListBox, ComboBox
  etc. The reason behind this is the items within it could be
  potentially virtualized during playback, so the recorder needs to
  capture the entire hierarchy during recording for it to de-virtualized
  each level and play back properly. In this scenario, there are only
  nested Groups (they do not have ItemContainerPattern support as to
  speak in UIA world). So the config does not apply for over.
The workaround over here is to handcode the test script to add all the
  nested controls in the search hierarchy.


text:
Q: Android manifest package Зачем этот атрибут в манифесте? - package, и что туда нужно писать, а то я вижу люди пишут как хотят

A: Package - полное имя пакета приложения, которое обычно пишут в формате обратного DNS. Может содержать буквы A-Z, a-z, цифры и нижние подчеркивания. Используется этот атрибут для 2 целей:

*

*это имя пакета используется как пространство имен для класса R.java, который используется для доступа к ресурсам приложения. Например, если имя пакета будет com.MyCompany.MySuperApp, то класс R будет создан в com.MyCompany.MySuperApp.R

*также это имя используется для того, чтобы создать полное имя для сущностей внутри манифеста приложения ( таких как Activity, Service, Application)

В общем случае, имя пакета удобно использовать, чтобы объявив его 1 раз в начале манифеста, не указывать полное имя для всех Activity, Service, Application далее по манифесту.
Пример:
Без указания  имени пакета:
<manifest . . . >
<application . . . >
    <service android:name="com.example.project.SecretService" . . . >
        . . .
    </service>
    . . .
</application>

С указанием имени пакета:
<manifest package="com.example.project" . . . >
<application . . . >
    <service android:name=".SecretService" . . . >
        . . .
    </service>
    . . .
</application>

Результат у примеров будет идентичный, только во втором случае не придется каждый раз дублировать имя пакета.
Выбрать себе имя пакета вы можете сами, главное, чтобы оно было уникальным. Одной из частых практик при выборе имени является формат com.ИмяКомпанииИлиРазработчика.НазваниеПриложения в таком случае имя является осмысленным (читаемым) и наверняка будет уникальным. Хотя, если не ошибаюсь, формат не обязательно должен быть reverse-DNS.
Подробней можно почитать в официальной документации по манифесту и конкретно по атрибуту package


text:
Q: Image in text line is slightly offset I'm trying to make a clickable button by treating a hyperlink with CSS and adding a little icon next to it. Everything but one detail works great; namely the icons which are slightly offset from the text on the button. It looks as follows:

As you may see, the white icons (12x12px) on the buttons are slightly higher than the text, touching the CSS borders of the hyperlink, while the rest of the text does not.
I have tried every solution that came to mind, including applying vertical-align to the image elements (which put the icon too close to the LOWER border instead, reversing the situation), but sadly could not get it to just line up with the text in the middle of the element nicely. What should I do?
Code in question:
HTML example of a button:

     {L_LOGIN_LOGOUT}

CSS of the buttons:
.headerlinks {
    margin: 0px 0px;
    font-size: 1.1em;
    line-height: 200%;
}

.headerlinks a img {
}

.headerlinks a {
    white-space: nowrap;
    border: 1px solid #FAE000;
    padding: 1px 4px 2px 4px;
    border-radius: 4px;
    margin: 0px;
    background-color: #000;
    vertical-align: middle;
}

A: Are you using a CSS reset? You can try the following one.
http://meyerweb.com/eric/tools/css/reset/
Also it's better to use a background-image for the icon, and set a position on it.

A: This should work if you add margin-top:2px; to the icon class. This number may need to be shifted by a digit or two.
This will work if you maintain the static font-size.


text:
Q: jQuery - resetting a variable I have a variable in a web page that gets set to a value and is of type string.  When a button is clicked, it calls a function & at the end of the function, I would want to clean up anything that had been set previously.  I have tried using:
$.removeData(myVar);

but it doesn't do anything.   Log statements before & after that statement show that it still has the value & type both before & after the above statement.
Another unused variable has a value of undefined and a type of undefined.  Both these variables happen to be global variables in the page.
How do you reset myVar to its initial state?  I know it ought to be simple, but I'm missing something.  Would appreciate any help.

A: Just assign a value to it. If the initial state was undefined, set it to null. You don't have to do anything fancy with jQuery to kill the value.

A: Well...several possible direct answers.
myVar = undefined;
myVar = null;
delete window.myVar;

HOWEVER, I would question the logic of having the variable be global, but only be used in certain methods. Here's how it might be better to structure (with a random pseudo-example of adding up values from ajax):
addAjaxButton.onClick(function() {
  var counter = 0;
  ajax(function(addition) {
    counter += addition;
    ajax(function(moreAdd) {
      counter += moreAdd;
      alert('Total is ' + counter);
    });
  });
});

In that case, counter doesn't need to be deleted - it will just go out of scope when all AJAX is complete.

A: It sounds like your function is doing some "side effecty" things and you want to undo those things?
This statement

I would want to clean up anything that had been set previously.

Is not the same as this statement

How do you reset myVar to its initial state?

What you actually want to do is copy it to a locally scoped variable and not change the global. This code demonstrates using function parameters and making a copy of the global var locally.
var someGlobal = 1;
someMethod();
someOtherMethod(someGlobal);

function someMethod() {
  var localVar = someGlobal;
  localVar = 2;
}

function someOtherMethod(localVar) {
  localVar = 3;
}

window.console.log(someGlobal);

A: This would be a way to reset the value:
$(myVar).val('');


text:
Q: My external HD is not showing up I have an external HD that I saved all my data on from my old windows setups. I now want to access that info on my ubuntu machine and the drive isn't mounting. I've floated around the help files and I am not finding anything that works.
the drive is firewire LaCie
My jolicloud machine sees it no problem. Ubuntu on the other hand does not.

A: When you had the drive plugged into Windows, did you go to the bottom right hand of the screen and click Remove Hardware?  Drives will not mount unless you plug it back into a Windows PC and then do that step, then plug it back into your Ubuntu PC and it will be recognised and will be accessible for use.

A: So after walking away from my laptop for a while, I came back and out of no where it recognized the HDD. Then it disappeared... Then it came back!
I don't get it, but it's here, and it works.
Thanks.
Perhaps it's the cable, the HDD, or the firewire port?


text:
Q: How do you round a number to two decimal places in C#? I want to do this using the Math.Round function

A: This is for rounding to 2 decimal places in C#:
label8.Text = valor_cuota .ToString("N2") ;

In VB.NET:
 Imports System.Math
 round(label8.text,2)

A: Here's some examples:
decimal a = 1.994444M;

Math.Round(a, 2); //returns 1.99

decimal b = 1.995555M;

Math.Round(b, 2); //returns 2.00

You might also want to look at bankers rounding / round-to-even with the following overload:
Math.Round(a, 2, MidpointRounding.ToEven);

There's more information on it here.

A: I know its an old question but please note for the following differences between Math round and String format round:
decimal d1 = (decimal)1.125;
Math.Round(d1, 2).Dump();   // returns 1.12
d1.ToString("#.##").Dump(); // returns "1.13"

decimal d2 = (decimal)1.1251;
Math.Round(d2, 2).Dump();   // returns 1.13
d2.ToString("#.##").Dump(); // returns "1.13"

A: Had a weird situation where I had a decimal variable, when serializing 55.50 it always sets default value mathematically as 55.5. But whereas, our client system is seriously expecting 55.50 for some reason and they definitely expected decimal. Thats when I had write the below helper, which always converts any decimal value padded to 2 digits with zeros instead of sending a string.
public static class DecimalExtensions
{
    public static decimal WithTwoDecimalPoints(this decimal val)
    {
        return decimal.Parse(val.ToString("0.00"));
    }
}

Usage should be
var sampleDecimalValueV1 = 2.5m;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());

decimal sampleDecimalValueV1 = 2;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());

Output:
2.50
2.00

A: If you'd like a string
> (1.7289).ToString("#.##")
"1.73"

Or a decimal
> Math.Round((Decimal)x, 2)
1.73m

But remember! Rounding is not distributive, ie. round(x*y) != round(x) * round(y). So don't do any rounding until the very end of a calculation, else you'll lose accuracy.

A: One thing you may want to check is the Rounding Mechanism of Math.Round:
http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.

A: Personally I never round anything. Keep it as resolute as possible, since rounding is a bit of a red herring in CS anyway. But you do want to format data for your users, and to that end, I find that string.Format("{0:0.00}", number) is a good approach.

A: You should be able to specify the number of digits you want to round to using Math.Round(YourNumber, 2)
You can read more here.

A: Math.Floor(123456.646 * 100) / 100
Would return 123456.64

A: Wikipedia has a nice page on rounding in general.
All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms.  For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even.  The Ceiling() and Floor() methods are related.
You can round with custom numeric formatting as well.
Note that Decimal.Round() uses a different method than Math.Round();
Here is a useful post on the banker's rounding algorithm.
See one of Raymond's humorous posts here about rounding...

A: // convert upto two decimal places
String.Format("{0:0.00}", 140.6767554);        // "140.67"
String.Format("{0:0.00}", 140.1);             // "140.10"
String.Format("{0:0.00}", 140);              // "140.00"

Double d = 140.6767554;
Double dc = Math.Round((Double)d, 2);       //  140.67

decimal d = 140.6767554M;
decimal dc = Math.Round(d, 2);             //  140.67

=========
// just two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"

can also combine "0" with "#".
String.Format("{0:0.0#}", 123.4567)       // "123.46"
String.Format("{0:0.0#}", 123.4)          // "123.4"
String.Format("{0:0.0#}", 123.0)          // "123.0"

A: Try this:
twoDec = Math.Round(val, 2)

A: If you want to round a number, you can obtain different results depending on: how you use the Math.Round() function (if for a round-up or round-down), you're working with doubles and/or floats numbers, and you apply the midpoint rounding. Especially, when using with operations inside of it or the variable to round comes from an operation. Let's say, you want to multiply these two numbers: 0.75 * 0.95 = 0.7125. Right? Not in C#
Let's see what happens if you want to round to the 3rd decimal:
double result = 0.75d * 0.95d; // result = 0.71249999999999991
double result = 0.75f * 0.95f; // result = 0.71249997615814209

result = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713

As you see, the first Round() is correct if you want to round down the midpoint. But the second Round() it's wrong if you want to round up.
This applies to negative numbers:
double result = -0.75 * 0.95;  //result = -0.71249999999999991
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713

So, IMHO, you should create your own wrap function for Math.Round() that fit your requirements. I created a function in which, the parameter 'roundUp=true' means to round to next greater number. That is: 0.7125 rounds to 0.713 and -0.7125 rounds to -0.712 (because -0.712 > -0.713). This is the function I created and works for any number of decimals:
double Redondea(double value, int precision, bool roundUp = true)
{
    if ((decimal)value == 0.0m)
        return 0.0;

    double corrector = 1 / Math.Pow(10, precision + 2);

    if ((decimal)value < 0.0m)
    {
        if (roundUp)
            return Math.Round(value, precision, MidpointRounding.ToEven);
        else
            return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);
    }
    else
    {
        if (roundUp)
            return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);
        else
            return Math.Round(value, precision, MidpointRounding.ToEven);
    }
}

The variable  'corrector' is for fixing the inaccuracy of operating with floating or double numbers.

A: string a = "10.65678";
decimal d = Math.Round(Convert.ToDouble(a.ToString()),2)

A:   public double RoundDown(double number, int decimalPlaces)
        {
            return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
        }


text:
Q: C# Oracle SQL Connection is extremely slow on large data-sets Thanks for reading!
I'm running into an issue where my connection to Oracle (2.5 million records) starts off 'relatively speedy' and then slows down immensely.
Here's how I'm creating the connection: (This is a synchronization between two databases, my local DB could be Oracle/SQL Server/MySQL--who knows?)
private static void ImportSomeData(string sql, DbConnection connection, int batchSize)
{
        var command = connection.CreateCommand();
        command.CommandText = sql;
        //Throw an exception here if needed
        var results = command.ExecuteReader();

        if (results.HasRows)
        {
          //...read here.
        }
}

The batch size refers to the EntityFramework, I'm holding a connection for ~ 200 rows and then recreating (OutOfMemory errors are quite possible, and I'm just trying to see what our optimal size is. (I should note I've used 200-20000 as batch sizes before recreating the IRepository and it seems to have very little effect other than memory errors on the upper size).
Here's an example of the logs:
[INFO]  [2015-11-24 12:34:21]   Imported 1000 Clients
[INFO]  [2015-11-24 12:34:24]   Imported 2000 Clients
[INFO]  [2015-11-24 12:34:26]   Imported 3000 Clients
[INFO]  [2015-11-24 12:34:29]   Imported 4000 Clients
[INFO]  [2015-11-24 12:34:33]   Imported 5000 Clients
[INFO]  [2015-11-24 12:34:37]   Imported 6000 Clients
[INFO]  [2015-11-24 12:34:41]   Imported 7000 Clients
[INFO]  [2015-11-24 12:34:45]   Imported 8000 Clients
[INFO]  [2015-11-24 12:34:49]   Imported 9000 Clients
[INFO]  [2015-11-24 12:34:55]   Imported 10000 Clients
[INFO]  [2015-11-24 12:35:00]   Imported 11000 Clients
[INFO]  [2015-11-24 12:35:05]   Imported 12000 Clients
[INFO]  [2015-11-24 12:35:11]   Imported 13000 Clients
[INFO]  [2015-11-24 12:35:17]   Imported 14000 Clients
[INFO]  [2015-11-24 12:35:23]   Imported 15000 Clients
[INFO]  [2015-11-24 12:35:30]   Imported 16000 Clients
[INFO]  [2015-11-24 12:35:37]   Imported 17000 Clients
[INFO]  [2015-11-24 12:35:44]   Imported 18000 Clients
[INFO]  [2015-11-24 12:35:51]   Imported 19000 Clients
[INFO]  [2015-11-24 12:35:59]   Imported 20000 Clients
[INFO]  [2015-11-24 12:36:06]   Imported 21000 Clients
[INFO]  [2015-11-24 12:36:14]   Imported 22000 Clients
[INFO]  [2015-11-24 12:36:21]   Imported 23000 Clients
[INFO]  [2015-11-24 12:36:31]   Imported 24000 Clients
[INFO]  [2015-11-24 12:36:42]   Imported 25000 Clients

I'm seeing this behavior on three different systems. If you look closely at the timestamps you'll see that as we move further and further into the resultset the time to process 1000 rows starts to creep up pretty quickly and it doesn't seem to level off. There's obviously a lot of places to start troubleshooting this (and it might not be Oracle) but I'm wondering if there might be a better approach to this (via a cursor/temp table, index...really I'm open to anything here).
--Example from the server:
[INFO]  [2015-11-20 11:09:18]   Imported 1000 Clients
[INFO]  [2015-11-20 11:10:45]   Imported 2000 Clients
...
[INFO]  [2015-11-20 18:06:45]   Imported 508000 Clients
[INFO]  [2015-11-20 18:08:36]   Imported 509000 Clients

Any thoughts on this would be appreciated. I could see a situation where the local connection in the target application is to blame but I see this same behavior over result-sets that already have the records in the database (starting quick and slowing down after the initial push) which is why I'm wondering if there's a better way to pull in this record by record comparison.
I would accept punting the EntityFramework out of the application as an acceptable solution, we were just looking for something that makes the data-import a bit more readable for the client systems. No one here has any other ideas on how to speed this up.
EDIT
Some of the SQL was requested, here's a (not real) example thanks to an NDA:
SELECT
  a.A AS Field1,
  a.B AS Field2,
  CASE a.C
  WHEN 'StringNum2' THEN 1
  WHEN 'StringNum2' THEN 2
   ...
  ELSE -1 AS Field3,
  --Another case statement
  a.D AS Field9
  ...
  a.G AS Field10
FROM
  ImportTableNoJoins a

A: Do you notice any improvement if you ensure Dispose is called?
private static void ImportSomeData(string sql, DbConnection connection, int batchSize)
{
    using(var command = connection.CreateCommand())
    {
        command.CommandText = sql;
        //Throw an exception here if needed
        var results = command.ExecuteReader();

        if (results.HasRows)
        {
          //...read here.
        }
    }
}

Also, could you please show us the SQL command text that you are using?  Here are some ideas on SQL Query optimization: http://www.codeproject.com/Articles/55505/SQL-Query-Optimization-FAQ-Part-With-video-expla
As well, you could try using performance counters to pinpoint the problem in C# code or some sort of tool to profile your Oracle database: http://www.codeproject.com/Articles/42001/NET-Best-Practice-No-Using-performance-counters


text:
Q: Liferay Developer Studio not resolving package com.liferay.portal.upload I'm trying to customize the Liferay Web Forms portlet to accept a file control, and I've just about gotten everything working except for the UploadPortletRequest to handle the actual uploading of the file from the form!
I've got:
import com.liferay.portal.upload.UploadPortletRequestImpl;

and in the compiler output:
[javac] 1. ERROR in C:\Program Files\Liferay Developer Studio\liferay-plugins-sdk-6.0-ee-sp2-20110727\portlets\AZ_WebForms-portlet\docroot\WEB-INF\src\com\liferay\autozone\webform\portlet\AZ_WebForm.java (at line 34)
[javac]     import com.liferay.portal.upload.UploadPortletRequestImpl;
[javac]            ^^^^^^^^^^^^^^^^^^^^^^^^^
[javac] The import com.liferay.portal.upload cannot be resolved

BUT...If I add portal-impl.jar to the Portal Dependency JARs to be able to resolve the class, it won't compile because portal-impl.jar is in WEB-INF/lib!! (and it doesn't like that)
I'm kind of at a loss here. What do I need to do?

A: You can't use anything from portal-impl.jar, unless you use ext environment and you modify Liferay.
From your compiler output I would say that you are writing your own portlet, not customizing existing. Am I wrong?
You must handle upload your self. Yyou can use Apache commons fileupload, it supports portlets.
Pleas see Using FileUpload, specifically Servlets and portlets part


text:
Q: Creating C function blocks in scilab 5.5.2 I have been using scilab version 5.5.2 (64 bit) under Windows 7 (64 bit).
For current project I need to be able to create xcos blocks which behavior
is prescribed by my own C language source code. I have found following
excellent tutorial Tutorial Creating a C Function Block in Scicos.
At first I have installed the MinGw toolbox 0.9.3. The installation seems
to be successful because the function haveacompiler returns true. Then I
have written the source code according to the above mentioned tutorial
// This is the computational function for a scicos model block.
// The model is of a variable-gain integrator with hard high and low limits.

    #include "c:\Program Files\scilab-5.5.2\modules\scicos_blocks\includes\scicos_block4.h"
    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>

    #define r_IN(n, i)  ((GetRealInPortPtrs(blk, n+1))[(i)])
    #define r_OUT(n, i) ((GetRealOutPortPtrs(blk, n+1))[(i)])

    // parameters
    #define Lhi (GetRparPtrs(blk)[0])   // integrator high limit
    #define Llo (GetRparPtrs(blk)[1])   // integrator low limit

    // inputs
    #define in  (r_IN(0,0)) // integrator input
    #define gainp   (r_IN(1,0)) // integrator gain when x > 0
    #define gainn   (r_IN(2,0)) // integrator gain when x <= 0

    // states
    #define X   (GetState(blk)[0])  // integrator state
    #define Xdot    (GetDerState(blk)[0])   // derivative of the integrator output

    // outputs
    #define out (r_OUT(0,0))    // integrator output
    #define Igain   (r_OUT(1,0))    // integrator gain

    // other constants
    #define surf0   (GetGPtrs(blk)[0])
    #define surf1   (GetGPtrs(blk)[1])
    #define surf2   (GetGPtrs(blk)[2])
    #define mode0   (GetModePtrs(blk)[0])

    // if X is greater than Lhi, then mode is 1
    // if X is between Lhi and zero, then mode is 2
    // if X is between zero and Llo, then mode is 3
    // if X is less than Llo, then mode is 4
    #define mode_xhzl   1
    #define mode_hxzl   2
    #define mode_hzxl   3
    #define mode_hzlx   4

    void lim_int(scicos_block *blk, int flag)
    {
        double gain = 0;

        switch(flag)
        {
            case 0:
                // compute the derivative of the continuous time state
                if((mode0 == mode_xhzl && in < 0) || mode0 == mode_hxzl)
                    gain = gainp;
                else if((mode0 == mode_hzlx && in > 0) || mode0 == mode_hzxl)
                    gain = gainn;
                Xdot = gain*in;
            break;

            case 1:
                // compute the outputs of the block
                if(X >=Lhi || X <= Llo)
                    Igain = 0;
                else if (X > 0)
                    Igain = gainp;
                else
                    Igain = gainn;
                out = X;
            break;

            case 9:
                // compute zero crossing surfaces and set modes
                surf0 = X - Lhi;
                surf1 = X;
                surf2 = X - Llo;

                if(get_phase_simulation() == 1)
                {
                    if(surf0 >= 0)
                        mode0 = mode_xhzl;
                    else if(surf2 <= 0)
                        mode0 = mode_hzlx;
                    else if(surf1 > 0)
                        mode0 = mode_hxzl;
                    else
                        mode0 = mode_hzxl;
                }
            break;
        }
    }

After that I have called the function ilib_for_link with following
arguments ilib_for_link('lim_int','lim_int_comp.c',[],"c")
The function returns following output:
ilib_for_link('lim_int','lim_int_comp.c',[],"c")
   Generate a loader file
   Generate a Makefile
   Running the Makefile
   Compilation of lim_int_comp.obj
   Building shared library (be patient)

!------------- Compile file lim_int_comp.c --------------                                !
!                                                                                !
!x86_64-w64-mingw32-gcc.exe -c -DWIN32 -D_MSC_VER -DSTRICT -DFORDLL -I"C:/PROGRA~1/SCILAB!
!     ~1.2/libs/MALLOC/includes" -I"C:/PROGRA~1/SCILAB~1.2/modules/core/includes" -I"C:/P!
!     ROGRA~1/SCILAB~1.2/modules/api_scilab/includes" -I"C:/PROGRA~1/SCILAB~1.2/modules/c!
!     all_scilab/includes" -I"C:/PROGRA~1/SCILAB~1.2/modules/output_stream/includes" -I"C!
!     :/PROGRA~1/SCILAB~1.2/modules/jvm/includes" -I"C:/PROGRA~1/SCILAB~1.2/modules/local!
!     ization/includes" -I"C:/PROGRA~1/SCILAB~1.2/modules/dynamic_link/includes" -I"C:/PR!
!     OGRA~1/SCILAB~1.2/modules/mexlib/includes" -I"C:/PROGRA~1/SCILAB~1.2/modules/time/i!
!     ncludes" -I"C:/PROGRA~1/SCILAB~1.2/modules/windows_tools/includes" -I"C:/PROGRA~1/S!
!     CILAB~1.2/libs/f2c" -I"C:/PROGRA~1/SCILAB~1.2/libs/hashtable" -I"C:/PROGRA~1/SCILAB!
!     ~1.2/libs/intl" -m64   lim_int_comp.c                                              !
!                                                                                !
!lim_int_comp.c: In function 'lim_int':                                                  !
!                                                                                !
!lim_int_comp.c:76:7: warning: implicit declaration of function 'get_phase_simulation' [-!
!     Wimplicit-function-declaration]                                                    !
!                                                                                !
!    if(get_phase_simulation() == 1)                                                     !
!                                                                                !
!       ^~~~~~~~~~~~~~~~~~~~                                                             !
!                                                                                !
!------------- Link files --------------                                                 !
!                                                                                !
!x86_64-w64-mingw32-gcc.exe --shared lim_int_comp.o  -L"c:\cygwin64\x86_64-w64-mingw32\li!
!     b" -LC:\Users\Stepan\AppData\Roaming\Scilab\scilab-5.5.2\mingwlib_x64 -lstdc++ -lgf!
!     ortran -lMALLOC -lblasplus -lf2c -llapack -lcore -lcore_f -lintersci -loutput_strea!
!     m -ldynamic_link -linteger -loptimization_f -ljvm -lscilocalization -lintl -llinpac!
!     k_f -lcall_scilab -ltime -lapi_scilab -lscilab_windows -lscicos -lscicos_blocks -ls!
!     cicos_blocks_f -lscicos_f -o liblim_int.dll  -Wl,--out-implib=liblim_int.a -Wl,--ex!
!     port-all-symbols -Wl,--enable-auto-import -Wl                                      !
!                                                                                !
!x86_64-w64-mingw32-gcc.exe: error: unrecognized command line option '-Wl'; did you mean !
!     '-W'?                                                                              !
!                                                                                !
!Makelib:102: recipe for target 'liblim_int.dll' failed                                  !
!                                                                                !
!make: *** [liblim_int.dll] Error 1                                                      !
 !--error 10000
ilib_compile: Error while executing Makelib.
at line      25 of function dlwCompile called by :
at line      51 of function ilib_compile called by :
at line      94 of function ilib_for_link called by :
ilib_for_link('lim_int','lim_int_comp.c',[],"c")

It seems to me that the problem is that prototype for get_phase_simulation function is
missing. Has anybody already encountered this problem? Thanks for any suggestions.

A: It seems that the error is not due to the missing prototype (just a warning) but to the -Wl argument of x86_64-w64-mingw32-gcc.exe


text:
Q: When uploading a picture with carrierwave and dropzone, render a thumbnail version Im using carrierwave and dropzone to upload some pictures to a album.
Everything is working fine, except that, when I add a new picture to the album, it re-renders the file without the thumbnail size.
My controller is like this:
class MediaContentsController < ApplicationController

  def index
    @media_contents = Media.all
  end

  def create
    @media = Media.new(file_name: params[:file])
    @album = Album.find(params[:album])
    @media.album = @album
    if @media.save!
      render json: @media
    else
      render json: { error: 'Failed to process' }, status: 422
    end
  end
end

class MediaUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

   version :thumb do
     process :resize_to_fill => [50, 50]
   end
end

And in my view:
<% if media_contents.empty? %>

No Media Found

<% else %>
  <% media_contents.each do |media| %>

        <%= image_tag media.file_name_url(:thumb) %>

            <%= check_box_tag 'media_contents[]', media.id %>

  <% end %>
<% end %>

So, in my view the image is being shown in full size (not in thumbnail). I suspect about this line:
 render json: @media

I already try to do
render json: @media.file_name_url(:thumb)

But If I do this it doesnt show nothing at all.
Any help?

A: Yes I have gone through the below tutorial
Image uploading using carrierwave
That does work for me just try to change your view some thing like that
<% if media_contents.empty? %>

No Media Found

<% else %>
  <% media_contents.each do |media| %>

        <%= image_tag media.thumb.url %>

            <%= check_box_tag 'media_contents[]', media.id %>

  <% end %>
<% end %>


text:
Q: Eliminating temp var use when accessing a multidimensional array element Is there a way to address array object's field with its coordinates in one line?
I have this array: Tile[,] Tiles. Whenever I need to change one of the tiles and I know the indices beforehand, I just do it like this: Tiles[1, 2] = new Tile(args);.
But when I have to calculate them, it looks like this:
Point p = GetTargetTileIndices(args);
Tiles[p.X, p.Y].someField = 127;

Storing tile's indices each time in a temp variable gets confusing and sometimes hard to read. Is there a way to get the indices as Point or something else and work with target array element in one line?

UPD: It is now clear to me that doing…
var tile = GetTile(point);
tile.field = value;

…does not change the tile in the array, but…
GetTile(point).field = value;

…does!

A: Create a GetTargetTile helper method... just like your GetTargetTileIndices but instead of a Point it returns the actual Tile

A: Just write your own method:
public static class Extensions
{
    public static T GetValue<T>(this T[,] array, Point point)
    {
        return array[point.X, point.Y];
    }

    public static void SetValue<T>(this T[,] array, Point point, T value)
    {
        array[point.X, point.Y] = value;
    }
}

Note that here if Tiles is a value type (struct) then you'll get back a copy from this method, so modifying one of it's properties will be modifying a copy and won't be helpful.
Using this method your code simply becomes:
Tiles.GetValue(GetTileIndices()).byte = 8;


text:
Q: CSS How to put a border around the entire nav bar https://jsfiddle.net/gnpoy2jc/
I would like to make a border around the entire nav element. Not each individual a tag. I can't seem to get it to work
HTML

                    ABOUT
                    MINISTRIES
                    EVANGELSTS
                    RESOURCES

CSS
.bigBar a {
  padding: 10px 15px;
  text-align: center;
  color: white;
  text-decoration: none;
  float: left;
  width: 15%;
  background: #933737; }

A: You need to add a border to the container element so in your case .bigBar. Since your child elements are float: left; You'll need to apply a clearfix. Therefore add this to your css:
.bigBar{
  border: 10px solid black;
}

.bigBar:after{
  content: "";
  display: table;
  clear: both;
}

A: Because you are putting the border around every  element. Remove the 'a' in your CSS and it should work.
.bigBar {
    border:1px solid;
}

Well, I see you didn't specify a border so also add border:1px solid;

A: try this, you can modify both width values to adjust it yo your page
.bigBar{
  display: inline-block;
  border: 2px solid black;
  width: 100%;
}
.bigBar a {
  padding: 10px 15px;
  text-align: center;
  color: white;
  text-decoration: none;
  float: left;
  width: 15%;
  background: #933737; }


text:
Q: selenium wait for certain amount of time and then execute script in python I have some pages which take more than 60s to load so what I want to achieve is to wait for 60s, once the 60s is done close the loading using execute_script("window.stop") or suggest some better way if you have any.
PS - please don't suggest driver.set_page_load_timeout(120)
It is not what I am looking for.
Thanks in Advance

A: wait for certain amount of time
sleep function is provided for such purposes in time module (part of standard library), it accepts value in seconds, so to wait 60 second just do:
import time
time.sleep(60)


text:
Q: Creating (and saving to) an object with a random name I have a function which I use repeatedly. One of the things it returns is a plot visualising effects of a model. I want the function to save the plot to an object, but I want the name of the object to have a random component to it. I use the function multiple times and don't want the plots to overwrite. But I could use the unique identifier in its name to reference it later for the writeup.
So I tried a few things, trying to save a simple object under a partially-random name. All of them  fail because I put a function left from the "<-" sign. I'm not going to give examples, because they are just very very wrong.
So I'd like to have something like:
NAME(randomNumber) <- "some plot"

Which, after running multiple times in a function (with the actual input on the right of course) would result in objects named randomly like
NAME104, NAME314, NAME235, etc.

Is this at all doable?

A: Yes its doable.
Don't do it.
Make a LIST of objects. You can use the name as the key in the list. Example:
 plots = list()
 plots[["NAME104"]] = "some plot"
 plots[["NAMEXXX"]] = "some other plot"

Why? Because now it's easy to loop over the plots stored in the list. Its also easy to create the list in a loop in the first place, something like:
 for(i in 1:100){
   data = read.table(paste("data",i,".csv"))
   name = data$name[1] # get name from column in file
   plots[[name]] = plotthing(data)
 }

If you really really want to create a thing with a random name, use assign:
> assign(paste0("NAME",round(runif(1,1,1000))), "hello")
> ls(pattern="NAME*")
[1] "NAME11"  "NAME333" "NAME717" "NAME719"

But really DONT do that.


text:
Q: If $T:V\to W$ is linear, prove that $T(V_{1})$ is a subspace of $W$ and that $\{x\in V: T(x)\in W_{1}\}$ is a subspace of $V$. Let $V$ and $W$ be vector spaces with subspaces $V_{1}$ and $W_{1}$, respectively. If $T:V\to W$ is linear, prove that $T(V_{1})$ is a subspace of $W$ and that $\{x\in V: T(x)\in W_{1}\}$ is a subspace of $V$.
MY ATTEMPT
Since $0_{V}\in V_{1}$, $T(0_{V}) = 0_{W}\in T(V_{1})$.
Let us suppose that $a\in T(V_{1})$ and $b\in T(V_{1})$. We have to prove that $a + b \in T(V_{1})$ as well as $\alpha a\in T(V_{1})$ where $\alpha\in\textbf{F}$.
Indeed, as a consequence of forward image definition, there are $x\in V_{1}$ and $y\in V_{1}$ such that $a = T(x)$ and $b = T(y)$.
Hence $a + b = T(x) + T(y) = T(x+y)\in T(V_{1})$.
Similarly, $\alpha a = \alpha T(x) = T(\alpha x)\in T(V_{1})$, and we are done with the first part.
Let us solve the second part now.
Indeed, $0_{V}\in\{x\in V: T(x)\in W_{1}\}$. This is because $T(0_{V}) = 0_{W}\in W_{1}$.
If $c,d\in\{x\in V:T(x)\in W_{1}\}$, then $c+d\in\{x\in V:T(x)\in W_{1}\}$ and $\beta c\in\{x\in V:T(x)\in W_{1}\}$.
This is because $T(c+d) = T(c) + T(d)$, $T(\beta c) = \beta T(c)$ and $W_{1}$ is a vector space.
Any comments on my solution? Could someone suggest improvements?

A: A little (nothing essentially, is more like the presentation) improve:

*

*First, $0_W = T(0_V) \in T(V_1)$ because $0_V \in V_1$. Now, let $w_1$ and $w_2$ in $T(V_1)$. This means that there is vectors $v_1$ and $v_2$ in $V_1$ such that $w_1 = T(v_1)$ and $w_2 = T(v_1)$; next, since $V_1$ is a subspace of $V$, for any $\alpha \in \mathbf F$ we have $\alpha v_1 + v_2 \in V_1$, and then
$$\alpha w_1 + w_2 = \alpha T(v_1) + T(v_2) = T(\alpha v_1 + v_2) \in T(V_1).$$

*Observe that $\{x \in V :\, T(x) \in W_1\} = T^{-1}(W_1)$. Right, the zero vector $0_V$ is in $T^{-1}(W_1)$ because $T(0_V) = 0_W \in W_1$. Now, let $v_1$ and $v_2$ two vectors in $T^{-1}(W_1)$, this means that $T(v_1)$ and $T(v_2)$ are in $W_1$, and since $W_1$ is a subspace of $W$, for any $\alpha \in \mathbf F$ we have $T(\alpha v_1 + v_2) = \alpha T(v_1) + T(v_2) \in W_1$, that is, $\alpha v_1 + v_2 \in T^{-1}(W_1)$.


text:
Q: App Visor de PDF Ios en Xcode 10 Pues mi problema es el siguiente. Tengo toda la app realizada con dos Viewcontroller. EL problema es que toda la app se desarrolla bien, menos al mostrar la celda de Pdf en la segunda pantalla que no aparece nada. ¿Qué me puede faltar? Este es el código del segundo ViewController donde tengo puesta una vista web desde el primero, y enlazado por un Segue:
import UIKit
import WebKit
class ViewController2: UIViewController, WKUIDelegate {
@IBOutlet var VistaWebPdf: WKWebView!

var nombrePdfRecibido: String?

var vistaWebPdf: WKWebView!

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    VistaWebPdf = WKWebView(frame: .zero, configuration: webConfiguration)
    VistaWebPdf.uiDelegate = self
    view = VistaWebPdf

    var vistaWebPdf: WKWebView!

    var nombrePdfRecibido:String?
    func viewDidLoad() {
    super.viewDidLoad()

        mostrarPdf()

}

    }

    func mostrarPdf(){

//1 Dirección del archivo PDF
    let nombrePdfRecibido = "PDF"
    let direccionPdf = URL(fileURLWithPath: Bundle.main.path(forResource: nombrePdfRecibido, ofType: "Pdf", inDirectory: "PDF")!)

//2 Transformar archivo PDF a Data
    let datosPdf = try? Data(contentsOf: direccionPdf )

//3 Mostrar Datos en la Vista Web
VistaWebPdf.load(datosPdf!, mimeType: "application/pdf", characterEncodingName: "utf-8", baseURL: direccionPdf)
 }

}
POSTERIORMENTE, PONGO EL CÓDIGO DEL VIEWCONTROLLER 1 unido al Navigation Controller:
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var contenidoCeldas = ["PDF1","PDF2","PDF3","PDF4","PDF5","PDF6","PDF7","PDF8"]
@IBOutlet var tabla: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    tabla.dataSource = self
    tabla.delegate = self

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return contenidoCeldas.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    print(indexPath.section)

    let celda = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier:"CellPDF")
    celda.textLabel?.text = contenidoCeldas[indexPath.row]

    return celda
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    _ = indexPath.row
    self.performSegue(withIdentifier: "Pantalla_2Segue"){

    }
    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "Pantalla_2Segue" {

        let iPdfSeleccionadoRecibido = sender as! NSIndexPath

        let idx = iPdfSeleccionadoRecibido.row
        func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if segue.identifier == "Pantalla_2Segue" {
                let idPdfSeleccionadoRecibido = sender as! NSIndexPath
                let idx = idPdfSeleccionadoRecibido.row

                let objPantalla2:ViewController2 = segue.destination as! ViewController2

    objPantalla2.nombrePdfRecibido = contenidoCeldas[idx]
            }

    }

}

A: Te recomendaria utilizar PDFKit, es una libreria nativa de ios muy sencilla de utilizar introducida por Apple en 2017 (watch?v=V-oy8diDApY)
En tu primera vista ejecuta el segue en el hilo principal de tu programa
Primera vista
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        DispatchQueue.main.async(execute: {
            self.performSegue(withIdentifier: "Pantalla_2Segue", sender: nil)
        })
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == self.mySegue {
            let destination:SegundoView = segue.destination as! SegundoView
            destination.urlDePdf = "url_de_pdf"
        }
}

Segunda vista
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = self.tableView.dequeueReusableCell(withIdentifier: cell_id, for: indexPath) as! MiCustomCell

        let pdfView = PDFView()
        pdfView.frame = cell.frame
        cell.addSubview(pdfView)
        if let document = PDFDocument(url: URL(string: urlDePdf) ?? URL(string:"")!) {
                pdfView.displayMode = .singlePageContinuous
                pdfView.autoScales = true
                pdfView.document = document
        }

        return cell

}


text:
Q: android app exit when select image I am  blocked  my app exit without any notification  when I select images but when I select forum photo or gallery did not crashed.
I use creativesdk for photo edited.
screnshoot

package com.lamba.selfie;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;

import com.aviary.android.feather.sdk.AviaryIntent;

public class MainActivity extends AppCompatActivity {
    private ImageView mResultImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mResultImageView = (ImageView) findViewById(R.id.resultImageView);

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,
                "Select Picture"), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    Uri selectedImageUri = data.getData();
                    Uri imageUri = Uri.parse(getPath(selectedImageUri));
                    Intent imageEditorIntent = new AviaryIntent.Builder(this)
                            .setData(imageUri)
                            .build();
                    startActivity(imageEditorIntent);
                /*case 1:
                    startActivityForResult(imageEditorIntent, 1);
                    Uri mImageUri = data.getData();
                    mResultImageView.setImageURI(mImageUri);
                    break;*/
            }
        }
    }

    public String getPath(Uri uri) {
        // just some safety built in
        if (uri == null) {
            // TODO perform some logging or show user feedback
            return null;
        }
        // try to retrieve the image from the media store first
        // this will only work for images selected from gallery
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        // this is our fallback here
        return uri.getPath();

    }

}

How could I fix it?

A: Source of the issue
You can simplify your switch statement's case 0 a bit and pass selectedImageUri directly to the AviaryIntent's setData() method.
As a result, you won't need your getPath() helper method.
Example code
Below is working code, based on your code above, that will:

*

*Open the image source chooser immediately

*Open the selected image in the Creative SDK Image Editor

*Attach the edited image to the ImageView
See the comments in the example code to find where these things happen.
public class MainActivity extends AppCompatActivity {

    private ImageView mSelectedImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mSelectedImageView = (ImageView) findViewById(R.id.selectedImageView);

        // Open the image source chooser immediately
        Intent galleryIntent = new Intent();
        galleryIntent.setType("image/*");
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(galleryIntent, "Select an image"), 0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                // Open the Creative SDK Image Editor with the chosen image
                case 0:
                    Uri selectedImageUri = data.getData();
                    Intent imageEditorIntent = new AviaryIntent.Builder(this)
                            .setData(selectedImageUri)
                            .build();

                    startActivityForResult(imageEditorIntent, 1);

                    break;

                // Attach the edited image to the ImageView
                case 1:
                    Uri editedImageUri = data.getData();
                    mSelectedImageView.setImageURI(editedImageUri);

                    break;
            }
        }

    }

    // ...
}

A: try to change true to false on your Activity in the manifest file.

android:noHistory="true" to android:noHistory="false"

A: your code : galleryIntent.setAction(Intent.ACTION_GET_CONTENT)
Use this : Intent GalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);


text:
Q: Remote install vbs in Powershell i recently started to learn powershell and this is kinda my first project. I am trying to automated remote installation. I try to look for solution everywhere, but i cant find the right one. Here is the problem:
I need to instal multiple applications that have multiple version on remote computers.
I try few things but nothing worked so far :(
This one worked for me, but only if i don't use variables. If i use them PS (or i guess cscript.exe) does not recognize them.
$hostname = "yourPc"

$app= "app_0001"

$ver = "v1.0.0"

Invoke-Command -ComputerName $hostname -ScriptBlock {cscript.exe \\$hostname\directory\install.vbs /p:$app /v:$ver}

So i basically end up with \\$hostname\directory\install.vbs /p:$app /v:$ver does not exist. Is it possible to this with cscript.exe?
Thanks.

A: The code in the script block win run on the remote computer, so it won't have access to your local variables.
You can either add the using: scope modifier to the variables that you want PowerShell to copy to the remote computer:
Invoke-Command -ComputerName $hostname -ScriptBlock {
  cscript.exe \\$using:hostname\directory\install.vbs /p:$using:app /v:$using:ver
}

... or you can explicitly pass values as parameter arguments to the remote scriptblock via the -ArgumentList parameter:
Invoke-Command -ComputerName $hostname -ScriptBlock {
  param($Path,$Application,$Version)

  cscript.exe \\$Path\directory\install.vbs /p:$Application /v:$Version
} -ArgumentList $hostname,$app,$ver


text:
Q: Prim's Algorithm in C++ implementation with letters This is a working Prim's algorithm taking in three ints. My issue is that my edges are letters, and not numbers. I can't seem to debug it to make it work with char, instead of int, so I am turning to you guys. Any help would be appreciated!
using namespace std;
# define INF 0x3f3f3f3f

// iPair ==>  Integer Pair
typedef pair<int, int> iPair;

// This class represents a directed graph using
// adjacency list representation
class Graph
{
    int V;    // No. of vertices

    // In a weighted graph, we need to store vertex
    // and weight pair for every edge
    list< pair<int, int> > *adj;

public:
    Graph(int V);  // Constructor

    // function to add an edge to graph
    void addEdge(int u, int v, int w);

    // Print MST using Prim's algorithm
    void primMST();
};

// Allocates memory for adjacency list
Graph::Graph(int V)
{
    this->V = V;
    adj = new list<iPair> [V];
}

void Graph::addEdge(int u, int v, int w)
{
    adj[u].push_back(make_pair(v, w));
    adj[v].push_back(make_pair(u, w));
}

// Prints shortest paths from src to all other vertices
void Graph::primMST()
{
    // Create a priority queue to store vertices that
// are being preinMST. This is weird syntax in C++.
// Refer below link for details of this syntax
// http://geeksquiz.com/implement-min-heap-using-stl/
priority_queue< iPair, vector <iPair> , greater<iPair> > pq;

int src = 0; // Taking vertex 0 as source

// Create a vector for keys and initialize all
// keys as infinite (INF)
vector<int> key(V, INF);

// To store parent array which in turn store MST
vector<int> parent(V, -1);

// To keep track of vertices included in MST
vector<bool> inMST(V, false);

// Insert source itself in priority queue and initialize
// its key as 0.
pq.push(make_pair(0, src));
key[src] = 0;

/* Looping till priority queue becomes empty */
while (!pq.empty())
{
    // The first vertex in pair is the minimum key
    // vertex, extract it from priority queue.
    // vertex label is stored in second of pair (it
    // has to be done this way to keep the vertices
    // sorted key (key must be first item
    // in pair)
    int u = pq.top().second;
    pq.pop();

    inMST[u] = true;  // Include vertex in MST

    // 'i' is used to get all adjacent vertices of a vertex
    list< pair<int, int> >::iterator i;
    for (i = adj[u].begin(); i != adj[u].end(); ++i)
    {
        // Get vertex label and weight of current adjacent
        // of u.
        int v = (*i).first;
        int weight = (*i).second;

        //  If v is not in MST and weight of (u,v) is smaller
        // than current key of v
        if (inMST[v] == false && key[v] > weight)
        {
            // Updating key of v
            key[v] = weight;
            pq.push(make_pair(key[v], v));
            parent[v] = u;
        }
    }
}

// Print edges of MST using parent array
for (int i = 1; i < V; ++i)
    printf("%d - %d\n", parent[i], i);
}

I tried changing the typedef pair to <char, char>, and the *adj to <char, char>. The problem arrives in the function addEdge, using the list to create my graph.

A: Your code seems to be taken from here.
When you run the code online there everything works fine.
You can diff your version with the theirs see what went wrong.


text:
Q: pandas sort dataframe by column that includes numbers and letters I need to sort a dataframe by one column, which includes a combination of numbers and letters.
df = [{"user": "seth",
       "name": "1"},
     {"user" : "chris",
       "name": "10A"},
     {"user" : "aaron",
       "name": "4B"},
     {"user" : "dan",
       "name": "10B"}]

My code:
df1 = df.sort_values(by=['name'])

This gets me:
df1 = [{"user": "seth",
       "name": "1"},
     {"user" : "chris",
       "name": "10A"},
     {"user" : "dan",
       "name": "10B"},
     {"user" : "aaron",
       "name": "4B"}]

I want:
df1 =    [{"user": "seth",
           "name": "1"},
         {"user" : "aaron",
           "name": "4B"},
         {"user" : "chris",
           "name": "10A"},
         {"user" : "dan",
           "name": "10B"}]

I had a different question that was flagged as a similar question, and their code:
   df.reindex(index=natsorted(df.name))

It returns a sorted dataframe, but all values have been replaced by NaNs.
  df.iloc(natsorted(df.name))

It raises an error:
TypeError: unhashable type: 'list'

A: To slightly correct Quang's comment, this works fine
import natsort

df1.iloc[natsort.index_humansorted(df1.name)]

A: You can now also do (with pandas >= 1.1.0):
import natsort

sorted_df = df1.sort_values("name", key=natsort.natsort_keygen())

A: you could use a regular expression and extract the numbers + letters, sort them and assign as a categorical column.
s = df["name"].str.extract("(\d+)?(\w|)")
s[0]= s[0].astype(int)

print(s)

   0  1
0   1
1  10  A
2   4  B
3  10  B

df['name'] = pd.Categorical(df['name'],s.sort_values([0,1]).astype(str).agg(''.join,axis=1))

print(df.sort_values('name')

   user name
0   seth    1
2  aaron   4B
1  chris  10A
3    dan  10B

A: Update using pandas 1.1.0+ sort_values now has key parameter:
df = pd.DataFrame([{"user": "seth",
       "name": "1"},
     {"user" : "chris",
       "name": "10A"},
     {"user" : "aaron",
       "name": "4B"},
     {"user" : "dan",
       "name": "10B"}])

df.sort_values('name', key=lambda x: x.str.extract('(\d+)').squeeze().astype(int))

Output:
    user name
0   seth    1
2  aaron   4B
1  chris  10A
3    dan  10B


text:
Q: Convergence results for block coordinate descent methods I am trying to solve the problem
minimize $f(x)$ subject to $x_1 \in C_1, x_2\in C_2, ... x_m\in C_m$
where $x_1, ..., x_m$ are block subvectors of $x$, and $C_i$ are each closed convex sets (not necessarily polyhedral).
I want to use the block coordinate descent algorithm, which cyclically computes
$x_i^+ = \text{argmin}_{u\in C_i} f(\hat x)$
where $\hat x = (x_1,x_2,...,x_{i-1},u,x_{i+1},...,x_m)$.
From Powell's "On Search Directions for Minimization Algorithms", we know that the block coordinate descent method is not guaranteed to converge. But, from Auslender's "Optimisation : méthodes numériques" (which no I have not read this but everyone cites this) we know that if $f(x)$ is strongly convex then this method will converge.
I'd like to be able to understand this concept more intuitively.
1) Does anyone have any intuitive geometric interpretations of Powell's and Auslender's results?
2) what would be an example of a function $f(x)$ which is convex but not strongly convex, in which this method would converge?
3) What would be an example of a function $f(x)$ where the method would converge, but would also stall for a finite number of iterations (which is a phenomena Powell describes, but for a different problem.)
I'd ultimately like to say that if $f(x)$ is strongly convex then the method is guaranteed to converge and not stall, and if $f(x)$ is not strongly convex but is convex, it might either stalls or not converges (and provide a concrete example).
Thanks for any insight!


text:
Q: How to make a nested list to appear like a table with collapsed borders? I have some information with the following semantic structure:
Company
    Project 1
        Monday
            Activity 1
            Activity 2
        Tuesday
            Activity 3
        ...
    Project 2
        Day of the week
            Activity 1...n
Company 2
    ...

And I chose to use lists in the markup because of how the information is related. However, it has to be laid out to appear like a table for printing purposes. I used flexboxes to make it look like so, the only thing is that I can't make the borders to collapse. I can't use tables because the responsive version does lay the information out like a list, and tables break the semantic structure of the information. So the question is:
How can I make it appear like a table (with collapsed borders)? Or is there a better solution for this?
This is how the markup looks:

    Company

        Project 1

Monday

Activities

Activities

Saturday

Activities

Activities

        Project 2

Monday

Activities

Activities

Saturday

Activities

Activities

And the CSS rules I used to lay it out like a table:
/* resest for this example */

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

/* using flex */

.container {
  display: flex;
  flex-direction: column;
}

.projects-container {
  display: flex;
  flex-direction: column;
}

.days-container {
  display: flex;
  flex-direction: row;
}

.activities-container {
  display: flex;
  flex-direction: column;
}

.project-item {
  flex-grow: 1;
}

.day-item {
  flex-grow: 1;
}

.activity-item {
  padding: 10pt;
}

li {
  border: 1px solid silver;
  text-align: center;
}

Here's the jsfiddle. Don't mind the layout at the activities level.

A: Done. I found out that there's not a simple way to do this, instead, the solution was to fiddle with the border rules for each element and changing a couple things on the markup, like surrounding the "headers" with spans with a block display. Here's the final markup:

    Company

        Project 1

            Monday

Activities

Activities

            Saturday

Activities

Activities

        Project 2

            Monday

Activities

Activities

            Saturday

Activities

Activities

Here's the final CSS:
/* resest for this example */

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  text-align: center;
  border-style: solid;
  border-color: grey;
  border-width: 0;
}

span {
  border-style: solid;
  border-color: grey;
}

/* using flex */

#container {
  display: flex;
  flex-direction: column;
  border-width: 0 0 1pt 0;
}

.company-item {
  border-width: 1pt 0 1pt 1pt;
}

.company-title {
  display: block;
  border-width: 0 1pt 0 0;
}

.projects-container {
  display: flex;
  flex-direction: column;
}

.project-item {
  flex-grow: 1;
  border-width: 1pt 0 0 0;
}

.project-title {
  display: block;
  border-width: 0 1pt 0 0;
}

.days-container {
  display: flex;
  flex-direction: row;
}

.day-item {
  flex-grow: 1;
  border-width: 1pt 1pt 0 0;
}

.day-title {
  display: block;
  border-width: 0 0 1pt 0;
}

.activities-container {
  display: flex;
  flex-direction: column;
}

.activity-item {
  padding: 10pt;
}

.activity-item:not(:last-child) {
  border-width: 0 0 1pt 0;
}

Here's the final jsfiddle.