问:
Error in For Each loop using AutoFilter runtime (error 13)
This is what I am trying to do

Find unique values in column D

Loop over those values by creating a filter with each

with the remaining rows after filtering, I do the same with columns E and F.

Finally, I just need to copy the remaining values in column K and past them in a different sheet.

In one of the loops the code gives me an error (see line below).  I have tried to solve it in different ways and looked for an answer online, but I have not been able to find why is that happening. I got "run-time error '13' Type mismatch"

I highly appreciate any ideas. Thanks!!

```<code>Sub UniqueVals_f()

'' Variables
Dim i As Variant   ' loop counter
Dim a As Variant   ' loop counter
Dim R As Long
Dim W As Long
Dim Z As Long
Dim gr As Variant  ' group values
Dim ca As Variant  ' category value
Dim cl As Variant  ' class value
Dim CategArray() As Variant
Dim GroupArray() As Variant
Dim ClassArray() As Variant
Dim My_Range As Range
Dim DestSh As Worksheet ' Destination sheet
Dim LastCol As Long
Dim rng As Range
Dim r1 As Range
Dim r2 As Range
Dim r3 As Range

' select range
Set My_Range = Worksheets("ICP").Range("D1", Range("F" & Rows.Count).End(xlUp))
My_Range.Parent.Select
My_Range.Parent.AutoFilterMode = False  'Remove the AutoFilter

' Destination sheet
Set DestSh = Sheets("items")

ca = Application.Transpose(Range("D2", Range("D" & Rows.Count).End(xlUp))) ' extract Categories
With CreateObject("Scripting.Dictionary") 'Categories array
    For Each i In ca  ' <-- This one works fine
        .Item(i) = i
    Next
    CategArray = Application.Transpose(.Keys)  ' getting unique values
End With

'' loop over categories
For R = 1 To UBound(CategArray, 1)
    My_Range.AutoFilter Field:=1, Criteria1:="=" & CategArray(R, 1) ' First Filter
    gr = Application.Transpose(Range("E2", Range("E" & Rows.Count).End(xlUp))) ' extract Groups
    With CreateObject("Scripting.Dictionary")
        For Each i In gr  ' <-- This one works fine too
            .Item(i) = i
        Next
        GroupArray = Application.Transpose(.Keys) ' getting unique values
    End With

    '' Loop over Groups
    For W = 1 To UBound(GroupArray, 1)
        My_Range.AutoFilter Field:=2, Criteria1:="=" & GroupArray(W, 1) ' Second Filter

        lr3 = Cells(Rows.Count, 6).End(xlUp).Row   '' Extract Classes
        cl = Application.Transpose(Range("F2:F" & lr3))
        ' cl = Range("F2:F" & lr3)               ' Alternative way 1
        ' cl = Range("F2:F" & lr3).Value2        ' Alternative way 2
        With CreateObject("Scripting.Dictionary")
            For Each i In cl    '' <-- THE ERROR IS HERE!!!
            'For i = LBound(cl, 1) To UBound(cl, 1) ' Alternative that has the same error
                .Item(i) = i
            Next
            'Next i
            ClassArray = Application.Transpose(.Keys)
        End With

        '' Loop over classes
        For Z = 1 To UBound(ClassArray, 1)
            ' filter classes
            My_Range.AutoFilter Field:=3, Criteria1:="=" & ClassArray(Z, 1) ' Third Filter

            '' Copy items
            Set rng = DestSh.Rows("2:2")
            LastCol = Last(2, rng)

            Range("K2", Range("K" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible).Copy _
            Destination:=DestSh.Cells(2, LastCol + 1)

            My_Range.Parent.AutoFilterMode = False  'Remove the AutoFilter

        Next Z
    Next W
Next R

End Sub
</code>```

Best,
Pablo

答:
All your alternatives won't work if lr3 = 2, because Range("F2:F" & lr3).Value (.Value is invoked implicitly since you dont use Set) will NOT be an array but just a value, and the same applies for its Transpose.

The reason is that you are not using Set, so you are getting a value, and the value of a single cell will not be an array. I noticed that none of your Transpose operations is necessary. So try this quick-fix,

Remove all your Transpose statements and take the original range

use the Set keyword to have range objects instead of arrays

.

```<code> Set ca = Range("D2", Range("D" & Rows.Count).End(xlUp))

 Set gr = Range("E2", Range("E" & Rows.Count).End(xlUp))

 Set cl = Range("F2:F" & lr3)
</code>```

That said, this will fix only the issue at hand. There are many other problems in the code. One of them being that when you apply My_Range.Parent.AutoFilterMode = False, All filters are removed, not only the one applied in the inner loop. But try fixing the current issue at the moment.

Body:
This is what I am trying to do

Find unique values in column D

Loop over those values by creating a filter with each

with the remaining rows after filtering, I do the same with columns E and F.

Finally, I just need to copy the remaining values in column K and past them in a different sheet.

In one of the loops the code gives me an error (see line below).  I have tried to solve it in different ways and looked for an answer online, but I have not been able to find why is that happening. I got "run-time error '13' Type mismatch"

I highly appreciate any ideas. Thanks!!

Sub UniqueVals_f()

'' Variables
Dim i As Variant   ' loop counter
Dim a As Variant   ' loop counter
Dim R As Long
Dim W As Long
Dim Z As Long
Dim gr As Variant  ' group values
Dim ca As Variant  ' category value
Dim cl As Variant  ' class value
Dim CategArray() As Variant
Dim GroupArray() As Variant
Dim ClassArray() As Variant
Dim My_Range As Range
Dim DestSh As Worksheet ' Destination sheet
Dim LastCol As Long
Dim rng As Range
Dim r1 As Range
Dim r2 As Range
Dim r3 As Range

' select range
Set My_Range = Worksheets("ICP").Range("D1", Range("F" & Rows.Count).End(xlUp))
My_Range.Parent.Select
My_Range.Parent.AutoFilterMode = False  'Remove the AutoFilter

' Destination sheet
Set DestSh = Sheets("items")

ca = Application.Transpose(Range("D2", Range("D" & Rows.Count).End(xlUp))) ' extract Categories
With CreateObject("Scripting.Dictionary") 'Categories array
    For Each i In ca  ' <-- This one works fine
        .Item(i) = i
    Next
    CategArray = Application.Transpose(.Keys)  ' getting unique values
End With

'' loop over categories
For R = 1 To UBound(CategArray, 1)
    My_Range.AutoFilter Field:=1, Criteria1:="=" & CategArray(R, 1) ' First Filter
    gr = Application.Transpose(Range("E2", Range("E" & Rows.Count).End(xlUp))) ' extract Groups
    With CreateObject("Scripting.Dictionary")
        For Each i In gr  ' <-- This one works fine too
            .Item(i) = i
        Next
        GroupArray = Application.Transpose(.Keys) ' getting unique values
    End With

    '' Loop over Groups
    For W = 1 To UBound(GroupArray, 1)
        My_Range.AutoFilter Field:=2, Criteria1:="=" & GroupArray(W, 1) ' Second Filter

        lr3 = Cells(Rows.Count, 6).End(xlUp).Row   '' Extract Classes
        cl = Application.Transpose(Range("F2:F" & lr3))
        ' cl = Range("F2:F" & lr3)               ' Alternative way 1
        ' cl = Range("F2:F" & lr3).Value2        ' Alternative way 2
        With CreateObject("Scripting.Dictionary")
            For Each i In cl    '' <-- THE ERROR IS HERE!!!
            'For i = LBound(cl, 1) To UBound(cl, 1) ' Alternative that has the same error
                .Item(i) = i
            Next
            'Next i
            ClassArray = Application.Transpose(.Keys)
        End With

        '' Loop over classes
        For Z = 1 To UBound(ClassArray, 1)
            ' filter classes
            My_Range.AutoFilter Field:=3, Criteria1:="=" & ClassArray(Z, 1) ' Third Filter

            '' Copy items
            Set rng = DestSh.Rows("2:2")
            LastCol = Last(2, rng)

            Range("K2", Range("K" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible).Copy _
            Destination:=DestSh.Cells(2, LastCol + 1)

            My_Range.Parent.AutoFilterMode = False  'Remove the AutoFilter

        Next Z
    Next W
Next R

End Sub

Best,
Pablo

Body:
All your alternatives won't work if lr3 = 2, because Range("F2:F" & lr3).Value (.Value is invoked implicitly since you dont use Set) will NOT be an array but just a value, and the same applies for its Transpose.

The reason is that you are not using Set, so you are getting a value, and the value of a single cell will not be an array. I noticed that none of your Transpose operations is necessary. So try this quick-fix,

Remove all your Transpose statements and take the original range

use the Set keyword to have range objects instead of arrays

.

 Set ca = Range("D2", Range("D" & Rows.Count).End(xlUp))

 Set gr = Range("E2", Range("E" & Rows.Count).End(xlUp))

 Set cl = Range("F2:F" & lr3)

That said, this will fix only the issue at hand. There are many other problems in the code. One of them being that when you apply My_Range.Parent.AutoFilterMode = False, All filters are removed, not only the one applied in the inner loop. But try fixing the current issue at the moment.


来源: stackexchange

问:
Thread 1: EXC_BAD_ACCESS (code=2, address = 0x010db93e38)
This is the crash log Every time I click on the button that is a part of the simulator, I keep getting the error EXC_BAD_ACCESS. This code is the part of the calendar from the JTAppleCalendar. </p>

```<code>import UIKit
import JTAppleCalendar

class EventsViewController: UIViewController {

    @IBOutlet weak var calendarView: JTAppleCalendarView!
    let formatter = DateFormatter()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupCalendarView()

    }
    func setupCalendarView(){
        calendarView.minimumLineSpacing = 0
        calendarView.minimumInteritemSpacing = 0

    }

        // Do any additional setup after loading the view.

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
</code>```

答: Check if calendarView is connected in the Storyboard in Referencing Outlets.</p>

ContentLicense: CC BY-SA 3.0

Body:
This is the crash log Every time I click on the button that is a part of the simulator, I keep getting the error EXC_BAD_ACCESS. This code is the part of the calendar from the JTAppleCalendar.

import UIKit
import JTAppleCalendar

class EventsViewController: UIViewController {

    @IBOutlet weak var calendarView: JTAppleCalendarView!
    let formatter = DateFormatter()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupCalendarView()

    }
    func setupCalendarView(){
        calendarView.minimumLineSpacing = 0
        calendarView.minimumInteritemSpacing = 0

    }

        // Do any additional setup after loading the view.

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


问:
Correction script Bash
I'm trying in vain to solve my problem with this script.

```<code>#!/bin/bash
for a in `wget -O - "https://pastebin.com/raw/7BFC94Ty"`; do echo "local-zone: \""$a" redirect\"""local-data: \""$a" A 0.0.0.0\"" >> adstest.conf; done
</code>```

Here is the result

```<code>local-zone: "101com.com
 redirect"local-data: "101com.com
 A 0.0.0.0"
</code>```

But this is not the right formatting, this is the expected result:

```<code>local-zone: "101com.com" redirect
local-data: "101com.com A 0.0.0.0"
</code>```

But I can not find this damn solution. I'm also looking for a solution to be able to use a local file rather than a url because I have a file of 40 000 lines and I would like to do without a web host for that.

Thank you for your help !

答:
First, you have to run it through dos2unix to get rid of the Windoze line breaks, then do two separate echos and send the results of the entire loop to the output file:

```<code>for a in `wget -O - "https://pastebin.com/raw/7BFC94Ty" | dos2unix`; do
  echo 'local-zone: "'$a'" redirect'
  echo 'local-data: "'$a' A 0.0.0.0"'
done >> adstest.conf
</code>```

I also used single-quotes so I did not have to escape the doubles you want printed.

Sample results:

```<code>$ rm adstest.conf

$ for a in `wget -O - "https://pastebin.com/raw/7BFC94Ty" | dos2unix`; do   echo 'local-zone: "'$a'" redirect';   echo 'local-data: "'$a' A 0.0.0.0"'; done >> adstest.conf
--2017-07-07 14:12:07--  https://pastebin.com/raw/7BFC94Ty
Resolving pastebin.com (pastebin.com)... 104.20.208.21, 104.20.209.21
Connecting to pastebin.com (pastebin.com)|104.20.208.21|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/plain]
Saving to: ‘STDOUT’

-                                        [ <=>                                                                   ] 385.23K  --.-KB/s    in 0.09s

2017-07-07 14:12:07 (3.97 MB/s) - written to stdout [394475]

$ wc -l adstest.conf
41860 adstest.conf

$ head adstest.conf
local-zone: "101com.com" redirect
local-data: "101com.com A 0.0.0.0"
local-zone: "101order.com" redirect
local-data: "101order.com A 0.0.0.0"
local-zone: "123found.com" redirect
local-data: "123found.com A 0.0.0.0"
local-zone: "140proof.com" redirect
local-data: "140proof.com A 0.0.0.0"
local-zone: "180hits.de" redirect
local-data: "180hits.de A 0.0.0.0"
</code>```

Title: Correction script Bash

Body:
I'm trying in vain to solve my problem with this script.

#!/bin/bash
for a in `wget -O - "https://pastebin.com/raw/7BFC94Ty"`; do echo "local-zone: \""$a" redirect\"""local-data: \""$a" A 0.0.0.0\"" >> adstest.conf; done

Here is the result

local-zone: "101com.com
 redirect"local-data: "101com.com
 A 0.0.0.0"

But this is not the right formatting, this is the expected result:

local-zone: "101com.com" redirect
local-data: "101com.com A 0.0.0.0"

But I can not find this damn solution. I'm also looking for a solution to be able to use a local file rather than a url because I have a file of 40 000 lines and I would like to do without a web host for that.

Thank you for your help !

Body:
First, you have to run it through dos2unix to get rid of the Windoze line breaks, then do two separate echos and send the results of the entire loop to the output file:

for a in `wget -O - "https://pastebin.com/raw/7BFC94Ty" | dos2unix`; do
  echo 'local-zone: "'$a'" redirect'
  echo 'local-data: "'$a' A 0.0.0.0"'
done >> adstest.conf

I also used single-quotes so I did not have to escape the doubles you want printed.

Sample results:

$ rm adstest.conf

$ for a in `wget -O - "https://pastebin.com/raw/7BFC94Ty" | dos2unix`; do   echo 'local-zone: "'$a'" redirect';   echo 'local-data: "'$a' A 0.0.0.0"'; done >> adstest.conf
--2017-07-07 14:12:07--  https://pastebin.com/raw/7BFC94Ty
Resolving pastebin.com (pastebin.com)... 104.20.208.21, 104.20.209.21
Connecting to pastebin.com (pastebin.com)|104.20.208.21|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/plain]
Saving to: ‘STDOUT’

-                                        [ <=>                                                                   ] 385.23K  --.-KB/s    in 0.09s

2017-07-07 14:12:07 (3.97 MB/s) - written to stdout [394475]

$ wc -l adstest.conf
41860 adstest.conf

$ head adstest.conf
local-zone: "101com.com" redirect
local-data: "101com.com A 0.0.0.0"
local-zone: "101order.com" redirect
local-data: "101order.com A 0.0.0.0"
local-zone: "123found.com" redirect
local-data: "123found.com A 0.0.0.0"
local-zone: "140proof.com" redirect
local-data: "140proof.com A 0.0.0.0"
local-zone: "180hits.de" redirect
local-data: "180hits.de A 0.0.0.0"


问:
"Command /usr/sbin/chown failed with exit code 1" when Archiving
I am trying to archive my first iOS 4.3 Application for iPhone and I always encounter this error:

```<code>Command /usr/sbin/chown failed with exit code 1
</code>```

I have searched through various forums, trying solutions such as changing the Alternate Install Group (which I don't know what to change to), and turning on 'Skip Install'.

答:
I had the same issue with Xcode . It started working after restarting Xcode.
In the screenshot , Xcode ->build settings , installed group was empty after restarting Xcode .the group id it has showed as some number.

Body:
I am trying to archive my first iOS 4.3 Application for iPhone and I always encounter this error:

Command /usr/sbin/chown failed with exit code 1

I have searched through various forums, trying solutions such as changing the Alternate Install Group (which I don't know what to change to), and turning on 'Skip Install'.


问:
Delete function always selects same ID - blog - Codeigniter
So, I have been trying to get this delete function to work now for a while.

At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.

View

```<code><div><?php foreach($posts as $post) : ?>
<hr>
<h3><?php echo $post['title']; ?></h3>
<div class="row">
    <div class="col-md-3">
        <img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">
    </div>
    <div class="col-md-9">
        <small class="post-date">Posted on: <?php echo $post['created_at']; ?> in <strong><?php echo $post['name']; ?></strong></small><br>
    <?php echo word_limiter($post['body'], 60); ?>
    <br><br>
    <p><a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More</a></p>
    </div>
</div>
<?php echo form_open('/posts/delete/'.$post['id']); ?>
    <input type="submit" value="Delete" class="btn btn-danger">
</form>
</code>```

Controller

```<code>public function posts($offset = 0){

  // Pagination Config
  $config['base_url'] = base_url() . 'admins/posts/';
  $config['total_rows'] = $this->db->count_all('posts');
  $config['per_page'] = 10;
  $config['uri_segment'] = 3;
  $config['attributes'] = array('class' => 'pagination-link');

  // Init Pagination
  $this->pagination->initialize($config);

  $data['title'] = 'Latest Posts';

  $data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);

    $this->load->view('templates/header');
    $this->load->view('admins/posts', $data);
    $this->load->view('templates/footer');
}
</code>```

Model

```<code>public function delete_post($id){
  $image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
  $cwd = getcwd(); // save the current working directory
  $image_file_path = $cwd."\\assets\\images\\posts\\";
  chdir($image_file_path);
  unlink($image_file_name);
  chdir($cwd); // Restore the previous working directory
  $this->db->where('id', $id);
  $this->db->delete('posts');
  return true;
}
</code>```

EDIT:
get_posts in model

```<code>public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }
  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }

  $query = $this->db->get_where('posts', array('slug' => $slug));
  return $query->row_array();
}
</code>```

The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.

答:
May be i am wrong but i think its a foreach syntax issue,
because if you getting same id in all the
rows,
you need to write like,</p>

```<code><?php foreach ($posts as $post) : ?>
instead of,
<?php foreach ($posts as $post) { ?>
//your code goes here
<?php } ?>
</code>```

Body:
So, I have been trying to get this delete function to work now for a while.

At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.

View

<?php foreach($posts as $post) : ?>

<?php echo $post['title']; ?>

        <img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">

        Posted on: <?php echo $post['created_at']; ?> in <?php echo $post['name']; ?>

    <?php echo word_limiter($post['body'], 60); ?>

<a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More

<?php echo form_open('/posts/delete/'.$post['id']); ?>
    <input type="submit" value="Delete" class="btn btn-danger">
</form>

Controller

public function posts($offset = 0){

  // Pagination Config
  $config['base_url'] = base_url() . 'admins/posts/';
  $config['total_rows'] = $this->db->count_all('posts');
  $config['per_page'] = 10;
  $config['uri_segment'] = 3;
  $config['attributes'] = array('class' => 'pagination-link');

  // Init Pagination
  $this->pagination->initialize($config);

  $data['title'] = 'Latest Posts';

  $data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);

    $this->load->view('templates/header');
    $this->load->view('admins/posts', $data);
    $this->load->view('templates/footer');
}

Model

public function delete_post($id){
  $image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
  $cwd = getcwd(); // save the current working directory
  $image_file_path = $cwd."\\assets\\images\\posts\\";
  chdir($image_file_path);
  unlink($image_file_name);
  chdir($cwd); // Restore the previous working directory
  $this->db->where('id', $id);
  $this->db->delete('posts');
  return true;
}

EDIT:
get_posts in model

public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }
  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }

  $query = $this->db->get_where('posts', array('slug' => $slug));
  return $query->row_array();
}

The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.

Body:
May be i am wrong but i think its a foreach syntax issue,
because if you getting same id in all the
rows,
you need to write like,

<?php foreach ($posts as $post) : ?>
instead of,
<?php foreach ($posts as $post) { ?>
//your code goes here
<?php } ?>


问:
Nib must contain exactly one top level object which must be a UITableViewCell instance
I got intermitent error when try to use nib that was registered for reuse. Im using the same custom cell on two ViewControllers.

2013-09-05 11:04:08.476 xxx[51395:c07] *** Terminating app due to
  uncaught exception 'NSInternalInconsistencyException', reason:
  'invalid nib registered for identifier (TweetTableViewCellId) - nib
  must contain exactly one top level object which must be a
  UITableViewCell instance'

Im use NIB file with one view at Object list - on top, sure -. It has type TweetViewCell, it that extends UITableViewCell -.

I already define [b]identifier[/b] as "TweetTableViewCellId"

Im load nib and did register it on viewDidLoad (i already debug and nib object aways is loaded)

I try to recover registered cell using the same id.

some piece of code

```<code>// First Controller to use custom Cell
@implementation TweetsViewController

- (void) viewDidLoad
{
...
  UINib *nib =  [UINib nibWithNibName:kTweetTableViewCellNibName bundle:nil];
  [self.tweetsTableView registerNib:nib forCellReuseIdentifier:@"TweetTableViewCellId"];

..
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  TweetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTweetTableViewCellId forIndexPath:indexPath];
...
}

@end

// second Controller to use custom Cell

@implementation OfflineEpisodeModalViewController

- (void) viewDidLoad
{
  UINib *nib =  [UINib nibWithNibName:kTweetTableViewCellNibName bundle:nil];
  [self.tweetSearchTableView registerNib:nib forCellReuseIdentifier:kTweetTableViewCellId];
}

...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  TweetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TweetTableViewCellId" forIndexPath:indexPath];
}

@end
</code>```

any suggestion?

答: You might have two views pointing to the same class in your .xib  Double check your interface files</p>

Body:
I got intermitent error when try to use nib that was registered for reuse. Im using the same custom cell on two ViewControllers.

2013-09-05 11:04:08.476 xxx[51395:c07] *** Terminating app due to
  uncaught exception 'NSInternalInconsistencyException', reason:
  'invalid nib registered for identifier (TweetTableViewCellId) - nib
  must contain exactly one top level object which must be a
  UITableViewCell instance'

Im use NIB file with one view at Object list - on top, sure -. It has type TweetViewCell, it that extends UITableViewCell -.

I already define [b]identifier[/b] as "TweetTableViewCellId"

Im load nib and did register it on viewDidLoad (i already debug and nib object aways is loaded)

I try to recover registered cell using the same id.

some piece of code

// First Controller to use custom Cell
@implementation TweetsViewController

- (void) viewDidLoad
{
...
  UINib *nib =  [UINib nibWithNibName:kTweetTableViewCellNibName bundle:nil];
  [self.tweetsTableView registerNib:nib forCellReuseIdentifier:@"TweetTableViewCellId"];

..
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  TweetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTweetTableViewCellId forIndexPath:indexPath];
...
}

@end

// second Controller to use custom Cell

@implementation OfflineEpisodeModalViewController

- (void) viewDidLoad
{
  UINib *nib =  [UINib nibWithNibName:kTweetTableViewCellNibName bundle:nil];
  [self.tweetSearchTableView registerNib:nib forCellReuseIdentifier:kTweetTableViewCellId];
}

...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  TweetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TweetTableViewCellId" forIndexPath:indexPath];
}

@end

any suggestion?


问:
REGEX to get all numbers in a string, even if other characters are in between
I have a Google Spreadsheet populated with information from a real estate website.

The phone numbers came across in a single cell like this *Cell #* (602) 695-2036 or *Cell #* 602-575-1008. I had an REGEXEXTRACT() function using \d-\d-\d which worked for numbers formatted like the second, but I need something that works on all cell number strings, regardless of formatting or characters between. So I want (602) 695-2036 to return 6026952036 and 602-575-1008 to return 6025751008.

Spreadsheet. Numbers are in row 5 and one is in row 6.

答:
Try this in your sample sheet for A5:</p>

```<code>=REGEXreplace(A5,"\D+", "")
</code>```

Body:
Try this in your sample sheet for A5:

=REGEXreplace(A5,"\D+", "")


问:
Add widget to activity
hey,
I've developped a car dock application.
I can add shortcuts in my activity but how can I add a system widget ?</p>

答: You need to extend the AppWidgetProvider class in your application. See a tutorial here and make sure you follow the design guidelines.</p>

ContentLicense: CC BY-SA 2.5

Title: Add widget to activity


问:
Moving EditText input from an Activity to a Fragment of a swipe view
This is the MainActivity upon launch.  The user puts in a number then clicks the button and the Intent brings them to a swipe view with the number they entered.

```<code>public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    continueButton = (Button) findViewById(R.id.ContinueButton);
    NumberET = (EditText) findViewById(R.id.etTotalAmount);
    continueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            number = NumberET.getText().toString();
            if (number.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("AMOUNT_KEY", number);
                FixedCosts fragment = new FixedCosts();
                fragment.setArguments(bundle);
                FragmentTransaction t = getSupportFragmentManager().beginTransaction();
                t.replace(R.id.container, fragment).commit();
                Intent intent = new Intent(MainActivity.this, FragmentActivity.class);
                intent.putExtra("NUMBER", number);
                startActivity(intent);
            }
        }
    });
}
</code>```

In the fragment, I would like to set the text of a textview to display that number.  I cannot get this number to send from this Activity class to the Fragment.  How can I fix this?

Fragment:

```<code>ublic class FixedCosts extends Fragment {
String amount;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fixed_costs_fragment, container, false);
    amount = this.getArguments().getString("AMOUNT_KEY");

    TextView TitletextView = (TextView) view.findViewById(R.id.amountTitle);
    TitletextView.setText(amount);
    return view;}}
</code>```

Here is the FragmentActivity that sets the swipe view:

```<code>public class FragmentActivity extends AppCompatActivity {
public static final String MY_CUSTOM_FRAGMENT_KEY = "I_GOT_THE_KEYS";

String MoneyAmount;

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment);

    /*MoneyAmount = getIntent().getExtras().getString("AmountMoney");*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}
private Fragment createCustomFragment(){
    Bundle bundle = new Bundle();
    bundle.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);

    PlaceholderFragment placeholderFragment = new PlaceholderFragment();
    placeholderFragment.setArguments(bundle);
    return placeholderFragment;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber, String MoneyAmount) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        args.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        Bundle bundle = getArguments();
        /*String amount = bundle.getString(MY_CUSTOM_FRAGMENT_KEY);
        TextView TitletextView = (TextView) FixedCosts.class.findViewById(R.id.amountTitle);
        TitletextView.setText(amount);*/

        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
       switch (position){
           case 0:
               FixedCosts fixedCosts = new FixedCosts();

               return fixedCosts;
       }
        return PlaceholderFragment.newInstance(position + 1, MoneyAmount);
    }
    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Fixed Costs";
            case 1:
                return "Long term investments";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}
</code>```

}

答:
I fixed the issue by saving the value to SharedPreferences.

In the MainActivity.class:

```<code>SharedPreferences saveAmount = getSharedPreferences("MyPrefs", 0);
    final SharedPreferences.Editor editor = saveAmount.edit();
editor.putString("AMOUNT", amount);
                editor.commit();
</code>```

In the Fragment class:

```<code>SharedPreferences sharedPrefs = this.getActivity().getSharedPreferences("MyPrefs", 0);

    String amount = (sharedPrefs.getString("AMOUNT", "Ummmmm"));
</code>```

Body:
This is the MainActivity upon launch.  The user puts in a number then clicks the button and the Intent brings them to a swipe view with the number they entered.

public class MainActivity extends AppCompatActivity{
String number;
Button continueButton;
EditText NumberET;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    continueButton = (Button) findViewById(R.id.ContinueButton);
    NumberET = (EditText) findViewById(R.id.etTotalAmount);
    continueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            number = NumberET.getText().toString();
            if (number.equals("")) {
                Toast.makeText(getApplicationContext(), "Enter Number", Toast.LENGTH_SHORT).show();
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("AMOUNT_KEY", number);
                FixedCosts fragment = new FixedCosts();
                fragment.setArguments(bundle);
                FragmentTransaction t = getSupportFragmentManager().beginTransaction();
                t.replace(R.id.container, fragment).commit();
                Intent intent = new Intent(MainActivity.this, FragmentActivity.class);
                intent.putExtra("NUMBER", number);
                startActivity(intent);
            }
        }
    });
}

In the fragment, I would like to set the text of a textview to display that number.  I cannot get this number to send from this Activity class to the Fragment.  How can I fix this?

Fragment:

ublic class FixedCosts extends Fragment {
String amount;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fixed_costs_fragment, container, false);
    amount = this.getArguments().getString("AMOUNT_KEY");

    TextView TitletextView = (TextView) view.findViewById(R.id.amountTitle);
    TitletextView.setText(amount);
    return view;}}

Here is the FragmentActivity that sets the swipe view:

public class FragmentActivity extends AppCompatActivity {
public static final String MY_CUSTOM_FRAGMENT_KEY = "I_GOT_THE_KEYS";

String MoneyAmount;

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment);

    /*MoneyAmount = getIntent().getExtras().getString("AmountMoney");*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}
private Fragment createCustomFragment(){
    Bundle bundle = new Bundle();
    bundle.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);

    PlaceholderFragment placeholderFragment = new PlaceholderFragment();
    placeholderFragment.setArguments(bundle);
    return placeholderFragment;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber, String MoneyAmount) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        args.putString(MY_CUSTOM_FRAGMENT_KEY, MoneyAmount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        Bundle bundle = getArguments();
        /*String amount = bundle.getString(MY_CUSTOM_FRAGMENT_KEY);
        TextView TitletextView = (TextView) FixedCosts.class.findViewById(R.id.amountTitle);
        TitletextView.setText(amount);*/

        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
       switch (position){
           case 0:
               FixedCosts fixedCosts = new FixedCosts();

               return fixedCosts;
       }
        return PlaceholderFragment.newInstance(position + 1, MoneyAmount);
    }
    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Fixed Costs";
            case 1:
                return "Long term investments";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}

}

Body:
I fixed the issue by saving the value to SharedPreferences.

In the MainActivity.class:

SharedPreferences saveAmount = getSharedPreferences("MyPrefs", 0);
    final SharedPreferences.Editor editor = saveAmount.edit();
editor.putString("AMOUNT", amount);
                editor.commit();

In the Fragment class:

SharedPreferences sharedPrefs = this.getActivity().getSharedPreferences("MyPrefs", 0);

    String amount = (sharedPrefs.getString("AMOUNT", "Ummmmm"));


问:
Jquery hack to change video for safari and other browsers
I am adding a video in my website but its not working on safari. I am using 'webm' video format. and i need to put 'mov' video format in safari.

Please suggest a hack in JQuery so that when safari opens, then 'mov' video is played and for other browsers 'webm' video is played.

答:
Detect which browser you are viewing on and then display the proper video</p>

```<code>if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {//play .mov}
else{//play .webm}
</code>```

Body:
Detect which browser you are viewing on and then display the proper video

if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {//play .mov}
else{//play .webm}


问:
Get last "column" after .str.split() operation on column in pandas DataFrame
I have a column in a pandas DataFrame that I would like to split on a single space. The splitting is simple enough with DataFrame.str.split(' '), but I can't make a new column from the last entry. When I .str.split() the column I get a list of arrays and I don't know how to manipulate this to get a new column for my DataFrame.

Here is an example. Each entry in the column contains 'symbol data price' and I would like to split off the price (and eventually remove the "p"... or "c" in half the cases).

```<code>import pandas as pd
temp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})
temp2 = temp.ticker.str.split(' ')
</code>```

which yields

```<code>0    ['spx', '5/25/2001', 'p500']
1    ['spx', '5/25/2001', 'p600']
2    ['spx', '5/25/2001', 'p700']
</code>```

But temp2[0] just gives one list entry's array and temp2[:][-1] fails. How can I convert the last entry in each array to a new column? Thanks!

答:
https://pandas.pydata.org/pandas-docs/stable/text.html

```<code>s2 = pd.Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'])
s2.str.split('_').str.get(1)
</code>```

or

```<code>s2.str.split('_').str[1]
</code>```

Body:
I have a column in a pandas DataFrame that I would like to split on a single space. The splitting is simple enough with DataFrame.str.split(' '), but I can't make a new column from the last entry. When I .str.split() the column I get a list of arrays and I don't know how to manipulate this to get a new column for my DataFrame.

Here is an example. Each entry in the column contains 'symbol data price' and I would like to split off the price (and eventually remove the "p"... or "c" in half the cases).

import pandas as pd
temp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})
temp2 = temp.ticker.str.split(' ')

which yields

0    ['spx', '5/25/2001', 'p500']
1    ['spx', '5/25/2001', 'p600']
2    ['spx', '5/25/2001', 'p700']

But temp2[0] just gives one list entry's array and temp2[:][-1] fails. How can I convert the last entry in each array to a new column? Thanks!

Body:
https://pandas.pydata.org/pandas-docs/stable/text.html

s2 = pd.Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'])
s2.str.split('_').str.get(1)

or

s2.str.split('_').str[1]


问:
Null pointer detection in tcc
I created a very simple linked list and noticed a difference in output for tcc filename.c vs tcc filename.c -run for my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct llist {
    struct llist *next;
    struct llist *last;
    struct llist *first;
    int value;
    int item;
    int *length;
};

struct llist *newList(int v){

    struct llist *l1 = malloc(sizeof(struct llist));
    l1 -> length = malloc(sizeof(int));
    *l1 -> length = 1;

    l1 -> value = v;
    l1 -> item = 0;
    l1 -> first = l1;

    return l1;
}

struct llist *appendList(struct llist *l1, int v){

    struct llist *l2 = malloc(sizeof(struct llist));

    l2 -> value = v;
    l2 -> last = l1;
    l2 -> first = l1 -> first;
    l2 -> length = l1 -> length;
    *l2 -> length += 1;
    l2 -> item = l1 -> item + 1;

    l1 -> next = l2;

    return l2;
};

int main(){
    struct llist *list = newList(4);
    list = appendList(list, 6);
    list = appendList(list, 8);
    list = appendList(list, 10);

    list = list -> first;

    int end = 0;
    while(end==0){

        printf("VAL: %d\n", list -> value);

        if(list -> next == NULL){
            printf("END\n");
            end = 1;
        }else{

            list = list -> next;
        }
    }

    return 0;
}
</code>```

For compiling with tcc filename.c and then running it produces the output I expected:

```<code>VAL: 4
VAL: 6
VAL: 8
VAL: 10
END
</code>```

It's also the output I get in GCC and clang.

When I use tcc filename.c -run I get:

```<code>VAL: 4
VAL: 6
VAL: 8
VAL: 10
VAL: 27092544
VAL: 1489483720
VAL: 0
END
</code>```

With the last number always being zero and the other two extra values being different every time I run.

I figured out the solution which was adding l1 -> next = NULL; in the newList function and l2 -> next = NULL; in the appendList function.

But I was wondering why there was a difference in output. Is there a bug in the compiler or was I wrong for not initialising the pointer to NULL even though it works in most compilers?

答:
Normally when you debug a program the debugger initialize everything, but in production there is no initialization, so next values is not null

Initialize next variables.

Title: Null pointer detection in tcc

Body:
I created a very simple linked list and noticed a difference in output for tcc filename.c vs tcc filename.c -run for my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct llist {
    struct llist *next;
    struct llist *last;
    struct llist *first;
    int value;
    int item;
    int *length;
};

struct llist *newList(int v){

    struct llist *l1 = malloc(sizeof(struct llist));
    l1 -> length = malloc(sizeof(int));
    *l1 -> length = 1;

    l1 -> value = v;
    l1 -> item = 0;
    l1 -> first = l1;

    return l1;
}

struct llist *appendList(struct llist *l1, int v){

    struct llist *l2 = malloc(sizeof(struct llist));

    l2 -> value = v;
    l2 -> last = l1;
    l2 -> first = l1 -> first;
    l2 -> length = l1 -> length;
    *l2 -> length += 1;
    l2 -> item = l1 -> item + 1;

    l1 -> next = l2;

    return l2;
};

int main(){
    struct llist *list = newList(4);
    list = appendList(list, 6);
    list = appendList(list, 8);
    list = appendList(list, 10);

    list = list -> first;

    int end = 0;
    while(end==0){

        printf("VAL: %d\n", list -> value);

        if(list -> next == NULL){
            printf("END\n");
            end = 1;
        }else{

            list = list -> next;
        }
    }

    return 0;
}

For compiling with tcc filename.c and then running it produces the output I expected:

VAL: 4
VAL: 6
VAL: 8
VAL: 10
END

It's also the output I get in GCC and clang.

When I use tcc filename.c -run I get:

VAL: 4
VAL: 6
VAL: 8
VAL: 10
VAL: 27092544
VAL: 1489483720
VAL: 0
END

With the last number always being zero and the other two extra values being different every time I run.

I figured out the solution which was adding l1 -> next = NULL; in the newList function and l2 -> next = NULL; in the appendList function.

But I was wondering why there was a difference in output. Is there a bug in the compiler or was I wrong for not initialising the pointer to NULL even though it works in most compilers?


答:
Try to replace all non-digits with nothing. Something like

```<code>=regexreplace(A1, "\D+", )
</code>```

should work. You can also iterate the regexreplace over an array..

```<code>=arrayformula(if(len(A1:A), regexreplace(A1:A, "\D+",),))
</code>```

Change range to suit and see if that works?

Title: REGEX to get all numbers in a string, even if other characters are in between

Body:
I have a Google Spreadsheet populated with information from a real estate website.

The phone numbers came across in a single cell like this *Cell #* (602) 695-2036 or *Cell #* 602-575-1008. I had an REGEXEXTRACT() function using \d-\d-\d which worked for numbers formatted like the second, but I need something that works on all cell number strings, regardless of formatting or characters between. So I want (602) 695-2036 to return 6026952036 and 602-575-1008 to return 6025751008.

Spreadsheet. Numbers are in row 5 and one is in row 6.

Body:
Try to replace all non-digits with nothing. Something like

=regexreplace(A1, "\D+", )

should work. You can also iterate the regexreplace over an array..

=arrayformula(if(len(A1:A), regexreplace(A1:A, "\D+",),))

Change range to suit and see if that works?


问:
Manage click event on remove_nested_fields button with nested_forms gem
What I need to do is just to increase the value of a "p" tag everytime the add button is pressed or decrease the value of the same "p" tag the delete button is pressed.

Well, nested forms uses a partial to add a new row to manage a nested form inside de main form view here is my partial code:

```<code><tr class="fields">
 <td>
    <%= f.text_field :nombre, class: 'form-control' %>
 </td>
 <td>
    <%
        concat f.select :idtipodocumento, CrTipoDocumento.all.collect
        {|p| [ p.nombre, p.id ] }, {prompt: 'Seleccione el tipo de
        documento'}, :class=>'form-control'
    %>
 </td>
 <td>
    <%= f.text_field :documento, class: 'form-control' %>
 </td>
 <td>
    <%= f.link_to_remove raw('<i class="fa fa-minus-circle" aria-
     hidden="true"></i>'), :class =>'btn btn-danger' %>
    </td>
 </tr>
</code>```

In my main view y render this partial with this code:

```<code>         <tbody>
            <fieldset id="acreditados">
              <%= f.fields_for :cr_acreditados, :wrapper => false %>
            </fieldset>
         </tbody>
</code>```

and I have also the add button to add new rows which works just good:

```<code>      <div id="addBtn">
        <% if @counter >= 1 %>
          <p><%= f.link_to_add raw('<i class="fa fa-plus-circle" aria-
        hidden="true"></i>'), :cr_acreditados, id: 'btna', :class =>
        'btn btn-primary lta', "data-target" => "#DAC" %></p>
        <% else %>
          <p class="text-center"><h3>No dispone de mas
          acreditaciones</h3></p>
        <% end %>
      </div>
</code>```

And Im using a javascript to update a "p tag" text every time the add button is pressed or the delete button is pressed, the javascript for the add button works just good! here is the code:

```<code>$( document ).ready(function() {
   $('.add_nested_fields').click(function(adLine){
      var cnt = document.getElementById('acd').innerHTML;
      if(cnt <= 1){
          if(cnt == 0)
          {
              alert("You cant add more rows")
              adLine.preventDefault();
              adLine.stopPropagation();
          }
          else
          {
              var res = cnt - 1;
              $('#acd').html(res);
          }
       }
       else{
             var res = cnt - 1;
             $('#acd').html(res);
       }
   });
});
</code>```

And I want the delete button to do the inverse of that which will be to +1 to the "p tag" text, thing is, javascript code cant detect click event on the new added rows but he detects the rows loaded with data from database the moment the view loads, here is my actual js code for the delete button:

```<code>$( document ).ready(function() {
$('.remove_nested_fields').click(function(remLine){
    var cnt = document.getElementById('acd').innerHTML;
    cnt = parseInt(cnt,10)
    var res = cnt + 1;
    $('#acd').html(res);
});
});
</code>```

答:
SOlved it! just have dig in a little into official documentation of the gem:
https://github.com/ryanb/nested_form

He even did a method to count and limit the max of fields! here is the link:
https://github.com/ryanb/nested_form/wiki/How-to:-limit-max-count-of-nested-fields

Body:
What I need to do is just to increase the value of a "p" tag everytime the add button is pressed or decrease the value of the same "p" tag the delete button is pressed.

Well, nested forms uses a partial to add a new row to manage a nested form inside de main form view here is my partial code:

    <%= f.text_field :nombre, class: 'form-control' %>

    <%
        concat f.select :idtipodocumento, CrTipoDocumento.all.collect
        {|p| [ p.nombre, p.id ] }, {prompt: 'Seleccione el tipo de
        documento'}, :class=>'form-control'
    %>

    <%= f.text_field :documento, class: 'form-control' %>

    <%= f.link_to_remove raw(''), :class =>'btn btn-danger' %>

In my main view y render this partial with this code:

            <fieldset id="acreditados">
              <%= f.fields_for :cr_acreditados, :wrapper => false %>
            </fieldset>

and I have also the add button to add new rows which works just good:

        <% if @counter >= 1 %>

<%= f.link_to_add raw(''), :cr_acreditados, id: 'btna', :class =>
        'btn btn-primary lta', "data-target" => "#DAC" %>

        <% else %>

No dispone de mas
          acreditaciones

        <% end %>

And Im using a javascript to update a "p tag" text every time the add button is pressed or the delete button is pressed, the javascript for the add button works just good! here is the code:

$( document ).ready(function() {
   $('.add_nested_fields').click(function(adLine){
      var cnt = document.getElementById('acd').innerHTML;
      if(cnt <= 1){
          if(cnt == 0)
          {
              alert("You cant add more rows")
              adLine.preventDefault();
              adLine.stopPropagation();
          }
          else
          {
              var res = cnt - 1;
              $('#acd').html(res);
          }
       }
       else{
             var res = cnt - 1;
             $('#acd').html(res);
       }
   });
});

And I want the delete button to do the inverse of that which will be to +1 to the "p tag" text, thing is, javascript code cant detect click event on the new added rows but he detects the rows loaded with data from database the moment the view loads, here is my actual js code for the delete button:

$( document ).ready(function() {
$('.remove_nested_fields').click(function(remLine){
    var cnt = document.getElementById('acd').innerHTML;
    cnt = parseInt(cnt,10)
    var res = cnt + 1;
    $('#acd').html(res);
});
});


问:
Issue when printing char buffer
I want to store the filename path in a char variable and pass it later via function call. To do so, I declared the following char buffer:

```<code>char *filename_path =  malloc(100* sizeof(char));
</code>```

Now, to test that, I assigned it using a path followed by printing the value of the buffer to make sure it fits well.

```<code>filename_path= "../Datasets/Cluster(%d)%s";
printf("%s\n", filename_path);
...
free(filename_path);
</code>```

However, I get this error :

```<code>../Datasets/Cluster(%d)%s
k.out(1154,0x7fff9843c3c0) malloc: *** error for object 0x103fbbacb: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
</code>```

Can someone hint me where the issue could be? Thank you

答:
The problem is that you need to save your original pointer in order to free it:

So store a temporary pointer and free that instead.

```<code>char *filename_path ,*temp_path;
filename_path  =  malloc(100* sizeof(char));
temp_path = filename_path;

//your code for filename_path

free(temp_path);
</code>```

Title: Issue when printing char buffer

Body:
I want to store the filename path in a char variable and pass it later via function call. To do so, I declared the following char buffer:

char *filename_path =  malloc(100* sizeof(char));

Now, to test that, I assigned it using a path followed by printing the value of the buffer to make sure it fits well.

filename_path= "../Datasets/Cluster(%d)%s";
printf("%s\n", filename_path);
...
free(filename_path);

However, I get this error :

../Datasets/Cluster(%d)%s
k.out(1154,0x7fff9843c3c0) malloc: *** error for object 0x103fbbacb: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

Can someone hint me where the issue could be? Thank you

Body:
The problem is that you need to save your original pointer in order to free it:

So store a temporary pointer and free that instead.

char *filename_path ,*temp_path;
filename_path  =  malloc(100* sizeof(char));
temp_path = filename_path;

//your code for filename_path

free(temp_path);


问:
Resampling pandas frame with function depending on column
I have a recurring issue where I have data frames in which some columns are angles while others are not, and I'd like to resample in such a way that mean values are computed correctly for each type.  Here is a small example:

```<code>import pandas as pd
import numpy as np

def angleMean(x):
    d2r = np.pi/180.
    cosMean = np.mean(np.cos(x * d2r))
    sinMean = np.mean(np.sin(x * d2r))
    return np.arctan2(sinMean,cosMean) / d2r

# Define data fame
t = pd.date_range("00:00", "3:00", freq="30min")
df = pd.DataFrame({'t':t,'x':[350.,0.,2.,4.,6.,8.,10.],'theta':[350.,0.,2.,4.,6.,8.,10.]}).set_index('t')

# Using normal mean
print df.resample('1H').mean()

# Using angular mean
print df.resample('1H').apply(angleMean)
</code>```

The above examples shows either type of averaging applied to all columns to get the resampling.

Is there a good way that I can define a function that uses the column name to determine the correct averaging to apply to each column?

答:
By calling apply, you pass each column of the DataFrame to the specified function as a Series-Object. You can get the name of the Series (i.e. the column name) via the .name attribute:

```<code>def conditionalMean(x):
  if x.name == 'theta':
    return angleMean(x)
  else:
    return x.mean()

print df.resample('1H').apply(conditionalMean)
</code>```

Body:
I have a recurring issue where I have data frames in which some columns are angles while others are not, and I'd like to resample in such a way that mean values are computed correctly for each type.  Here is a small example:

import pandas as pd
import numpy as np

def angleMean(x):
    d2r = np.pi/180.
    cosMean = np.mean(np.cos(x * d2r))
    sinMean = np.mean(np.sin(x * d2r))
    return np.arctan2(sinMean,cosMean) / d2r

# Define data fame
t = pd.date_range("00:00", "3:00", freq="30min")
df = pd.DataFrame({'t':t,'x':[350.,0.,2.,4.,6.,8.,10.],'theta':[350.,0.,2.,4.,6.,8.,10.]}).set_index('t')

# Using normal mean
print df.resample('1H').mean()

# Using angular mean
print df.resample('1H').apply(angleMean)

The above examples shows either type of averaging applied to all columns to get the resampling.

Is there a good way that I can define a function that uses the column name to determine the correct averaging to apply to each column?

Body:
By calling apply, you pass each column of the DataFrame to the specified function as a Series-Object. You can get the name of the Series (i.e. the column name) via the .name attribute:

def conditionalMean(x):
  if x.name == 'theta':
    return angleMean(x)
  else:
    return x.mean()

print df.resample('1H').apply(conditionalMean)


问:
c strcmp source code
```<code>int strcmp(const char *s1, const char *s2)

{
  int ret = 0;

  while (!(ret = *(unsigned char *) s1 - *(unsigned char *) s2) && *s2) ++s1, ++s2;

  if (ret < 0)

    ret = -1;
  else if (ret > 0)

    ret = 1 ;

  return ret;
}
</code>```

I review the code from : http://www.jbox.dk/sanos/source/lib/string.c.html

I suppose that there're some problem.
If strlen(s2)>strlen(s1),then ++s1 may beyond the range. Unfortunately, then the function return error.

答: No, there's not such a problem, provided that s2 is '\0'-terminated.</p>

Title: c strcmp source code

Body:
int strcmp(const char *s1, const char *s2)

{
  int ret = 0;

  while (!(ret = *(unsigned char *) s1 - *(unsigned char *) s2) && *s2) ++s1, ++s2;

  if (ret < 0)

    ret = -1;
  else if (ret > 0)

    ret = 1 ;

  return ret;
}

I review the code from : http://www.jbox.dk/sanos/source/lib/string.c.html

I suppose that there're some problem.
If strlen(s2)>strlen(s1),then ++s1 may beyond the range. Unfortunately, then the function return error.


问:
RapidSSL to AWS Certificate Manager
I have a few certificates that were purchased on RapidSSL/Symantec, and I have switched to them to the AWS Certificate Manager (AWS Issued). My certificates on RapidSSL are expiring in 20 days and I was wondering what should/must be done to make sure the transition from RapidSSL to AWS goes seamlessly.

Are there steps that must be taken, or does AWS Certificate Manager instantly take over once the RapidSSL certs expire?

答:
At the moment, certificates provided by ACM can only be used with specific AWS services.

Elastic Load Balancing

Amazon CloudFront

Amazon API Gateway

AWS Elastic Beanstalk

To use ACM certificate, it would required you to use one of these services infront of your EC2 instance configured with ACM certificate and forwarded traffic to EC2. You can keep them without enabling HTTPS. When your RapidSSL certificate expires in EC2, you need to manually enable HTTPS in the service you used infront and then remove the RapidSSL certificate from EC2.

Note: Also you can make the entire process automated by using AWS CLI if needed which requires additional effort.

Title: RapidSSL to AWS Certificate Manager


问:
Convert unix time to readable date in pandas dataframe
I have a dataframe with unix times and prices in it. I want to convert the index column so that it shows in human readable dates.

So for instance I have date as 1349633705 in the index column but I'd want it to show as 10/07/2012 (or at least 10/07/2012 18:15).

For some context, here is the code I'm working with and what I've tried already:

```<code>import json
import urllib2
from datetime import datetime
response = urllib2.urlopen('http://blockchain.info/charts/market-price?&format=json')
data = json.load(response)
df = DataFrame(data['values'])
df.columns = ["date","price"]
#convert dates
df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.index = df.date
</code>```

As you can see I'm using
df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d")) here which doesn't work since I'm working with integers, not strings. I think I need to use datetime.date.fromtimestamp but I'm not quite sure how to apply this to the whole of df.date.

Thanks.

答:
If you try using:

```<code>df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))
</code>```

and receive an error :

"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"

This means the DATE_FIELD is not specified in seconds.

In my case, it was milli seconds - EPOCH time.

The conversion worked using below:

```<code>df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms'))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe with unix times and prices in it. I want to convert the index column so that it shows in human readable dates.

So for instance I have date as 1349633705 in the index column but I'd want it to show as 10/07/2012 (or at least 10/07/2012 18:15).

For some context, here is the code I'm working with and what I've tried already:

import json
import urllib2
from datetime import datetime
response = urllib2.urlopen('http://blockchain.info/charts/market-price?&format=json')
data = json.load(response)
df = DataFrame(data['values'])
df.columns = ["date","price"]
#convert dates
df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.index = df.date

As you can see I'm using
df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d")) here which doesn't work since I'm working with integers, not strings. I think I need to use datetime.date.fromtimestamp but I'm not quite sure how to apply this to the whole of df.date.

Thanks.

Body:
If you try using:

df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],***unit='s'***))

and receive an error :

"pandas.tslib.OutOfBoundsDatetime: cannot convert input with unit 's'"

This means the DATE_FIELD is not specified in seconds.

In my case, it was milli seconds - EPOCH time.

The conversion worked using below:

df[DATE_FIELD]=(pd.to_datetime(df[DATE_FIELD],unit='ms'))


答:
Look at it this way:

You are allocating 100 bytes of memory and assigning the filename_path pointer to point to that allocated memory.

You now change filename_path to point to the static string "../Datasets/Cluster(%d)%s".

Since you changed where filename_path points to, you no longer have a pointer to the memory you allocated earlier and no longer have any way to free it.

When you attempt to free filename_path you are actually attempting to free the static string "../Datasets/Cluster(%d)%s" which of course as the error message says, was not actually allocated by malloc.

Title: Issue when printing char buffer


问:
Should HttpMessageHandler use ConfigureAwait(false)
If I have an asynchronous call inside a HttpMessageHandler, should it use the .ConfigureAwait method e.g.</p>

```<code>/// <summary>
/// Handler to assign the MD5 hash value if content is present
/// </summary>
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content == null)
        {
            return await base.SendAsync(request, cancellationToken);
        }

        await request.Content.AssignMd5Hash().ConfigureAwait(false);

        var response = await base.SendAsync(request, cancellationToken);

        return response;
    }
}
</code>```

答:
I assume you are talking about this line and if it is OK to have ConfigureAwait(false) on that line.

```<code>await request.Content.AssignMd5Hash().ConfigureAwait(false);
</code>```

No, on the next line you call SendAsync with the Http Request. You can't switch threads and still have access to the correct http request context so you have to use ConfigureAwait(true) or omit the call to ConfigureAwait all together.

Body:
If I have an asynchronous call inside a HttpMessageHandler, should it use the .ConfigureAwait method e.g.

///
/// Handler to assign the MD5 hash value if content is present
///
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content == null)
        {
            return await base.SendAsync(request, cancellationToken);
        }

        await request.Content.AssignMd5Hash().ConfigureAwait(false);

        var response = await base.SendAsync(request, cancellationToken);

        return response;
    }
}

Body:
I assume you are talking about this line and if it is OK to have ConfigureAwait(false) on that line.

await request.Content.AssignMd5Hash().ConfigureAwait(false);

No, on the next line you call SendAsync with the Http Request. You can't switch threads and still have access to the correct http request context so you have to use ConfigureAwait(true) or omit the call to ConfigureAwait all together.


问:
django-pyodbc for Django 1.11
I am currently using Django 1.11.1 and am trying to connect to my iSeries Database using the django-pyodbc engine.  However all the documentation I can find states django-pyodbc is only supported through Django 1.10.  Is there any coding modifications I can make to have it support 1.11?   </p>

答:
There are several forks and versions named django-pyodbc, however, the best maintained I've found is django-pyodbc-azure. It supports Django 1.11 and can be found here:

https://github.com/michiya/django-pyodbc-azure

I have used it with SQL Server 2005 - 2016 (but never Azure). Good luck!

Title: django-pyodbc for Django 1.11


答:
Your code is overwriting the pointer returned by malloc with a new, constant string (the filename_path = "../Datasets/Cluster(%d)%s" line). It is, then, trying to free it.

You can't do that, because the pointer is not the same as the one returned by malloc anymore.

To copy your contents into your malloc'ed string, you should use strncpy.

Like this:

```<code>char *filename_path =  malloc(100* sizeof(char));

strncpy(filename_path, "../Datasets/Cluster(%d)%s", 100);
printf("%s\n", filename_path);

free(filename_path);
</code>```

Title: Issue when printing char buffer

Body:
Your code is overwriting the pointer returned by malloc with a new, constant string (the filename_path = "../Datasets/Cluster(%d)%s" line). It is, then, trying to free it.

You can't do that, because the pointer is not the same as the one returned by malloc anymore.

To copy your contents into your malloc'ed string, you should use strncpy.

Like this:

char *filename_path =  malloc(100* sizeof(char));

strncpy(filename_path, "../Datasets/Cluster(%d)%s", 100);
printf("%s\n", filename_path);

free(filename_path);


答:
The line

```<code>filename_path= "../Datasets/Cluster(%d)%s";
</code>```

does not copy the contents of the string literal to the memory pointed to by filename_path; it overwrites the value of filename_path with the address of the string literal.  You're basically throwing away the value returned from malloc, leading to a) a memory leak, and b) the error when calling free.

Instead of using the assignment operator, use the strcpy function:

```<code>strcpy( filename_path, "../Datasets/Cluster(%d)%s" );
</code>```

Title: Issue when printing char buffer

Body:
The line

filename_path= "../Datasets/Cluster(%d)%s";

does not copy the contents of the string literal to the memory pointed to by filename_path; it overwrites the value of filename_path with the address of the string literal.  You're basically throwing away the value returned from malloc, leading to a) a memory leak, and b) the error when calling free.

Instead of using the assignment operator, use the strcpy function:

strcpy( filename_path, "../Datasets/Cluster(%d)%s" );


问:
Images dissappear when height/weidth switched from pixels to percentage?
So I have 3 circular images on my page. For some reason, when I change their height/width from px to %, the images just dissappear. They work perfectly at 200px height/width, and at 50px.. but I want them at 20%.

Code:

<!DOCTYPE html>

  <link rel="stylesheet" href="styles.css">
   <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Welcome to RyanTeaches

Activities

Activities

```

Site to see:
http://ryanteaches.com/newindex.html

Any ideas why they dissappear?

Cheers.

答:
It's the height that's causing this problem. Setting the width this way will work just fine, and if you had actual img tags instead of inserting the images using css, you could use height:auto, and it would scale the image as you want.

However, when you say height: 20%, it will calculate the element's height as a percentage of its parent's height. Since you haven't defined the height of any of the elements' ancestors, it will be 0 (you can confirm using your browser's inspector).

So, you could define the height of the container div, but given that you want it to be relative to the width of the device, your best option is probably to use img tags and height:auto instead of background-image.

UPDATE: per your comment, here's an example using img tags. I think this is more or less what you're trying to achieve.

  body{width: 100%;}
/*Parallax*/

.parallax{
    background-image: url("bg.jpg");
    height: 540px;
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    margin: 0;
    position:relative;
}
/*Parallax*/

#header{
 position: absolute;
  top: 40%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
  text-align: center;
 left: 20%;
  font-size: 4vw;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 15px;
  padding-bottom: 20px;
  background-color: #357eca;
  width: 50%;
  word-wrap: break-word;
  opacity: 0.9;
  font-weight: 900;
  padding-left: 5%;
  padding-right: 5%;

}

h5
{
  color:white;
  text-align: center;
    font-family: 'Montserrat';
      text-transform: uppercase;
      font-weight: 900;

  /*-webkit-margin-before:0.67em;
  -webkit-margin-after:0.67em;
  -webkit-margin-start:0px;
  -webkit-margin-end:0px;
  -webkit-tap-highlight-colour:rgba(0,0,0,0);
  -webkit-font-smoothing:antialiased;
  -webkit-box-direction:normal;
  position: absolute;*/
}
h5:after, h5:before
{
  content: '';
  width: 50px;
  height: 2px;
  background: black;
  margin: 0 10px;
}
/*--- Circular images --- */

.img-circular1,
.img-circular2,
.img-circular3 {
  width:100%;
  background-size: cover;
  border-radius: 50%;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  background: red;
  display: block;
  margin: 0 auto;
}

#container1 {
  top: 100px;
  position: relative;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: auto;
  width: 70%;
  background-color: green;
  overflow: auto;
  bottom: 0;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.wrap {
  //flex-grow: 1;
  width: 25%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navigation"></div>

<div class="parallax"><h5 id="header"><b>Welcome to RyanTeaches</b></h5></div>

<!--<img src="bg.jpg" style="top:60px;height: 510px;min-width: 100%;">-->
<div id="content">
<h2 style="margin-top: 0px;">Activities</h2>
</div>

<div id="container1" style="padding-bottom: 400px;">
  <div class="wrap">
    <img class="img-circular1" src="http://via.placeholder.com/150x150"/>
  </div>
  <div class="wrap">
    <img class="img-circular2" src="http://via.placeholder.com/150x150"/>
  </div>
  <div class="wrap">
    <img class="img-circular3" src="http://via.placeholder.com/150x150"/>
  </div>
</div>

<div id="content">
<h2 style="margin-top: 0px;">Activities</h2>
</div></code>```

Body:
So I have 3 circular images on my page. For some reason, when I change their height/width from px to %, the images just dissappear. They work perfectly at 200px height/width, and at 50px.. but I want them at 20%.

Code:

<!DOCTYPE html>

  <link rel="stylesheet" href="styles.css">
   <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Welcome to RyanTeaches

Activities

Activities

Site to see:
http://ryanteaches.com/newindex.html

Any ideas why they dissappear?

Cheers.

Body:
It's the height that's causing this problem. Setting the width this way will work just fine, and if you had actual img tags instead of inserting the images using css, you could use height:auto, and it would scale the image as you want.

However, when you say height: 20%, it will calculate the element's height as a percentage of its parent's height. Since you haven't defined the height of any of the elements' ancestors, it will be 0 (you can confirm using your browser's inspector).

So, you could define the height of the container div, but given that you want it to be relative to the width of the device, your best option is probably to use img tags and height:auto instead of background-image.

UPDATE: per your comment, here's an example using img tags. I think this is more or less what you're trying to achieve.

  body{width: 100%;}
/*Parallax*/

.parallax{
    background-image: url("bg.jpg");
    height: 540px;
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    margin: 0;
    position:relative;
}
/*Parallax*/

#header{
 position: absolute;
  top: 40%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
  text-align: center;
 left: 20%;
  font-size: 4vw;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 15px;
  padding-bottom: 20px;
  background-color: #357eca;
  width: 50%;
  word-wrap: break-word;
  opacity: 0.9;
  font-weight: 900;
  padding-left: 5%;
  padding-right: 5%;

}

h5
{
  color:white;
  text-align: center;
    font-family: 'Montserrat';
      text-transform: uppercase;
      font-weight: 900;

  /*-webkit-margin-before:0.67em;
  -webkit-margin-after:0.67em;
  -webkit-margin-start:0px;
  -webkit-margin-end:0px;
  -webkit-tap-highlight-colour:rgba(0,0,0,0);
  -webkit-font-smoothing:antialiased;
  -webkit-box-direction:normal;
  position: absolute;*/
}
h5:after, h5:before
{
  content: '';
  width: 50px;
  height: 2px;
  background: black;
  margin: 0 10px;
}
/*--- Circular images --- */

.img-circular1,
.img-circular2,
.img-circular3 {
  width:100%;
  background-size: cover;
  border-radius: 50%;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  background: red;
  display: block;
  margin: 0 auto;
}

#container1 {
  top: 100px;
  position: relative;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: auto;
  width: 70%;
  background-color: green;
  overflow: auto;
  bottom: 0;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.wrap {
  //flex-grow: 1;
  width: 25%;
}

<div id="navigation"></div>

<div class="parallax"><h5 id="header"><b>Welcome to RyanTeaches</b></h5></div>

<!--<img src="bg.jpg" style="top:60px;height: 510px;min-width: 100%;">-->
<div id="content">
<h2 style="margin-top: 0px;">Activities</h2>
</div>

<div id="container1" style="padding-bottom: 400px;">
  <div class="wrap">
    <img class="img-circular1" src="http://via.placeholder.com/150x150"/>
  </div>
  <div class="wrap">
    <img class="img-circular2" src="http://via.placeholder.com/150x150"/>
  </div>
  <div class="wrap">
    <img class="img-circular3" src="http://via.placeholder.com/150x150"/>
  </div>
</div>

<div id="content">
<h2 style="margin-top: 0px;">Activities</h2>
</div>


答:
I figured out the solution which was adding l1 -> next = NULL; in the
  newList function and l2 -> next = NULL; in the appendList function.

But I was wondering why there was a difference in output. Is there a
  bug in the compiler or was I wrong for not initialising the pointer to
  NULL even though it works in most compilers?

You were wrong to access the pointer's value without having assigned it one or caused it to be explicitly or implicitly initialized (which are different from assigning a value).  Doing so produces undefined behavior.  That the program nevertheless happened to exhibit the behavior you expected under some circumstances is a possible and plausible result, but it does not validate the program.

Moreover, you are likely to find that your original approach does not work reliably with the other compilers you tested under more complex circumstances (but I can make only a probabilistic statement about that, because "undefined").

Title: Null pointer detection in tcc

Body:
I created a very simple linked list and noticed a difference in output for tcc filename.c vs tcc filename.c -run for my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct llist {
    struct llist *next;
    struct llist *last;
    struct llist *first;
    int value;
    int item;
    int *length;
};

struct llist *newList(int v){

    struct llist *l1 = malloc(sizeof(struct llist));
    l1 -> length = malloc(sizeof(int));
    *l1 -> length = 1;

    l1 -> value = v;
    l1 -> item = 0;
    l1 -> first = l1;

    return l1;
}

struct llist *appendList(struct llist *l1, int v){

    struct llist *l2 = malloc(sizeof(struct llist));

    l2 -> value = v;
    l2 -> last = l1;
    l2 -> first = l1 -> first;
    l2 -> length = l1 -> length;
    *l2 -> length += 1;
    l2 -> item = l1 -> item + 1;

    l1 -> next = l2;

    return l2;
};

int main(){
    struct llist *list = newList(4);
    list = appendList(list, 6);
    list = appendList(list, 8);
    list = appendList(list, 10);

    list = list -> first;

    int end = 0;
    while(end==0){

        printf("VAL: %d\n", list -> value);

        if(list -> next == NULL){
            printf("END\n");
            end = 1;
        }else{

            list = list -> next;
        }
    }

    return 0;
}

For compiling with tcc filename.c and then running it produces the output I expected:

VAL: 4
VAL: 6
VAL: 8
VAL: 10
END

It's also the output I get in GCC and clang.

When I use tcc filename.c -run I get:

VAL: 4
VAL: 6
VAL: 8
VAL: 10
VAL: 27092544
VAL: 1489483720
VAL: 0
END

With the last number always being zero and the other two extra values being different every time I run.

I figured out the solution which was adding l1 -> next = NULL; in the newList function and l2 -> next = NULL; in the appendList function.

But I was wondering why there was a difference in output. Is there a bug in the compiler or was I wrong for not initialising the pointer to NULL even though it works in most compilers?


问:
Best practices with saving datetime & timezone info in database when data is dependant on datetime
There were quite a few questions about saving datetime & timezones info in DB but more on the overall level. Here I'd like to address a specific case.

System specs

We have an Orders system database

It is a multi-tenant system where tenants can use arbitrary timezone (it is arbitrary but single timezone per tenant, saved in Tenants table once and never changes)

Business rule needed to be covered in DB

When tenant places an Order into the system, order number gets computed based on their local datetime (its not literally a number but some kind of an identifier like ORDR-13432-Year-Month-Day). Precise calculation is not important for the moment, it's just important that it's dependant on tenants local datetime

We also do want to be able to select all Orders, on the system level, placed between some UTC datetimes regardless of the tenant (for general system statistics/reporting)

Our initial idea

Our initial idea was to save UTC datetime across whole DB and, of course, keep tenants timezone offset relative to UTC and have application that consumes DB always convert datetimes to UTC so that DB itself always operate with UTC.

Approach 1

Saving local tenants datetime would be nice per tenant but then we have problem with queries like:

```<code>SELECT * FROM ORDERS WHERE OrderDateTime BETWEEN UTCDateTime1 AND UTCDateTime2
</code>```

It's problematic because OrderDateTime in this query means different moment in time, based on tenant. Of course, this query might include join to Tenants table to get local datetime offset which would then calculate OrderDateTime on the fly to make adjustments. It's possible, but not sure if it's a good way to do it?

Approach 2

On the other hand, when saving UTC datetime, then when we do calculation of OrderNumber since the day/month/year in UTC might differ from the one in local datetime

Let's take extreme example; let's say tenant is 6 hours ahead of UTC and his local datetime is 2017-01-01 02:00.
UTC would be 2016-12-31 20:00. Order placed at that moment should get OrderNumber 'ORDR-13432-2017-1-1' but if saving UTC it would get ORDR-13432-2016-12-31.

In this case, at the moment of creating Order in DB, we should get UTC datetime, tenants offset and compile OrderNumber based on recalculated tenants localtime but still save DateTime column in UTC.

Questions

What is the preferred way of handling this kind of situation?

Is there a nice solution with saving UTC datetimes because that one would be pretty nice for us because of the system-level reporting?

If going with saving UTC, is Approach 2) good way to handle those cases or is there some better/recommended way?

[UPDATE]

Based on comments from Gerard Ashton and Hugo:

Initial question was not clear with respect to the detail if tenant can change timezone or not and what happens if political authority changes the timezone properties or some terirory's timezone.
Of course that is of an extreme importance, but it is not in the center of this question . We might address that in a separate question.

For the sake of this question, lets assume tenant will not change location. Timezone properties or timezone itself for that location might change and those changes will be handled in the system separately from this question.

答:
Hugo's answer is mostly correct, but I'll add a few key points:

When you're storing the customer's time zone, do NOT store a numerical offset.  As others have pointed out, the offset from UTC is only for a single point in time, and can easily change for DST and for other reasons.  Instead, you should store a time zone identifier, preferably an IANA time zone identifier as a string, such as "America/Los_Angeles".  Read more in the timezone tag wiki.

Your OrderDateTime field should absolutely represent the time in UTC.  However, depending on your database platform, you have several choices for how to store this.

For example, if using Microsoft SQL Server, a good approach is to store the local time in a datetimeoffset column, which preserves the offset from UTC.  Note that any index you create on that column will be based on the UTC equivalent, so you will get good query performance when doing your range query.

If using other database platforms, you may instead wish to store the UTC value in a timestamp field.  Some databases also have timestamp with time zone, but understand that it doesn't mean it stores the time zone or offset, it just means that it can do conversions for you implicitly as you store and retrieve values.  If you intend to always represent UTC, then often timestamp (without time zone) or just datetime is more appropriate.

Since either of the above methods will store a UTC time, you'll also need to consider how to perform operations that need an index of local time values.  For example, you might need to create a daily report, based on the day of the user's time zone.  For that, you'd need to group by the local date.  If you try to compute that at query time from your UTC value, you'll end up scanning the entire table.

A good approach to deal with this is to create a separate column for the local date (or perhaps even the local datetime depending on your needs, but not a datetimeoffset or timestamp).  This could be a completely isolated column that you populate separately, or it could be a computed/calculated column based on your other column.  Use this column in an index so you can filter or group by local date.

If you go for the computed-column approach, you'll need to know how to convert between time zones in the database.  Some databases have a convert_tz function built-in that understands IANA time zone identifiers.

If you're using Microsoft SQL Server, you can use the new AT TIME ZONE function in SQL 2016 and Azure SQL DB, but that only works with Microsoft time zone identifiers.  To use IANA time zone identifiers, you'll need a third party solution, such as my SQL Server Time Zone Support project.

At query time, avoid using the BETWEEN statement.  It is fully inclusive.  It works ok for whole dates, but when you have time involved you're better off doing a half-open range query, such as:

```<code>... WHERE OrderDateTime >= @t1 AND OrderDateTime < @t2
</code>```

For example, if @t1 were the start of today, @t2 would be the start of tomorrow.

Regarding the scenario discussed in comments where the user's time zone has changed:

If you choose to calculate the local date in the database, the only scenario you need to worry about is if a location or business switches time zones without a "zone split" occurring.  A zone split is when a new time zone identifier is introduced which covers the area that changed, including their old and new rules.

For example, the latest zone added to the IANA tzdb at the time of writing this is America/Punta_Arenas, which was a zone split when the southern part of Chile decided to stay at UTC-3 when the rest of Chile (America/Santiago) went back to UTC-4 at the end of DST.

However, if a minor locality on the border of two time zones decides to change which side they follow, and a zone split wasn't warranted, then you'd potentially be using the rules of their new time zone against their old data.

If you store the local date separately (computed in the application, not the DB), then you'll have no problems.  The user changes their time zone to the new one, all old data is still intact, and new data is stored with the new time zone.

Body:
There were quite a few questions about saving datetime & timezones info in DB but more on the overall level. Here I'd like to address a specific case.

System specs

We have an Orders system database

It is a multi-tenant system where tenants can use arbitrary timezone (it is arbitrary but single timezone per tenant, saved in Tenants table once and never changes)

Business rule needed to be covered in DB

When tenant places an Order into the system, order number gets computed based on their local datetime (its not literally a number but some kind of an identifier like ORDR-13432-Year-Month-Day). Precise calculation is not important for the moment, it's just important that it's dependant on tenants local datetime

We also do want to be able to select all Orders, on the system level, placed between some UTC datetimes regardless of the tenant (for general system statistics/reporting)

Our initial idea

Our initial idea was to save UTC datetime across whole DB and, of course, keep tenants timezone offset relative to UTC and have application that consumes DB always convert datetimes to UTC so that DB itself always operate with UTC.

Approach 1

Saving local tenants datetime would be nice per tenant but then we have problem with queries like:

SELECT * FROM ORDERS WHERE OrderDateTime BETWEEN UTCDateTime1 AND UTCDateTime2

It's problematic because OrderDateTime in this query means different moment in time, based on tenant. Of course, this query might include join to Tenants table to get local datetime offset which would then calculate OrderDateTime on the fly to make adjustments. It's possible, but not sure if it's a good way to do it?

Approach 2

On the other hand, when saving UTC datetime, then when we do calculation of OrderNumber since the day/month/year in UTC might differ from the one in local datetime

Let's take extreme example; let's say tenant is 6 hours ahead of UTC and his local datetime is 2017-01-01 02:00.
UTC would be 2016-12-31 20:00. Order placed at that moment should get OrderNumber 'ORDR-13432-2017-1-1' but if saving UTC it would get ORDR-13432-2016-12-31.

In this case, at the moment of creating Order in DB, we should get UTC datetime, tenants offset and compile OrderNumber based on recalculated tenants localtime but still save DateTime column in UTC.

Questions

What is the preferred way of handling this kind of situation?

Is there a nice solution with saving UTC datetimes because that one would be pretty nice for us because of the system-level reporting?

If going with saving UTC, is Approach 2) good way to handle those cases or is there some better/recommended way?

[UPDATE]

Based on comments from Gerard Ashton and Hugo:

Initial question was not clear with respect to the detail if tenant can change timezone or not and what happens if political authority changes the timezone properties or some terirory's timezone.
Of course that is of an extreme importance, but it is not in the center of this question . We might address that in a separate question.

For the sake of this question, lets assume tenant will not change location. Timezone properties or timezone itself for that location might change and those changes will be handled in the system separately from this question.

Body:
Hugo's answer is mostly correct, but I'll add a few key points:

When you're storing the customer's time zone, do NOT store a numerical offset.  As others have pointed out, the offset from UTC is only for a single point in time, and can easily change for DST and for other reasons.  Instead, you should store a time zone identifier, preferably an IANA time zone identifier as a string, such as "America/Los_Angeles".  Read more in the timezone tag wiki.

Your OrderDateTime field should absolutely represent the time in UTC.  However, depending on your database platform, you have several choices for how to store this.

For example, if using Microsoft SQL Server, a good approach is to store the local time in a datetimeoffset column, which preserves the offset from UTC.  Note that any index you create on that column will be based on the UTC equivalent, so you will get good query performance when doing your range query.

If using other database platforms, you may instead wish to store the UTC value in a timestamp field.  Some databases also have timestamp with time zone, but understand that it doesn't mean it stores the time zone or offset, it just means that it can do conversions for you implicitly as you store and retrieve values.  If you intend to always represent UTC, then often timestamp (without time zone) or just datetime is more appropriate.

Since either of the above methods will store a UTC time, you'll also need to consider how to perform operations that need an index of local time values.  For example, you might need to create a daily report, based on the day of the user's time zone.  For that, you'd need to group by the local date.  If you try to compute that at query time from your UTC value, you'll end up scanning the entire table.

A good approach to deal with this is to create a separate column for the local date (or perhaps even the local datetime depending on your needs, but not a datetimeoffset or timestamp).  This could be a completely isolated column that you populate separately, or it could be a computed/calculated column based on your other column.  Use this column in an index so you can filter or group by local date.

If you go for the computed-column approach, you'll need to know how to convert between time zones in the database.  Some databases have a convert_tz function built-in that understands IANA time zone identifiers.

If you're using Microsoft SQL Server, you can use the new AT TIME ZONE function in SQL 2016 and Azure SQL DB, but that only works with Microsoft time zone identifiers.  To use IANA time zone identifiers, you'll need a third party solution, such as my SQL Server Time Zone Support project.

At query time, avoid using the BETWEEN statement.  It is fully inclusive.  It works ok for whole dates, but when you have time involved you're better off doing a half-open range query, such as:

... WHERE OrderDateTime >= @t1 AND OrderDateTime < @t2

For example, if @t1 were the start of today, @t2 would be the start of tomorrow.

Regarding the scenario discussed in comments where the user's time zone has changed:

If you choose to calculate the local date in the database, the only scenario you need to worry about is if a location or business switches time zones without a "zone split" occurring.  A zone split is when a new time zone identifier is introduced which covers the area that changed, including their old and new rules.

For example, the latest zone added to the IANA tzdb at the time of writing this is America/Punta_Arenas, which was a zone split when the southern part of Chile decided to stay at UTC-3 when the rest of Chile (America/Santiago) went back to UTC-4 at the end of DST.

However, if a minor locality on the border of two time zones decides to change which side they follow, and a zone split wasn't warranted, then you'd potentially be using the rules of their new time zone against their old data.

If you store the local date separately (computed in the application, not the DB), then you'll have no problems.  The user changes their time zone to the new one, all old data is still intact, and new data is stored with the new time zone.