问:
Get address of pixel in bitmap display MIPS
I'm using the bitmap display of the MARS-simulator with unit width 16px, and startaddress $gp.
How would I get the address of a specific pixel using coordinates?

Example (x,y)
I guess I just have to count the amount of pixels until I get to (x,y) and use that as offset on $gp?

Pseudo:

```<code>>ColAmount = 32 #RowLength
>RowAmount = 16 #ColumnHeight
>x = 4
>y = 5
Coordinate = (x, y)
AmountOfPixelsUntilCoordinate = (RowAmount * y) + ColAmount
offset = AmountOfPixelsUntilCoordinate
addressOfPixel = offset($gp)
</code>```

Is this correct? How'd I implement this in MIPS ASM?

答:
You must provide also display size. i.e. 16x16 "unit" with 512x256 "display" means the actual bitmap resolution is 32x16 pixels (512/16, 256/16).

Then the "index of pixel(x, y)" is y * 32 + x => what you have in question. But to get memory offset, you have to accommodate for the size of single pixel, which takes whole word, so offset = 4 * index.

Final memory address is the $gp + offset.

You got it almost right, just the *4 is missing (of course for *4 don't use multiplication, but left shit by 2: sll $<offset_reg>, $<index_reg>, 2).  (and *32 is "shift left by 5")

EDIT: Example of tracking something by (x, y) position (even with custom coordinate system, in this example "x" is same as bitmap 0..31 from left to right, but "y" is from 0..15 from bottom to top (bitmap is 0..15 from top to bottom).

The main part calculating memory offset and drawing pixel into Bitmap is after the comment:

```<code># when ball is on the current row, draw it *now* (to minimize flickering)
</code>```

How to run it: MARS4.5, verify "Delayed branching" is OFF, Tools->Bitmap Display and configure it to: 16x16 unit, 512x256 display (= bitmap size is then 32x16 pixels), and base address as $gp. Compile, run.

```<code>.data
ball_move_x:        .byte   -1
ball_move_y:        .byte   1

.text
.eqv    bounce_pos_y_min    1
.eqv    bounce_pos_y_max    14
.eqv    bounce_pos_x_min    1
.eqv    bounce_pos_x_max    30
.eqv    adjust_y_pos_xor    15
.eqv    ball_colour         0x00d0e0ff

    li      $t1, 0x00ff0000     #Loading RED in register
    li      $t2, 0x00ffff00     #Loading YELLOW in register
    li      $t3, 3              #"ball" x position
    li      $t4, 3              #"ball" y position (0->15 from bottom upward!)
    li      $t5, ball_colour
big_loop:
    # top row + first column
    move    $a0, $gp            # pointer to write to
    li      $a1, 33             # 32 pixels for first row, +1 for left column
    move    $a2, $t2            # yellow
    jal     setPixels
    # 14 red rows with yellow endings+starts
    li      $t0, 14
red_rows_loop:
    li      $a1, 30
    move    $a2, $t1
    jal     setPixels           # set 30 background pixels in middle
    # when ball is on the current row, draw it *now* (to minimize flickering)
    bne     $t4, $t0, skip_ball_draw
    xori    $at, $t4, adjust_y_pos_xor  # y pos goes from BOTTOM! -> flipping it
    # y ($t4) pos goes from bottom to make compare with count-down ($t0) simple
    # after flipping it, the $at has here real bitmap Y pos going 0->15 from top
    sll     $at, $at, 5         # calculate offset in $at: at = y_pos * 32
    add     $at, $at, $t3       # at = y_pos * 32 + x_pos = "index"
    sll     $at, $at, 2         # at = (y_pos * 32 + x_pos)*4 = "offset"
    add     $at, $at, $gp       # at = gp + offset
    sw      $t5, ($at)          # draw it!
    # W: dont't use $at unless you are sure the assembler will not destroy its content
    #    (pseudo instructions often do use it for partial calculations)
skip_ball_draw:
    # draw remaining border + next line border and loop for all lines
    sw      $t2, ($a0)          # set 1 yellow at end, and 1 at start of next row
    sw      $t2, 4($a0)
    addi    $a0, $a0, 8
    addi    $t0, $t0, -1
    bnez    $t0, red_rows_loop
    # finish last row to be full yellow
    li      $a1, 31             # 31 pixels more needed (1 is already there)
    move    $a2, $t2            # yellow
    jal     setPixels
    # update ball position x
    lb      $a0, ball_move_x
    beq     $t3, bounce_pos_x_min, ball_flip_x_dir
    bne     $t3, bounce_pos_x_max, ball_flip_x_dir_skip
ball_flip_x_dir:
    neg     $a0, $a0
    sb      $a0, ball_move_x    # store if flipped
ball_flip_x_dir_skip:
    add     $t3, $t3, $a0       # x += move_x
    # update ball position y
    lb      $a0, ball_move_y
    beq     $t4, bounce_pos_y_min, ball_flip_y_dir
    bne     $t4, bounce_pos_y_max, ball_flip_y_dir_skip
ball_flip_y_dir:
    neg     $a0, $a0
    sb      $a0, ball_move_y    # store if flipped
ball_flip_y_dir_skip:
    add     $t4, $t4, $a0       # y += move_y
    # short delay before next frame, and loop forever
    li      $v0, 32             # MARS service delay(ms)
    li      $a0, 40             # 40ms = ~25 FPS if the draw would be instant
    syscall
    addiu   $t1, $t1, 0xFE0408  # adjust background color (red -2, green +4, blue +8 + overflows (B -> G -> R)
    andi    $t1, $t1, 0xFFFFFF  # force "alpha" to zero
    j       big_loop            # infinite loop will animate colours...

# Sets $a1 pixels to $a2 value starting at $a0 (memory fill)
# a0 = pointer to write to, a1 = count of pixels, a2 = value of pixel to set
# a0 will be updated to point right after the last written word
setPixels:
    sw      $a2, ($a0)      # set pixel (or simply memory word)
    addi    $a0, $a0, 4     # advance memory pointer
    addi    $a1, $a1, -1    # count-down loop
    bnez    $a1, setPixels
    jr      $ra             # return
</code>```

Body:
I'm using the bitmap display of the MARS-simulator with unit width 16px, and startaddress $gp.
How would I get the address of a specific pixel using coordinates?

Example (x,y)
I guess I just have to count the amount of pixels until I get to (x,y) and use that as offset on $gp?

Pseudo:

>ColAmount = 32 #RowLength
>RowAmount = 16 #ColumnHeight
>x = 4
>y = 5
Coordinate = (x, y)
AmountOfPixelsUntilCoordinate = (RowAmount * y) + ColAmount
offset = AmountOfPixelsUntilCoordinate
addressOfPixel = offset($gp)

Is this correct? How'd I implement this in MIPS ASM?

Body:
You must provide also display size. i.e. 16x16 "unit" with 512x256 "display" means the actual bitmap resolution is 32x16 pixels (512/16, 256/16).

Then the "index of pixel(x, y)" is y * 32 + x => what you have in question. But to get memory offset, you have to accommodate for the size of single pixel, which takes whole word, so offset = 4 * index.

Final memory address is the $gp + offset.

You got it almost right, just the *4 is missing (of course for *4 don't use multiplication, but left shit by 2: sll $<offset_reg>, $<index_reg>, 2).  (and *32 is "shift left by 5")

EDIT: Example of tracking something by (x, y) position (even with custom coordinate system, in this example "x" is same as bitmap 0..31 from left to right, but "y" is from 0..15 from bottom to top (bitmap is 0..15 from top to bottom).

The main part calculating memory offset and drawing pixel into Bitmap is after the comment:

# when ball is on the current row, draw it *now* (to minimize flickering)

How to run it: MARS4.5, verify "Delayed branching" is OFF, Tools->Bitmap Display and configure it to: 16x16 unit, 512x256 display (= bitmap size is then 32x16 pixels), and base address as $gp. Compile, run.

.data
ball_move_x:        .byte   -1
ball_move_y:        .byte   1

.text
.eqv    bounce_pos_y_min    1
.eqv    bounce_pos_y_max    14
.eqv    bounce_pos_x_min    1
.eqv    bounce_pos_x_max    30
.eqv    adjust_y_pos_xor    15
.eqv    ball_colour         0x00d0e0ff

    li      $t1, 0x00ff0000     #Loading RED in register
    li      $t2, 0x00ffff00     #Loading YELLOW in register
    li      $t3, 3              #"ball" x position
    li      $t4, 3              #"ball" y position (0->15 from bottom upward!)
    li      $t5, ball_colour
big_loop:
    # top row + first column
    move    $a0, $gp            # pointer to write to
    li      $a1, 33             # 32 pixels for first row, +1 for left column
    move    $a2, $t2            # yellow
    jal     setPixels
    # 14 red rows with yellow endings+starts
    li      $t0, 14
red_rows_loop:
    li      $a1, 30
    move    $a2, $t1
    jal     setPixels           # set 30 background pixels in middle
    # when ball is on the current row, draw it *now* (to minimize flickering)
    bne     $t4, $t0, skip_ball_draw
    xori    $at, $t4, adjust_y_pos_xor  # y pos goes from BOTTOM! -> flipping it
    # y ($t4) pos goes from bottom to make compare with count-down ($t0) simple
    # after flipping it, the $at has here real bitmap Y pos going 0->15 from top
    sll     $at, $at, 5         # calculate offset in $at: at = y_pos * 32
    add     $at, $at, $t3       # at = y_pos * 32 + x_pos = "index"
    sll     $at, $at, 2         # at = (y_pos * 32 + x_pos)*4 = "offset"
    add     $at, $at, $gp       # at = gp + offset
    sw      $t5, ($at)          # draw it!
    # W: dont't use $at unless you are sure the assembler will not destroy its content
    #    (pseudo instructions often do use it for partial calculations)
skip_ball_draw:
    # draw remaining border + next line border and loop for all lines
    sw      $t2, ($a0)          # set 1 yellow at end, and 1 at start of next row
    sw      $t2, 4($a0)
    addi    $a0, $a0, 8
    addi    $t0, $t0, -1
    bnez    $t0, red_rows_loop
    # finish last row to be full yellow
    li      $a1, 31             # 31 pixels more needed (1 is already there)
    move    $a2, $t2            # yellow
    jal     setPixels
    # update ball position x
    lb      $a0, ball_move_x
    beq     $t3, bounce_pos_x_min, ball_flip_x_dir
    bne     $t3, bounce_pos_x_max, ball_flip_x_dir_skip
ball_flip_x_dir:
    neg     $a0, $a0
    sb      $a0, ball_move_x    # store if flipped
ball_flip_x_dir_skip:
    add     $t3, $t3, $a0       # x += move_x
    # update ball position y
    lb      $a0, ball_move_y
    beq     $t4, bounce_pos_y_min, ball_flip_y_dir
    bne     $t4, bounce_pos_y_max, ball_flip_y_dir_skip
ball_flip_y_dir:
    neg     $a0, $a0
    sb      $a0, ball_move_y    # store if flipped
ball_flip_y_dir_skip:
    add     $t4, $t4, $a0       # y += move_y
    # short delay before next frame, and loop forever
    li      $v0, 32             # MARS service delay(ms)
    li      $a0, 40             # 40ms = ~25 FPS if the draw would be instant
    syscall
    addiu   $t1, $t1, 0xFE0408  # adjust background color (red -2, green +4, blue +8 + overflows (B -> G -> R)
    andi    $t1, $t1, 0xFFFFFF  # force "alpha" to zero
    j       big_loop            # infinite loop will animate colours...

# Sets $a1 pixels to $a2 value starting at $a0 (memory fill)
# a0 = pointer to write to, a1 = count of pixels, a2 = value of pixel to set
# a0 will be updated to point right after the last written word
setPixels:
    sw      $a2, ($a0)      # set pixel (or simply memory word)
    addi    $a0, $a0, 4     # advance memory pointer
    addi    $a1, $a1, -1    # count-down loop
    bnez    $a1, setPixels
    jr      $ra             # return


来源: stackexchange

问:
Sending informations from iOS to OSX
I am looking at sending informations from the iPhone/iPad to the Mac. A simple case would be moving a slider on the iPad and returning the value ( say, between 1 and 100 ) to the Mac ( terminal for example ) in any case I assume I'd have to go with wifi or Bluetooth .

Would anybody be able to point me towards which libraries and frameworks I should look at ? Would GameKit accomodate such thing ? Bonjour maybe ?

答:
Bonjour could be used to find the service which I would recommend using and I would use something like an AsyncSocket to establish a connection and send data between them. GameKit would not help you at this time as it is not available on the Mac.

Another option would be to use Bojour to find the service and an NSURLRequest to send/receive data to it, depending on how much and how fast you want to send stuff.

ContentLicense: CC BY-SA 2.5

Title: Sending informations from iOS to OSX


问:
Calculating price from quantity
I making the shops for my site, and but I can't understand why this conde don't wont to work...Here's the code:

```<code><script>
function Price() {
    var Quantity = document.getElementsByClassName('BUY')[0].value;
    var Total = Quantity * 20;
    if (!IsNan(Total)) {

        document.getElementsByClassName('Total').innerHTML = Total;
        document.getElementsByClassName('Quantity').innerHTML = Quantity;
    } else {
        document.getElementsByClassName('Total').innerHTML = "Invalid number";
        document.getElementsByClassName('Quantity').innerHTML = 0
    }
}
</code>```

Here is the html:

```<code><input style="margin-top:1%;" type="text" name="BUY" class="input" maxlength="1000" autocomplete="on" placeholder="Buy " onchange="Price()" required>Price for <span class="Quantity">0</span>Views:<span class="Total">0</span> Satoshis<br>
</code>```

From this code I expect a print of the calculation based on the quantity but  the code don't work and I get no errors...

答: document.getElementsByClassName('BUY') will search for elements having class 'BUY', but ur input has class 'input'

ContentLicense: CC BY-SA 3.0

Title: Calculating price from quantity


问:
Realtime database interaction iOS
I am creating an app where a I want a user notified in app whenever anyone they are following posts a picture. So lets say user A follows user B, when user B posts a picture it appears in realtime on user A's screen. My question is: Is this kind of thing done using push notifications? As in make a request to get the image when notification is received or is it better to be using sockets or queues?</p>

答:
For realtime actions like that you may use google's firebase
also you may use push notifications to send the model which may contain a url of the image and when received load the image and display it,Also same functionality can be accomplished with socketIO

Title: Realtime database interaction iOS


问:
File is downloading without extension?
I am trying to download a PDF file but when i click on the download button it downloads the file without extension. That is there is no PDF extension with the file when i download it!

Action:

```<code>public function executeDownload(sfWebRequest $request) {
        $this->ebook_id = $request->getParameter('ebook', $this->default_ebook);
        $this->ebook = $this->ebooks[$this->ebook_id];

        if (!is_array($this->ebook))
            return;

        // Allow user to download the ebook (and make sure there is no other output)
        $this->setLayout(false);
        sfConfig::set('sf_web_debug', false);
        $content = sfConfig::get('sf_root_dir').'/web'.$this->ebook['ebook'];
        //echo "<p>PDF: $content</p>"; var_export(filesize($content));exit;
        // Check if the file exists
        $this->forward404Unless(file_exists($content));

        // Record the download for this eBook
        $c = new Criteria();
        $c->add(EbookDownloadsPeer::EBOOK_SLUG, $this->ebook_id);
        $ebook = EbookDownloadsPeer::doSelectOne($c);

        $ebook->setLastDownloaded(time());
        $ebook->setEbookDownloads($ebook->getEbookDownloads()+1);
        $ebook->save();

        // Adding the file to the Response object
        $content_type = (in_array($this->ebook_id, array('readyourbody', 'whyamifatigued', 'nutrientsfromfood'))) ? 'application/pdf': 'image/jpeg';

        $this->getResponse()->clearHttpHeaders();
        $this->getResponse()->setHttpHeader('Pragma: public', true);
        $this->getResponse()->setContentType($content_type);
        $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="'.$this->ebook['name'].'"');
        $this->getResponse()->setHttpHeader('Content-Length', filesize($content));
        $this->getResponse()->sendHttpHeaders();
        $this->getResponse()->setContent(readfile($content));

        return sfView::NONE;
    }
</code>```

Template:

```<code> <div class="cyan3 txt-large txt-c">
      <?php echo link_to('Click here','ebooks/download?ebook='.$ebook_id,'') ?> to <?php echo link_to('download it now','ebooks/download?ebook='.$ebook_id,'') ?>!
        </div><br />
    </div>
</code>```

答:
Check the contents of the $this->ebook array and look for a field that holds the file extension. Add this value to the line

$this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="'.$this->ebook['name'] . '"');

so it because something like

$this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="'.$this->ebook['name'] . $this->ebook['extension'].'"');

Title: File is downloading without extension?

Body:
I am trying to download a PDF file but when i click on the download button it downloads the file without extension. That is there is no PDF extension with the file when i download it!

Action:

public function executeDownload(sfWebRequest $request) {
        $this->ebook_id = $request->getParameter('ebook', $this->default_ebook);
        $this->ebook = $this->ebooks[$this->ebook_id];

        if (!is_array($this->ebook))
            return;

        // Allow user to download the ebook (and make sure there is no other output)
        $this->setLayout(false);
        sfConfig::set('sf_web_debug', false);
        $content = sfConfig::get('sf_root_dir').'/web'.$this->ebook['ebook'];
        //echo "
PDF: $content
"; var_export(filesize($content));exit;
        // Check if the file exists
        $this->forward404Unless(file_exists($content));

        // Record the download for this eBook
        $c = new Criteria();
        $c->add(EbookDownloadsPeer::EBOOK_SLUG, $this->ebook_id);
        $ebook = EbookDownloadsPeer::doSelectOne($c);

        $ebook->setLastDownloaded(time());
        $ebook->setEbookDownloads($ebook->getEbookDownloads()+1);
        $ebook->save();

        // Adding the file to the Response object
        $content_type = (in_array($this->ebook_id, array('readyourbody', 'whyamifatigued', 'nutrientsfromfood'))) ? 'application/pdf': 'image/jpeg';

        $this->getResponse()->clearHttpHeaders();
        $this->getResponse()->setHttpHeader('Pragma: public', true);
        $this->getResponse()->setContentType($content_type);
        $this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="'.$this->ebook['name'].'"');
        $this->getResponse()->setHttpHeader('Content-Length', filesize($content));
        $this->getResponse()->sendHttpHeaders();
        $this->getResponse()->setContent(readfile($content));

        return sfView::NONE;
    }

Template:

      <?php echo link_to('Click here','ebooks/download?ebook='.$ebook_id,'') ?> to <?php echo link_to('download it now','ebooks/download?ebook='.$ebook_id,'') ?>!


问:
Icons from Website on Lenovo ThinkPad
This one is a rather weird question, but please help me to find at least a solution or a possibility.

On our website we have some sort of round button with a centered "+", which opens a set of other buttons to the bottom when clicked on.

These popped up buttons only have icons as centered content, each fitting to 24px width and height. For centering we use the method with left: 50% and top:50% as well as transform:translate(-12px,-12px) - the usual centering apart from flexbox methods.

On all our tests these icons where fairly centered (of course there is always some pixel differences with crossbrowser and crossdevice).

Now the last problem remaining is, that on Lenovo ThinkPads (browser of choice) the icons are far off the position they should be; like 5 to 6 pixels to the left or bottom. We could not figure out how we can fix this problem to this day.

On any other device, let it be a Laptop or a PC stationary with the same installed Windows and browsers, it is displaying as intended.

My question now: Does anyone have an idea WHY the Lenovo ThinkPads are displaying these icons differently? Is there something Lenovo ThinkPads are rendering differently or is it the DPI or something else we are just unaware of?

Many thanks for your possible answers.

答:
Hello all interested people,

We've discovered the issue in the font-family: "Material Icons". This CSS adds unnatural behaviour on Lenovo ThinkPads, adding weird whitespace on the right side of some icons.

Thank you for your suggestions and help :) Much appreciated.

Title: Icons from Website on Lenovo ThinkPad


问:
Persisting data in docker's volume for Oracle database
I created volume for storing my application database data - docker volume create dbvolume.

Then I launched my docker container with Oracle XE 11g database image and data volume.

docker run --name=OracleXE --shm-size=1g -p 1521:1521 -p 8080:8080 -e ORACLE_PWD=weblogic1 -v dbvolume:/opt/oracle/oradata oracle/database:11.2.0.2-xe

Stored some entries in database. Stopped and removed container then launched it again, but no data persisted in database.

How can I get persisted data on subsequent requests to application.

答:
from https://github.com/oracle/docker-images/tree/master/OracleDatabase </p>

```<code>-v /opt/oracle/oradata
              The data volume to use for the database.
              Has to be writable by the Unix "oracle" (uid: 54321) user inside the container!
              If omitted the database will not be persisted over container recreation.
</code>```

Body:
from https://github.com/oracle/docker-images/tree/master/OracleDatabase

-v /opt/oracle/oradata
              The data volume to use for the database.
              Has to be writable by the Unix "oracle" (uid: 54321) user inside the container!
              If omitted the database will not be persisted over container recreation.


问:
SQL Select titles of all books that have at least one rating of 4 or higher Titles must be ordered alphabetically
You are given three tables:

```<code>create table books(id int, title varchar(250), year int, author varchar(250));

create table reviewers(id int, name varchar(250));

create table ratings(reviewer_id int, book_id int, rating int, rating_date date);
</code>```

Select titles of all books that have at least one rating of 4 or higher
Titles must be ordered alphabetically.

What is wrong with my statement:

```<code>SELECT title FROM books WHERE id = (SELECT book_id FROM ratings WHERE rating >= 4) ORDER BY title;
</code>```

Desired Results:

```<code>A Tale Of Two Cities
And Then There Were None
Dream of the Red Chamber
She: A History of Adventure
</code>```

Books: sample data

```<code>id  title   year    author
101 A Tale Of Two Cities    1859    Charles Dickens
102 The Lord of the Rings   1955    J. R. R. Tolkien
103 The Hobbit  1937    NULL
104 The Little Prince   1943    Antoine de Saint-Exupéry
</code>```

Reviewers: sample data

```<code>id  name
15201   Joe Martinez
53202   Alice Lewis
44203   John Smith
Ratings: sample data
reviewer_id book_id rating  rating_date
15201   101 2   2015-02-11
15201   101 4   2015-06-16
53202   103 4   NULL
</code>```

答:
You need to either use JOIN:

```<code>SELECT title FROM books b
JOIN ratings r ON b.id = r.book_id
WHERE r.rating >= 4
ORDER BY b.title;
</code>```

Or an 'IN' in WHERE clause of the sub-query:

```<code>SELECT title FROM books WHERE id IN
(SELECT book_id FROM ratings WHERE rating >= 4)
ORDER BY title;
</code>```

reviewers table is irrelevant to the question.

Body:
You are given three tables:

create table books(id int, title varchar(250), year int, author varchar(250));

create table reviewers(id int, name varchar(250));

create table ratings(reviewer_id int, book_id int, rating int, rating_date date);

Select titles of all books that have at least one rating of 4 or higher
Titles must be ordered alphabetically.

What is wrong with my statement:

SELECT title FROM books WHERE id = (SELECT book_id FROM ratings WHERE rating >= 4) ORDER BY title;

Desired Results:

A Tale Of Two Cities
And Then There Were None
Dream of the Red Chamber
She: A History of Adventure

Books: sample data

id  title   year    author
101 A Tale Of Two Cities    1859    Charles Dickens
102 The Lord of the Rings   1955    J. R. R. Tolkien
103 The Hobbit  1937    NULL
104 The Little Prince   1943    Antoine de Saint-Exupéry

Reviewers: sample data

id  name
15201   Joe Martinez
53202   Alice Lewis
44203   John Smith
Ratings: sample data
reviewer_id book_id rating  rating_date
15201   101 2   2015-02-11
15201   101 4   2015-06-16
53202   103 4   NULL

Body:
You need to either use JOIN:

SELECT title FROM books b
JOIN ratings r ON b.id = r.book_id
WHERE r.rating >= 4
ORDER BY b.title;

Or an 'IN' in WHERE clause of the sub-query:

SELECT title FROM books WHERE id IN
(SELECT book_id FROM ratings WHERE rating >= 4)
ORDER BY title;

reviewers table is irrelevant to the question.


问:
OMXPLAYER pause seek for 6secs with --live
When i use the live parameter in my command line like this :

```<code>omxplayer -o hdmi http://www.example.com/video.mp4 --live
</code>```

If I press "p" the video is paused but seek +6s.

I doesn't have the problem when i doesn't use the live parameter.

Thanks.

答:
Use --loop instead of --live
Try this one:

```<code>omxplayer -o hdmi --loop http://www.example.com/video.mp4
</code>```

In my experiences the --live command doesn't do anything at all.

Body:
When i use the live parameter in my command line like this :

omxplayer -o hdmi http://www.example.com/video.mp4 --live

If I press "p" the video is paused but seek +6s.

I doesn't have the problem when i doesn't use the live parameter.

Thanks.

Body:
Use --loop instead of --live
Try this one:

omxplayer -o hdmi --loop http://www.example.com/video.mp4

In my experiences the --live command doesn't do anything at all.


问:
Facebook Share and Like button display same count - that's not right
How come the Share and Like button have the same count?
I just implemented the Like button today and should only have around 2-3 likes.

You can see my problem here: http://www.norwegianfashion.no/news/ofw-forbids-fur-on-the-catwalk/

The code I use is this:

```<code>        <div class="share">
          <div class="face_share">
            <a name="fb_share" type="button_count" href="http://www.facebook.com/sharer.php">Share</a><script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>
          </div>
          <div class="face_like">
            <iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo urlencode(get_permalink($post->ID)); ?>&layout=button_count&show_faces=false&width=130&action=like&colorscheme=light&font=arial" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:130px; height:20px;"></iframe>
          </div>
          <div class="twitter">
            <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="norw_fashion">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
          </div>
        </div>
</code>```

答:
Both functions are doing the same thing now:

Share is still an option, however we merged the external count so that
  the count represents total
  interactions with the URL.

Additionally, ‘like’ still gives you the ability to publish an image
  when a comment is added (through the
  XFBML version).

Source.

Body:
How come the Share and Like button have the same count?
I just implemented the Like button today and should only have around 2-3 likes.

You can see my problem here: http://www.norwegianfashion.no/news/ofw-forbids-fur-on-the-catwalk/

The code I use is this:

            Share

            <iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo urlencode(get_permalink($post->ID)); ?>&layout=button_count&show_faces=false&width=130&action=like&colorscheme=light&font=arial" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:130px; height:20px;">

            Tweet


问:
Flexbox wrap to next line with available space
Using Flexbox I can not seem to make a div wrap to a new line without having it break with previous block content.

I made a codepen to explain:

.container {
  left: 0;
  right: 0;
  margin: auto;
  background-color: grey;
  width: 800px;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}

.lightblue {
  background-color: lightblue;
  width: 300px;
  height: 100px;
  display: block;
}

.lightpink {
  background-color: lightpink;
  width: 300px;
  height: 50px;
}

.red {
  background-color: red;
  width: 300px;
  height: 50px;
}

body {
  margin 0;
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

  <div class="lightblue"></div>
  <div class="lightpink"></div>
  <div class="red"></div>
</div></code>```

What I want is for the red block to display inline, to the right of my lightblue block.

Can you tell me how to achieve this effect?

Thanks!

答:
You can achieve this by adding these 3 lines to your container.

```<code>  flex-direction: column;
  max-height: 100px;
  align-content: flex-start;
</code>```

See the fiddle for working example. https://jsfiddle.net/meercha/yn9gtnpc/1/

Body:
Using Flexbox I can not seem to make a div wrap to a new line without having it break with previous block content.

I made a codepen to explain:

.container {
  left: 0;
  right: 0;
  margin: auto;
  background-color: grey;
  width: 800px;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}

.lightblue {
  background-color: lightblue;
  width: 300px;
  height: 100px;
  display: block;
}

.lightpink {
  background-color: lightpink;
  width: 300px;
  height: 50px;
}

.red {
  background-color: red;
  width: 300px;
  height: 50px;
}

body {
  margin 0;
  width: 100%;
  height: 100%;
}

What I want is for the red block to display inline, to the right of my lightblue block.

Can you tell me how to achieve this effect?

Thanks!

Body:
You can achieve this by adding these 3 lines to your container.

  flex-direction: column;
  max-height: 100px;
  align-content: flex-start;

See the fiddle for working example. https://jsfiddle.net/meercha/yn9gtnpc/1/


问:
Element on focus event listener is not being triggered using element.focus()
Any idea why the event listener is not being triggered in this case?

If I change focus to click, it works fine.

jsfiddle:

https://jsfiddle.net/bobbyrne01/cda3tpfq/

html:

```<code><div id="result">
  No focus.
</div>
</code>```

js:

```<code>var myElement = document.createElement('myElement');
myElement.setAttribute('tabindex', -1);
myElement.addEventListener('focus', function() {
  document.getElementById('result').textContent = 'Focus recieved.';
});

myElement.focus();
</code>```

答:
Assuming you want to update the inner text in the div, something like this should work..

html:

```<code><div id="result" tabindex="-1">no focus</div>
</code>```

js:

```<code>var myElement = document.getElementById('result');
myElement.addEventListener('focus', function() {
    myElement.innerText = 'Focus received.';
},true);
</code>```

Then either manually click on the div to focus or use myElement.focus()

Body:
Any idea why the event listener is not being triggered in this case?

If I change focus to click, it works fine.

jsfiddle:

https://jsfiddle.net/bobbyrne01/cda3tpfq/

html:

  No focus.

js:

var myElement = document.createElement('myElement');
myElement.setAttribute('tabindex', -1);
myElement.addEventListener('focus', function() {
  document.getElementById('result').textContent = 'Focus recieved.';
});

myElement.focus();

Body:
Assuming you want to update the inner text in the div, something like this should work..

html:

<div id="result" tabindex="-1">no focus</div>

js:

var myElement = document.getElementById('result');
myElement.addEventListener('focus', function() {
    myElement.innerText = 'Focus received.';
},true);

Then either manually click on the div to focus or use myElement.focus()


问:
Symfony - Unable to transform value for property path launchdate: Expected a \DateTimeInterface
I'm trying to add a new product with a price containing a launchdate.
This results into the error in the title.

Product.php

```<code>...
public function __construct() {
    $this->clients = new ArrayCollection();
    $this->priceupdates = new ArrayCollection();
    $this->currentPrice = new PriceUpdate();
}
...
</code>```

ProductController.php

```<code>...
public function newAction(Request $request) {
    $entity = new Product();
    $form = $this->createForm(ProductType::class, $entity);
...
</code>```

ProductType.php

```<code>...
public function buildForm(FormBuilderInterface $builder, array $options) {

    $builder
    ->add('description', TextType::class)
    ->add('ProductPriceUpdate', ProductPriceUpdateType::class ,array(
        'data_class' => PriceUpdate::class))
    ->add('clients', EntityType::class, array(
        'class' => 'AppBundle:Client',
        'choice_label' => 'naam',
        'multiple' => true
        ))
    ->add('reset', ResetType::class, array(
        'label' => 'Reset',
        'attr'  => array(
            'class' => 'btn btn-danger'
        )))
    ->add('submit', SubmitType::class, array(
        'label' => 'Create',
        'attr'  => array(
            'class' => 'btn btn-success'
        )));
}
...
</code>```

ProductPriceUpdateType.php

```<code>class ProductPriceUpdateType extends AbstractType {

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
        ->add('price', MoneyType::class)
        ->add('launchdate', DateType::class);
    }
...
}
</code>```

PriceUpdate.php

```<code>public function __construct() {
        $this->launchdate = \DateTime::createFromFormat('m/d/Y', 'now');
</code>```

Stacktrace

```<code>Symfony\Component\Form\Exception\TransformationFailedException:
Unable to transform value for property path "launchdate": Expected a \DateTimeInterface.

  at vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:1107
  at Symfony\Component\Form\Form->normToView(false)
     (vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:350)
  at Symfony\Component\Form\Form->setData(false)
     (vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper.php:49)
  at Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper->mapDataToForms(object(PriceUpdate), object(RecursiveIteratorIterator))
     (vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:383)
  at Symfony\Component\Form\Form->setData(object(PriceUpdate))
     (vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper.php:49)
  at Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper->mapDataToForms(object(Product), object(RecursiveIteratorIterator))
     (vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:383)
  at Symfony\Component\Form\Form->setData(object(Product))
     (vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:487)
  at Symfony\Component\Form\Form->initialize()
     (vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php:226)
  at Symfony\Component\Form\FormBuilder->getForm()
     (vendor\symfony\symfony\src\Symfony\Component\Form\FormFactory.php:30)
  at Symfony\Component\Form\FormFactory->create('AppBundle\\Form\\Type\\ProductType', object(Product), array())
     (vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait.php:331)
  at Symfony\Bundle\FrameworkBundle\Controller\Controller->createForm('AppBundle\\Form\\Type\\ProductType', object(Product))
     (src\AppBundle\Controller\ProductController.php:82)
  at AppBundle\Controller\ProductController->newAction(object(Request))
  at call_user_func_array(array(object(ProductController), 'newAction'), array(object(Request)))
     (vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php:153)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
     (vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php:68)
  at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
     (vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php:169)
  at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
     (web\app_dev.php:29)
  at require('C:\\Users\\rsluimers\\PhpstormProjects\\LunchApp\\LunchApp\\web\\app_dev.php')
     (vendor\symfony\symfony\src\Symfony\Bundle\WebServerBundle\Resources\router.php:42)
</code>```

I don't see anything wrong with it and I don't understand why a \DateTimeInterface is expected.

答:
It looks like 'now' cannot be used for when datetime is created from format and time() has to used instead.

PriceHistory.php

```<code>...
public function __construct() {
    $this->activedate = DateTime::createFromFormat('U', time());
...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add a new product with a price containing a launchdate.
This results into the error in the title.

Product.php

...
public function __construct() {
    $this->clients = new ArrayCollection();
    $this->priceupdates = new ArrayCollection();
    $this->currentPrice = new PriceUpdate();
}
...

ProductController.php

...
public function newAction(Request $request) {
    $entity = new Product();
    $form = $this->createForm(ProductType::class, $entity);
...

ProductType.php

...
public function buildForm(FormBuilderInterface $builder, array $options) {

    $builder
    ->add('description', TextType::class)
    ->add('ProductPriceUpdate', ProductPriceUpdateType::class ,array(
        'data_class' => PriceUpdate::class))
    ->add('clients', EntityType::class, array(
        'class' => 'AppBundle:Client',
        'choice_label' => 'naam',
        'multiple' => true
        ))
    ->add('reset', ResetType::class, array(
        'label' => 'Reset',
        'attr'  => array(
            'class' => 'btn btn-danger'
        )))
    ->add('submit', SubmitType::class, array(
        'label' => 'Create',
        'attr'  => array(
            'class' => 'btn btn-success'
        )));
}
...

ProductPriceUpdateType.php

class ProductPriceUpdateType extends AbstractType {

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
        ->add('price', MoneyType::class)
        ->add('launchdate', DateType::class);
    }
...
}

PriceUpdate.php

public function __construct() {
        $this->launchdate = \DateTime::createFromFormat('m/d/Y', 'now');

Stacktrace

Symfony\Component\Form\Exception\TransformationFailedException:
Unable to transform value for property path "launchdate": Expected a \DateTimeInterface.

  at vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:1107
  at Symfony\Component\Form\Form->normToView(false)
     (vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:350)
  at Symfony\Component\Form\Form->setData(false)
     (vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper.php:49)
  at Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper->mapDataToForms(object(PriceUpdate), object(RecursiveIteratorIterator))
     (vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:383)
  at Symfony\Component\Form\Form->setData(object(PriceUpdate))
     (vendor\symfony\symfony\src\Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper.php:49)
  at Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper->mapDataToForms(object(Product), object(RecursiveIteratorIterator))
     (vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:383)
  at Symfony\Component\Form\Form->setData(object(Product))
     (vendor\symfony\symfony\src\Symfony\Component\Form\Form.php:487)
  at Symfony\Component\Form\Form->initialize()
     (vendor\symfony\symfony\src\Symfony\Component\Form\FormBuilder.php:226)
  at Symfony\Component\Form\FormBuilder->getForm()
     (vendor\symfony\symfony\src\Symfony\Component\Form\FormFactory.php:30)
  at Symfony\Component\Form\FormFactory->create('AppBundle\\Form\\Type\\ProductType', object(Product), array())
     (vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait.php:331)
  at Symfony\Bundle\FrameworkBundle\Controller\Controller->createForm('AppBundle\\Form\\Type\\ProductType', object(Product))
     (src\AppBundle\Controller\ProductController.php:82)
  at AppBundle\Controller\ProductController->newAction(object(Request))
  at call_user_func_array(array(object(ProductController), 'newAction'), array(object(Request)))
     (vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php:153)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
     (vendor\symfony\symfony\src\Symfony\Component\HttpKernel\HttpKernel.php:68)
  at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
     (vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php:169)
  at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
     (web\app_dev.php:29)
  at require('C:\\Users\\rsluimers\\PhpstormProjects\\LunchApp\\LunchApp\\web\\app_dev.php')
     (vendor\symfony\symfony\src\Symfony\Bundle\WebServerBundle\Resources\router.php:42)

I don't see anything wrong with it and I don't understand why a \DateTimeInterface is expected.

Body:
It looks like 'now' cannot be used for when datetime is created from format and time() has to used instead.

PriceHistory.php

...
public function __construct() {
    $this->activedate = DateTime::createFromFormat('U', time());
...


问:
Convert the following into a loop function
I have a small data set and I am trying to subset the data.frame using the grepl function.

I have;

```<code>year_list <- list("2013", "2014", "2015", "2016", "2017")

test.2013 <- subset(searches[, 1:2], grepl(year_list[1], searches$date))
test.2014 <- subset(searches[, 1:2], grepl(year_list[2], searches$date))
test.2015 <- subset(searches[, 1:2], grepl(year_list[3], searches$date))
test.2016 <- subset(searches[, 1:2], grepl(year_list[4], searches$date))
test.2017 <- subset(searches[, 1:2], grepl(year_list[5], searches$date))
</code>```

I am trying to create a loop in order to subset columns 1 to 2 (the date column and hits column) into a new data.frame.

I am trying to take the date in year_lists, apply the grepl function to the column date in the searches data.frame and return these values into a new data.frame but using a loop function or something less repetitive than what I currently have.

Dataframe

```<code>         date hits         keyword   geo gprop category
1: 2013-01-06   23  Price world   web        0
2: 2013-01-13   23  Price world   web        0
3: 2013-01-20   40  Price world   web        0
4: 2013-01-27   25  Price world   web        0
5: 2013-02-03   21  Price world   web        0
6: 2013-02-10   19  Price world   web        0
</code>```

答:
If my understanding is correct that you want to split a data.frame into several data.framess on basis of the entries in the date column, then you might consider the following solution which produces a list of the desired data.frame subsets using split. I have used your data (not as data.table) and introduced two lines representing an additional year. I hope my understanding was correct.

```<code>df <- read.table(text = "
date hits         keyword   geo gprop category
2013-01-06   23  Price world   web        0
2013-01-13   23  Price world   web        0
2013-01-20   40  Price world   web        0
2013-01-27   25  Price world   web        0
2013-02-03   21  Price world   web        0
2013-02-10   19  Price world   web        0
2014-02-03   21  Price world   web        0
2014-02-10   19  Price world   web        0
", header = T, stringsAsFactors = F)

#extract only the four first digits from date column
#to generate splitting groups
df_split <- split(df[, c("date", "hits")], gsub("(\\d{4})(.*$)", "\\1", df$date))

df_split
# $`2013`
#       date    hits
# 1 2013-01-06   23
# 2 2013-01-13   23
# 3 2013-01-20   40
# 4 2013-01-27   25
# 5 2013-02-03   21
# 6 2013-02-10   19
#
# $`2014`
#       date    hits
# 7 2014-02-03   21
# 8 2014-02-10   19
</code>```

Body:
I have a small data set and I am trying to subset the data.frame using the grepl function.

I have;

year_list <- list("2013", "2014", "2015", "2016", "2017")

test.2013 <- subset(searches[, 1:2], grepl(year_list[1], searches$date))
test.2014 <- subset(searches[, 1:2], grepl(year_list[2], searches$date))
test.2015 <- subset(searches[, 1:2], grepl(year_list[3], searches$date))
test.2016 <- subset(searches[, 1:2], grepl(year_list[4], searches$date))
test.2017 <- subset(searches[, 1:2], grepl(year_list[5], searches$date))

I am trying to create a loop in order to subset columns 1 to 2 (the date column and hits column) into a new data.frame.

I am trying to take the date in year_lists, apply the grepl function to the column date in the searches data.frame and return these values into a new data.frame but using a loop function or something less repetitive than what I currently have.

Dataframe

         date hits         keyword   geo gprop category
1: 2013-01-06   23  Price world   web        0
2: 2013-01-13   23  Price world   web        0
3: 2013-01-20   40  Price world   web        0
4: 2013-01-27   25  Price world   web        0
5: 2013-02-03   21  Price world   web        0
6: 2013-02-10   19  Price world   web        0

Body:
If my understanding is correct that you want to split a data.frame into several data.framess on basis of the entries in the date column, then you might consider the following solution which produces a list of the desired data.frame subsets using split. I have used your data (not as data.table) and introduced two lines representing an additional year. I hope my understanding was correct.

df <- read.table(text = "
date hits         keyword   geo gprop category
2013-01-06   23  Price world   web        0
2013-01-13   23  Price world   web        0
2013-01-20   40  Price world   web        0
2013-01-27   25  Price world   web        0
2013-02-03   21  Price world   web        0
2013-02-10   19  Price world   web        0
2014-02-03   21  Price world   web        0
2014-02-10   19  Price world   web        0
", header = T, stringsAsFactors = F)

#extract only the four first digits from date column
#to generate splitting groups
df_split <- split(df[, c("date", "hits")], gsub("(\\d{4})(.*$)", "\\1", df$date))

df_split
# $`2013`
#       date    hits
# 1 2013-01-06   23
# 2 2013-01-13   23
# 3 2013-01-20   40
# 4 2013-01-27   25
# 5 2013-02-03   21
# 6 2013-02-10   19
#
# $`2014`
#       date    hits
# 7 2014-02-03   21
# 8 2014-02-10   19


问:
Bad Escape String in variable returning image src in JSON

I am using Google Tag Manager to implement the 'article' JSON markup and return a couple of variables for changing elements on specific pages. One of the elements I am trying to return is an image src.

Right now I am using a DOM element to return this that is using a CSS selector. The HTML element that it is targeting is:

```<code> <div class="field-item even">
<img src="THISISTHEIMAGEURL.jpg">
</div>
</code>```

and I am targeting in GTM by collecting: div.field-item.even > img with an attribute name of src
This is a screenshot of how I'm targeting in GTM

Right now when I test this in preview mode the URL of the image is appearing exactly how it is supposed to and everything looks great.

When I check this using the Google Structured data testing tool I am returning an error that says "Bad Escape String" and a URL for the image that has slashes going both ways like http://\www.mysite.com/\image1.jpg/\

I have been doing some research, and it seems I may need to use a custom javascript variable or something in order to make this work.

I was trying to use something like this:

```<code> function() {
var src = document.querySelector(‘.fielditem.even > img').src;
}
</code>```

but then I get an error in GTM telling me I need a return value. Unfortanately, my javascript skills are pretty poor and after some more research I tried something like this:

```<code> var picture = document.getElementsByClassName(".fielditem.even");
var src = picture[0].firstElementChild.src;
</code>```

but I still am getting the same error, that I need a return value. Any help is greatly appreciated.

Thanks!

答:
You forgot the - sign in both of your selectors.

```<code>.fielditem.even > img
</code>```

Instead of

```<code>.field-item.even > img
</code>```

If you execute the script below it works fine, when querying the correct classes.

var image = document.querySelector('.field-item.even > img');
var src = image.src;

console.log(src)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="field-item even">
  <img src="https://resources.risingstack.com/risingstack-logo-2017.svg">
</div></code>```

Body:
I am using Google Tag Manager to implement the 'article' JSON markup and return a couple of variables for changing elements on specific pages. One of the elements I am trying to return is an image src.

Right now I am using a DOM element to return this that is using a CSS selector. The HTML element that it is targeting is:

and I am targeting in GTM by collecting: div.field-item.even > img with an attribute name of src
This is a screenshot of how I'm targeting in GTM

Right now when I test this in preview mode the URL of the image is appearing exactly how it is supposed to and everything looks great.

When I check this using the Google Structured data testing tool I am returning an error that says "Bad Escape String" and a URL for the image that has slashes going both ways like http://\www.mysite.com/\image1.jpg/\

I have been doing some research, and it seems I may need to use a custom javascript variable or something in order to make this work.

I was trying to use something like this:

 function() {
var src = document.querySelector(‘.fielditem.even > img').src;
}

but then I get an error in GTM telling me I need a return value. Unfortanately, my javascript skills are pretty poor and after some more research I tried something like this:

 var picture = document.getElementsByClassName(".fielditem.even");
var src = picture[0].firstElementChild.src;

but I still am getting the same error, that I need a return value. Any help is greatly appreciated.

Thanks!

Body:
You forgot the - sign in both of your selectors.

.fielditem.even > img

Instead of

.field-item.even > img

If you execute the script below it works fine, when querying the correct classes.

var image = document.querySelector('.field-item.even > img');
var src = image.src;

console.log(src)

<div class="field-item even">
  <img src="https://resources.risingstack.com/risingstack-logo-2017.svg">
</div>


问:
Python2 version of this python3 code for encoding
I am trying to run code from the answer in this post (which works perfectly with python3 version 3.5.3) with python2 version 2.7.13:

```<code>def myencode_str(ori_str, key):
    enc = []
    for i in range(len(ori_str)):
        key_c = key[i % len(key)]
        enc_c = (ord(ori_str[i]) + ord(key_c)) % 256
        enc.append(enc_c)
    return (base64.urlsafe_b64encode(bytes(enc))).decode("utf-8")
</code>```

I am using following decode fn:

```<code>def mydecode(enc_str, key):
    dec = []
    enc_str = base64.urlsafe_b64decode(enc_str)
    for i in range(len(enc_str)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + enc_str[i] - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)
</code>```

But I get following error message:

```<code>    dec_c = chr((256 + enc_str[i] - ord(key_c)) % 256)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

I tried code with following changes but they also do not work:

```<code>    dec_c = chr((256 + int(enc_str[i]) - int(ord(key_c))) % 256)
ValueError: invalid literal for int() with base 10: '\xc3'
</code>```

Where is the problem and how can it be solved?

答:
The problems is that bytes constructor has changed between Python2 and Python3, when it receives an list of integers:

in Python3, it builds a byte string where each byte receives a code from the list

in Python2, it just converts the list to a string (by using the representation or the string)

And in Python3 a byte string is an iterable of bytes (which are directly convertible to integers) while it is a mere string in Python2.

So your functions have to be a little changed:

```<code>def myencode_str(ori_str, key):
    enc = []
    for i in range(len(ori_str)):
        key_c = key[i % len(key)]
        enc_c = (ord(ori_str[i]) + ord(key_c)) % 256
        enc.append(enc_c)
    return (base64.urlsafe_b64encode(''.join([chr(i) for i in enc])))

def mydecode(enc_str, key):
    dec = []
    enc_str = [ord(i) for i in base64.urlsafe_b64decode(enc_str)]
    for i in range(len(enc_str)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + enc_str[i] - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)
</code>```

In fact, it is possible to write those functions so that same code can be used in both Python2 and Python3 with the help of the bytearray class which has same behaviour in both versions. Simply you must choose whether the input is a byte string or a unicode string. As the algorythm is based on bytes, I choosed to process byte strings in following code. You would need to encode the original string and key (using 'utf8' for full portability) and decode the decoded string to process unicode strings:

```<code>def myencode_str(ori_str, key):
    enc = []
    b = bytearray(ori_str)
    k = bytearray(key)
    for i, c in enumerate(b):
        key_c = k[i % len(key)]
        enc_c = (c + key_c) % 256
        enc.append(enc_c)
    return (base64.urlsafe_b64encode(bytes(bytearray(enc))))

def mydecode(enc_str, key):
    dec = []
    enc_str = bytearray(base64.urlsafe_b64decode(enc_str))
    k = bytearray(key)
    for i, c in enumerate(enc_str):
        key_c = k[i % len(key)]
        dec_c = (c - key_c) % 256
        dec.append(dec_c)
    return bytes(bytearray(dec))
</code>```

You can then do in Python2:

```<code>>>> myencode_str(b"abcdef", b"XYZ")
'ubu9vL7A'
>>> mydecode('ubu9vL7A', b"XYZ")
'abcdef'
</code>```

and in Python3:

```<code>>>> myencode_str(b"abcdef", b"XYZ")
b'ubu9vL7A'
>>> mydecode(b'ubu9vL7A', b"XYZ")
b'abcdef'
</code>```

Body:
I am trying to run code from the answer in this post (which works perfectly with python3 version 3.5.3) with python2 version 2.7.13:

def myencode_str(ori_str, key):
    enc = []
    for i in range(len(ori_str)):
        key_c = key[i % len(key)]
        enc_c = (ord(ori_str[i]) + ord(key_c)) % 256
        enc.append(enc_c)
    return (base64.urlsafe_b64encode(bytes(enc))).decode("utf-8")

I am using following decode fn:

def mydecode(enc_str, key):
    dec = []
    enc_str = base64.urlsafe_b64decode(enc_str)
    for i in range(len(enc_str)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + enc_str[i] - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)

But I get following error message:

    dec_c = chr((256 + enc_str[i] - ord(key_c)) % 256)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I tried code with following changes but they also do not work:

    dec_c = chr((256 + int(enc_str[i]) - int(ord(key_c))) % 256)
ValueError: invalid literal for int() with base 10: '\xc3'

Where is the problem and how can it be solved?

Body:
The problems is that bytes constructor has changed between Python2 and Python3, when it receives an list of integers:

in Python3, it builds a byte string where each byte receives a code from the list

in Python2, it just converts the list to a string (by using the representation or the string)

And in Python3 a byte string is an iterable of bytes (which are directly convertible to integers) while it is a mere string in Python2.

So your functions have to be a little changed:

def myencode_str(ori_str, key):
    enc = []
    for i in range(len(ori_str)):
        key_c = key[i % len(key)]
        enc_c = (ord(ori_str[i]) + ord(key_c)) % 256
        enc.append(enc_c)
    return (base64.urlsafe_b64encode(''.join([chr(i) for i in enc])))

def mydecode(enc_str, key):
    dec = []
    enc_str = [ord(i) for i in base64.urlsafe_b64decode(enc_str)]
    for i in range(len(enc_str)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + enc_str[i] - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)

In fact, it is possible to write those functions so that same code can be used in both Python2 and Python3 with the help of the bytearray class which has same behaviour in both versions. Simply you must choose whether the input is a byte string or a unicode string. As the algorythm is based on bytes, I choosed to process byte strings in following code. You would need to encode the original string and key (using 'utf8' for full portability) and decode the decoded string to process unicode strings:

def myencode_str(ori_str, key):
    enc = []
    b = bytearray(ori_str)
    k = bytearray(key)
    for i, c in enumerate(b):
        key_c = k[i % len(key)]
        enc_c = (c + key_c) % 256
        enc.append(enc_c)
    return (base64.urlsafe_b64encode(bytes(bytearray(enc))))

def mydecode(enc_str, key):
    dec = []
    enc_str = bytearray(base64.urlsafe_b64decode(enc_str))
    k = bytearray(key)
    for i, c in enumerate(enc_str):
        key_c = k[i % len(key)]
        dec_c = (c - key_c) % 256
        dec.append(dec_c)
    return bytes(bytearray(dec))

You can then do in Python2:

>>> myencode_str(b"abcdef", b"XYZ")
'ubu9vL7A'
>>> mydecode('ubu9vL7A', b"XYZ")
'abcdef'

and in Python3:

>>> myencode_str(b"abcdef", b"XYZ")
b'ubu9vL7A'
>>> mydecode(b'ubu9vL7A', b"XYZ")
b'abcdef'


问:
Android-Threading: refer to Views from Threads
I've tried to use threads for better performance in my Android App.
In the onCreate Method i started two threads:

```<code> @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.play);

    ...

    new Thread(new Runnable() {
        public void run() {
         makeList();
        }
    }).start();

    new Thread(new Runnable() {
        public void run() {
         setChronometer();
        }
    }).start();
}
</code>```

In these Methods I change the some settings of my Views. (no heavy events)

First a Chronometer:

```<code> private void setChronometer(){
 time.post(new Runnable() {
         public void run() {
       time.setFormat("Time: %s");
       time.setBase(SystemClock.elapsedRealtime());
       time.start();
         }
       });
 }
</code>```

Second a ListView:

```<code>private void makeList(){
  ...
        final ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(...);

        list.post(new Runnable() {
         public void run() {
          list.setAdapter(listAdapter);
          list.setOnItemClickListener(new OnItemClickListener() {
     public void onItemClick(AdapterView<?> parent,  View view, int position, long id) {
    ....

         }
       });
 }
</code>```

The Chronometer works fine,
but the operations in makeList() weren't done.. so my ListView isn't working!

I had the idea,that when the activity starts, defining the listView and Chronometer is less important, so i defer them in threads, with the aim, that the activity starts faster (is more performat)

First of all, was this a good Idea?

Secondly, why is my ListView not working? When i remove the list.post(new Runnable() {
it works, but i thought that wasn't a good way in android. Cause now the Views are directy changed from a thread.

Thirdly, when should i use Threads vs.View.post?

Any help would be great, Thanks!

Greetings
FireDragon

答: Reuben is right about AsyncTask.  However, if you want to understand how Threading works I've detailed the various approaches on blog.  AsyncTask is the way to go though.</p>

Body:
I've tried to use threads for better performance in my Android App.
In the onCreate Method i started two threads:

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.play);

    ...

    new Thread(new Runnable() {
        public void run() {
         makeList();
        }
    }).start();

    new Thread(new Runnable() {
        public void run() {
         setChronometer();
        }
    }).start();
}

In these Methods I change the some settings of my Views. (no heavy events)

First a Chronometer:

 private void setChronometer(){
 time.post(new Runnable() {
         public void run() {
       time.setFormat("Time: %s");
       time.setBase(SystemClock.elapsedRealtime());
       time.start();
         }
       });
 }

Second a ListView:

private void makeList(){
  ...
        final ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(...);

        list.post(new Runnable() {
         public void run() {
          list.setAdapter(listAdapter);
          list.setOnItemClickListener(new OnItemClickListener() {
     public void onItemClick(AdapterView<?> parent,  View view, int position, long id) {
    ....

         }
       });
 }

The Chronometer works fine,
but the operations in makeList() weren't done.. so my ListView isn't working!

I had the idea,that when the activity starts, defining the listView and Chronometer is less important, so i defer them in threads, with the aim, that the activity starts faster (is more performat)

First of all, was this a good Idea?

Secondly, why is my ListView not working? When i remove the list.post(new Runnable() {
it works, but i thought that wasn't a good way in android. Cause now the Views are directy changed from a thread.

Thirdly, when should i use Threads vs.View.post?

Any help would be great, Thanks!

Greetings
FireDragon


问:
Infinitely Horizontally scrolling set of divs within container div
I'm trying to create a strip of logos that when one is selected reveals a quote from that customer. When a logo is selected, it should go to the left side of the strip and stay there. I got that to work.

My problem is making the logos go on forever.

As the divs of the logos go outside of their container, I'm trying to remove them and then recreate them on the other side of the strip, so that the logos can keep going on and on and on. However, it is not working very well.

This is the html:

```<code><div class="logo-strip">
                <div id="logo-1" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-2" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-3" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-4" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-5" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>
                <div id="logo-6" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-7" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-8" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>
            </div>
</code>```

Here is the CSS:

```<code> div.logo-strip {
 display: flex;
 height: 70px;
 width: 100%;
 overflow: hidden; }

div.logo-strip div.logo {
  display: flex;
  min-width: 112.5px;
  padding: 5px;
  cursor: pointer;
  opacity: .4;
  transition: .5s; }

    div.logo-strip div.logo img {
    object-fit: contain; }

  div.logo-strip div.selected-logo {
  opacity: 1; }
</code>```

Now here is my js:

```<code>( function( $ ) {

$('div#quote-1').removeClass('hidden');
$('div#quote-1').animate({'opacity' : '1'}, 500);
$('div#logo-1').addClass('selected-logo');

$('div.logo').click(function() {

    $('div.logo').removeClass('selected-logo');
    $(this).addClass('selected-logo');

    var logo_offset = $(this).offset().left - $('div.logo').first().offset().left;
    var negative_offset = logo_offset * -1;

    var strip_offset = $('div.logo-strip').offset().left - $('div.logo').first().offset().left;

    if (strip_offset >  100) {

        var to_be_cloned = $('div.logo').slice(0, 3);
        to_be_cloned.remove();
        $('div.logo').last().after(to_be_cloned);

    }

    console.log(strip_offset);
    console.log(to_be_cloned);

    $('div.logo').css({'transform' : 'translateX(' + negative_offset + 'px)'});

    var logo_id = $(this).attr('id');
    var logo_id_trimmed = logo_id.substr(5);

    $('div.customer-quote').addClass('hidden');
    $('div.customer-quote').css({'opacity' : '0'});
    $('div#quote-' + logo_id_trimmed).removeClass('hidden');
    $('div#quote-' + logo_id_trimmed).animate({'opacity' : '1'}, 500);
});

} )( jQuery );
</code>```

Basically I've been trying to make it so that after the first logo gets a certain distance away from the div.logo-strip container element, then it removes that logo div and recreates it at the end of the logo divs. It sort of works but it is janky as hell. Does anyone know how to do this?

答:
I figured it out.

First, everything was moving around strangle because I was deleting the divs on one end of the set and putting them on the other end, causing everything to shift around. What I needed to do was clone the divs and put them at the end, so I was just adding divs on the end, and not removing them from the beginning at all.

Second, I needed to get the index of the previously selected div and the newly selected div and use them to create the slice numbers.

Third, you need to move the whole chain of divs by a measurement of the newly selected div's offset left minus the first div's offset left.

Fourth, you need to start out with extra divs trailing outside of the area on end. If you don't have that then it will move weird at the beginning.

Here is the new JS:

```<code>$('div.logo').click(function() {
    var previously_selected = $('div.selected-logo');
    var newly_selected = $(this);
    var number_of_previous_selection = $('div.logo').index(previously_selected);
    var number_of_new_selection = $('div.logo').index(newly_selected);
    var selection_distance = number_of_previous_selection - number_of_new_selection;

    $('div.logo').removeClass('selected-logo');
    $(this).addClass('selected-logo');

    var logo_offset = $(this).offset().left - $('div.logo').first().offset().left;
    var negative_offset = logo_offset * -1;
    var strip_offset = $('div.logo-strip').offset().left - $('div.logo').first().offset().left;

    var to_be_cloned = $('div.logo').slice(number_of_previous_selection, number_of_new_selection).clone(true);
    $('div.logo-strip').append(to_be_cloned);
    $('div.logo').css({'transform' : 'translateX(' + negative_offset + 'px)'});

    console.log(number_of_new_selection);
    console.log(number_of_previous_selection);
    console.log(negative_offset);

    var logo_id = $(this).attr('id');
    var logo_id_trimmed = logo_id.substr(5);

    $('div.customer-quote').addClass('hidden');
    $('div.customer-quote').css({'opacity' : '0'});
    $('div#quote-' + logo_id_trimmed).removeClass('hidden');
    $('div#quote-' + logo_id_trimmed).animate({'opacity' : '1'}, 500);

});
</code>```

And then the HTML:

```<code><div class="quote-and-title">
                <div class="customer-quote hidden" id="quote-1">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-2">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-3">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-4">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-5">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-6">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-7">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-8">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-9">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-10">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-11">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-12">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="title has-red-divider-uptop">
                    <p>What The Industry is Saying</p>
                </div>
            </div>

            <div class="logo-strip">

                <div id="logo-1" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-2" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-3" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-4" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-5" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>
                <div id="logo-6" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-7" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-8" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>
                <div id="logo-9" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-10" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>
                <div id="logo-11" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-12" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>

            </div>
</code>```

Body:
I'm trying to create a strip of logos that when one is selected reveals a quote from that customer. When a logo is selected, it should go to the left side of the strip and stay there. I got that to work.

My problem is making the logos go on forever.

As the divs of the logos go outside of their container, I'm trying to remove them and then recreate them on the other side of the strip, so that the logos can keep going on and on and on. However, it is not working very well.

This is the html:

Here is the CSS:

 div.logo-strip {
 display: flex;
 height: 70px;
 width: 100%;
 overflow: hidden; }

div.logo-strip div.logo {
  display: flex;
  min-width: 112.5px;
  padding: 5px;
  cursor: pointer;
  opacity: .4;
  transition: .5s; }

    div.logo-strip div.logo img {
    object-fit: contain; }

  div.logo-strip div.selected-logo {
  opacity: 1; }

Now here is my js:

( function( $ ) {

$('div#quote-1').removeClass('hidden');
$('div#quote-1').animate({'opacity' : '1'}, 500);
$('div#logo-1').addClass('selected-logo');

$('div.logo').click(function() {

    $('div.logo').removeClass('selected-logo');
    $(this).addClass('selected-logo');

    var logo_offset = $(this).offset().left - $('div.logo').first().offset().left;
    var negative_offset = logo_offset * -1;

    var strip_offset = $('div.logo-strip').offset().left - $('div.logo').first().offset().left;

    if (strip_offset >  100) {

        var to_be_cloned = $('div.logo').slice(0, 3);
        to_be_cloned.remove();
        $('div.logo').last().after(to_be_cloned);

    }

    console.log(strip_offset);
    console.log(to_be_cloned);

    $('div.logo').css({'transform' : 'translateX(' + negative_offset + 'px)'});

    var logo_id = $(this).attr('id');
    var logo_id_trimmed = logo_id.substr(5);

    $('div.customer-quote').addClass('hidden');
    $('div.customer-quote').css({'opacity' : '0'});
    $('div#quote-' + logo_id_trimmed).removeClass('hidden');
    $('div#quote-' + logo_id_trimmed).animate({'opacity' : '1'}, 500);
});

} )( jQuery );

Basically I've been trying to make it so that after the first logo gets a certain distance away from the div.logo-strip container element, then it removes that logo div and recreates it at the end of the logo divs. It sort of works but it is janky as hell. Does anyone know how to do this?

Body:
I figured it out.

First, everything was moving around strangle because I was deleting the divs on one end of the set and putting them on the other end, causing everything to shift around. What I needed to do was clone the divs and put them at the end, so I was just adding divs on the end, and not removing them from the beginning at all.

Second, I needed to get the index of the previously selected div and the newly selected div and use them to create the slice numbers.

Third, you need to move the whole chain of divs by a measurement of the newly selected div's offset left minus the first div's offset left.

Fourth, you need to start out with extra divs trailing outside of the area on end. If you don't have that then it will move weird at the beginning.

Here is the new JS:

$('div.logo').click(function() {
    var previously_selected = $('div.selected-logo');
    var newly_selected = $(this);
    var number_of_previous_selection = $('div.logo').index(previously_selected);
    var number_of_new_selection = $('div.logo').index(newly_selected);
    var selection_distance = number_of_previous_selection - number_of_new_selection;

    $('div.logo').removeClass('selected-logo');
    $(this).addClass('selected-logo');

    var logo_offset = $(this).offset().left - $('div.logo').first().offset().left;
    var negative_offset = logo_offset * -1;
    var strip_offset = $('div.logo-strip').offset().left - $('div.logo').first().offset().left;

    var to_be_cloned = $('div.logo').slice(number_of_previous_selection, number_of_new_selection).clone(true);
    $('div.logo-strip').append(to_be_cloned);
    $('div.logo').css({'transform' : 'translateX(' + negative_offset + 'px)'});

    console.log(number_of_new_selection);
    console.log(number_of_previous_selection);
    console.log(negative_offset);

    var logo_id = $(this).attr('id');
    var logo_id_trimmed = logo_id.substr(5);

    $('div.customer-quote').addClass('hidden');
    $('div.customer-quote').css({'opacity' : '0'});
    $('div#quote-' + logo_id_trimmed).removeClass('hidden');
    $('div#quote-' + logo_id_trimmed).animate({'opacity' : '1'}, 500);

});

And then the HTML:

<div class="quote-and-title">
                <div class="customer-quote hidden" id="quote-1">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-2">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-3">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-4">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-5">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-6">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-7">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-8">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-9">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-10">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-11">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="customer-quote hidden" id="quote-12">
                    <p class="customer-text">“Lorem ipsum dolor sit amet, consectetuer adipiscin elit,
                    sed diam nonummy nibh euismod tincidunt ut laoreet
                    dolore magna aliquam erat volutpat. Ut wisi enim ad
                    minim. Lorem ipsum dolor sit amet.”</p>
                    <p class="customer-title">John Smith, Facility Manager</p>
                </div>
                <div class="title has-red-divider-uptop">
                    <p>What The Industry is Saying</p>
                </div>
            </div>

            <div class="logo-strip">

                <div id="logo-1" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-2" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-3" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-4" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-5" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>
                <div id="logo-6" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-7" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-8" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>
                <div id="logo-9" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-10" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>
                <div id="logo-11" class="logo">
                    <img src="http://www.henningsen.com/wp-content/themes/henningsen-cold-storage/images/logo-emboss.png">
                </div>
                <div id="logo-12" class="logo">
                    <img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/ce/Safeway_Logo.svg/1280px-Safeway_Logo.svg.png">
                </div>

            </div>


问:
Regex.Match() vs new Regex().Match() is there a difference?
Specifically to memory here, would Regex.Match() and new Regex().Match() have a difference?

Would not creating a new assertion of the Regex class cost more memory then using Regex.Match?

The reason I am asking is I've always been doing new Regex("pattern").Match("Input") and saw Regex.Match and I'm now questioning if I'm doing it wrong!

答:
You are correct. The static method Regex.Match is good for situations when you won't need to reuse a Regex object. If you were going to be matching multiple inputs, you would likely want to use

```<code>Regex reggy = new Regex("pattern");
</code>```

And then use that object as many times as you need it.

Body:
You are correct. The static method Regex.Match is good for situations when you won't need to reuse a Regex object. If you were going to be matching multiple inputs, you would likely want to use

Regex reggy = new Regex("pattern");

And then use that object as many times as you need it.


问:
how to remove length from my url in asp.net mvc?
I m creating  an Mvc application . I have some issue .

I am getting url

http://localhost:2355/Home/Contract?Length=4

I want my url as

http://localhost:2355/Home/Contract

```<code>routes.MapRoute(
  name: "Default",
  url: "{controller}/{action}",
  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
</code>```

what is problem in my route mapping

答:
If you're using @Html.ActionLink() you should try try these ones.

```<code>@Html.ActionLink("MyAction", "MyController", new { }, new { @Class="class-name"})
</code>```

with Areas

```<code>@Html.ActionLink("MyAction", "MyController", new { }, new {@Area = "MyArea" @Class="class-name"})
</code>```

Sendind data

```<code>@using (Ajax.BeginForm("MyAction", "MyController", new {  }, new AjaxOptions { HttpMethod = "POST" }, new { @Area = "MyArea" }))
</code>```

Sending data with no Area

```<code>@using (Ajax.BeginForm("MyAction", "MyController", new AjaxOptions { HttpMethod = "POST" }));
</code>```

Besides that, you can check the url which @gardarvalur has posted.
I hope it helps you.

Body:
I m creating  an Mvc application . I have some issue .

I am getting url

http://localhost:2355/Home/Contract?Length=4

I want my url as

http://localhost:2355/Home/Contract

routes.MapRoute(
  name: "Default",
  url: "{controller}/{action}",
  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

what is problem in my route mapping

Body:
If you're using @Html.ActionLink() you should try try these ones.

@Html.ActionLink("MyAction", "MyController", new { }, new { @Class="class-name"})

with Areas

@Html.ActionLink("MyAction", "MyController", new { }, new {@Area = "MyArea" @Class="class-name"})

Sendind data

@using (Ajax.BeginForm("MyAction", "MyController", new {  }, new AjaxOptions { HttpMethod = "POST" }, new { @Area = "MyArea" }))

Sending data with no Area

@using (Ajax.BeginForm("MyAction", "MyController", new AjaxOptions { HttpMethod = "POST" }));

Besides that, you can check the url which @gardarvalur has posted.
I hope it helps you.