问:
React - Empty Array When Rendering JSON Data
Why is an empty array created when rendering this JSON array? See attached screenshot  I assume the constructor is just initiating it with a null value and filling it at a later point.

New to Javascript + React and just want to make sure I am understanding what is happening.  I will also accept critique on the garbage code that is below. Codepen link

```<code>class Jobs extends React.Component {
  render() {
    const jobs = this.props.jobs;
    console.log(jobs);
    const formattedJobs = jobs.map((job) =>
      <ul key={job.id}>
        <div class="company">{job.company_name}</div>
        <div class="title">{job.title}</div>
      </ul>
    );
    return(
      <div>{formattedJobs}</div>
    );
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state={
      jobs:[]
    }
  var myUrl = "https://codepen.io/jobs.json";
  fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
  }

  render() {
    return (
    <div className="app">
      <div className="header">
        <h1 id="header-title">Job Postings</h1>
      </div>
      <div className="content">
        <Jobs jobs={this.state.jobs}/>
      </div>
    </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

答:
Jobs component

always be nice for default props - component can / will render before fetch returns response

replace class with className as first one is restricted word in JSX

ul can only contains li childs - not div

nice for use key property when you iterate over collection

App component

there is place for suppor unexpected response, you can set new state like error and support it

please consider with component is responsible to support errors and spinners- App or Jobs

Ract application

```<code>class Jobs extends React.Component {
  render() {
    const { jobs } = this.props;
    const formattedJobs = jobs.map(job =>
      <ul key={job.id}>
        <li className="company">{job.company_name}</li>
        <li className="title">{job.title}</li>
      </ul>
    );

    return <div>{formattedJobs}</div>;
  }
}

Jobs.defaultProps = {
  jobs: []
};

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      jobs: []
    };
  }

  componentDidMount() {
    fetch("https://codepen.io/jobs.json")
      .then(response => response.json())
      .then(response => {
        if (!Array.isArray(response.jobs)) {
          throw new Error(
            `Expected response but got ${JSON.stringify(response.jobs)}`
          );
        } else {
          return response.jobs;
        }
      })
      .then(jobs => this.setState({ jobs }));
  }

  render() {
    return (
      <div className="app">
        <div className="header">
          <h1 id="header-title">Job Postings</h1>
        </div>
        <div className="content">
          <Jobs jobs={this.state.jobs} />
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
</code>```

Body:
Why is an empty array created when rendering this JSON array? See attached screenshot  I assume the constructor is just initiating it with a null value and filling it at a later point.

New to Javascript + React and just want to make sure I am understanding what is happening.  I will also accept critique on the garbage code that is below. Codepen link

class Jobs extends React.Component {
  render() {
    const jobs = this.props.jobs;
    console.log(jobs);
    const formattedJobs = jobs.map((job) =>

{job.company_name}

{job.title}

    );
    return(

{formattedJobs}

    );
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state={
      jobs:[]
    }
  var myUrl = "https://codepen.io/jobs.json";
  fetch(myUrl)
    .then((response) => response.json())
    .then((json) => this.setState({jobs: json.jobs}));
  }

  render() {
    return (

Job Postings

        <Jobs jobs={this.state.jobs}/>

    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Body:
Jobs component

always be nice for default props - component can / will render before fetch returns response

replace class with className as first one is restricted word in JSX

ul can only contains li childs - not div

nice for use key property when you iterate over collection

App component

there is place for suppor unexpected response, you can set new state like error and support it

please consider with component is responsible to support errors and spinners- App or Jobs

Ract application

class Jobs extends React.Component {
  render() {
    const { jobs } = this.props;
    const formattedJobs = jobs.map(job =>
      <ul key={job.id}>
        <li className="company">{job.company_name}</li>
        <li className="title">{job.title}</li>
      </ul>
    );

    return <div>{formattedJobs}</div>;
  }
}

Jobs.defaultProps = {
  jobs: []
};

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      jobs: []
    };
  }

  componentDidMount() {
    fetch("https://codepen.io/jobs.json")
      .then(response => response.json())
      .then(response => {
        if (!Array.isArray(response.jobs)) {
          throw new Error(
            `Expected response but got ${JSON.stringify(response.jobs)}`
          );
        } else {
          return response.jobs;
        }
      })
      .then(jobs => this.setState({ jobs }));
  }

  render() {
    return (
      <div className="app">
        <div className="header">
          <h1 id="header-title">Job Postings</h1>
        </div>
        <div className="content">
          <Jobs jobs={this.state.jobs} />
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));


来源: stackexchange

问:
How to parse date string to Date?
How do I parse the date string below into a Date object?

```<code>String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result =  df.parse(target);
</code>```

Throws exception...

```<code>java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
        at java.text.DateFormat.parse(DateFormat.java:337)
</code>```

答:
Here is a working example:

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class j4496359 {
    public static void main(String[] args) {
        try {
            String target = "Thu Sep 28 20:29:30 JST 2000";
            DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
            Date result =  df.parse(target);
            System.out.println(result);
        } catch (ParseException pe) {
            pe.printStackTrace();
        }
    }
}
</code>```

Will print:

```<code>Thu Sep 28 13:29:30 CEST 2000
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to parse date string to Date?

Body:
How do I parse the date string below into a Date object?

String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result =  df.parse(target);

Throws exception...

java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
        at java.text.DateFormat.parse(DateFormat.java:337)

Body:
Here is a working example:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;

public class j4496359 {
    public static void main(String[] args) {
        try {
            String target = "Thu Sep 28 20:29:30 JST 2000";
            DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
            Date result =  df.parse(target);
            System.out.println(result);
        } catch (ParseException pe) {
            pe.printStackTrace();
        }
    }
}

Will print:

Thu Sep 28 13:29:30 CEST 2000

ContentLicense: CC BY-SA 2.5


问:
Get variable outsite foreach
I want to create a slideshow to work with Seblod, but I don't know how to get the thumbs outsite foreach:

```<code>    <ul class="bxslider">
<?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

  <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>

 <?php } ?>
 </ul>
<div id="bx-pager">
  <a data-slide-index="1" href=""><img src="/<?php echo $fx->thumb1; ?>" /></a>
</div>
</code>```

Because $fx->thumb1 is outsite foreach - I can't get the links of thumbs :(

答:
You can use variable.But when you are looping the variable will keep the last value.

```<code><?php
$thumb1 = '';
?>
<ul class="bxslider">
<?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

  <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>

  <?php
    $thumb1 = $fx->thumb1;
  }
?>
</ul>
<div id="bx-pager">
  <a data-slide-index="1" href=""><img src="/<?php echo $thumb1; ?>" /></a>
</div>
</code>```

if you want all the values:

```<code><ul class="bxslider">
    <?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

      <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>

      <?php
      $thumb1.='<a data-slide-index="1" href=""><img src="/<?php echo $thumb1; ?>" /></a>';
      }
    ?>
 </ul>
    <div id="bx-pager">
      <?php
       echo $thumb1;
       ?>
    </div>
</code>```

Title: Get variable outsite foreach

Body:
I want to create a slideshow to work with Seblod, but I don't know how to get the thumbs outsite foreach:

<?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

 <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" />

 <?php } ?>

  <img src="/<?php echo $fx->thumb1; ?>" />

Because $fx->thumb1 is outsite foreach - I can't get the links of thumbs :(

Body:
You can use variable.But when you are looping the variable will keep the last value.

<?php
$thumb1 = '';
?>
<ul class="bxslider">
<?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

  <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>

  <?php
    $thumb1 = $fx->thumb1;
  }
?>
</ul>
<div id="bx-pager">
  <a data-slide-index="1" href=""><img src="/<?php echo $thumb1; ?>" /></a>
</div>

if you want all the values:

<ul class="bxslider">
    <?php foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

      <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>

      <?php
      $thumb1.='<a data-slide-index="1" href=""><img src="/<?php echo $thumb1; ?>" /></a>';
      }
    ?>
 </ul>
    <div id="bx-pager">
      <?php
       echo $thumb1;
       ?>
    </div>


答:
Try this</p>

```<code>$html = '';
<ul class="bxslider">

<?php
  $i = 0;
 foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

  <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>

  $html.=" <a data-slide-index='{$i}' href=''><img src='/{$fx->thumb1}' /></a>";

 <?php $i++; } ?>
 </ul>
<div id="bx-pager">
  <?php echo $html; ?>
</div>
</code>```

Title: Get variable outsite foreach

Body:
Try this

$html = '';
<ul class="bxslider">

<?php
  $i = 0;
 foreach($cck->get( 'galerie_photo' )->value as $fx){ ?>

  <li> <img src="/<?php echo $fx->value; ?>" title ="<?php echo $fx->image_title; ?>" /></li>

  $html.=" <a data-slide-index='{$i}' href=''><img src='/{$fx->thumb1}' /></a>";

 <?php $i++; } ?>
 </ul>
<div id="bx-pager">
  <?php echo $html; ?>
</div>


问:
Using a media/gif as a texture in rotating cube with vispy
I am using Vispy to rotate a cube. I can use imageio to use a custom texture in the face of the rotating cube successfully, but I don't understand how to use a movie or gif image.

Full source code:

```<code>import numpy as np

from vispy import gloo, app
from vispy.gloo import Program, VertexBuffer, IndexBuffer
from vispy.util.transforms import perspective, translate, rotate
from vispy.geometry import create_cube
import imageio

im = imageio.imread('C:\\vhosts\\VIDEO_TWO_CLONE\\shape.jpg')

vertex = """
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
uniform sampler2D texture;

attribute vec3 position;
attribute vec2 texcoord;
attribute vec3 normal;
attribute vec4 color;

varying vec2 v_texcoord;
void main()
{
    gl_Position = projection * view * model * vec4(position,1.0);
    v_texcoord = texcoord;
}
"""

fragment = """
uniform sampler2D texture;
varying vec2 v_texcoord;
void main()
{
    gl_FragColor = texture2D(texture, v_texcoord);
}
"""

def checkerboard(grid_num=8, grid_size=32):
    row_even = grid_num // 2 * [0, 1]
    row_odd = grid_num // 2 * [1, 0]
    Z = np.row_stack(grid_num // 2 * (row_even, row_odd)).astype(np.uint8)
    return 255 * Z.repeat(grid_size, axis=0).repeat(grid_size, axis=1)

class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, size=(750, 750), title='Textured cube',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = translate((0, 0, -5))
        model = np.eye(4, dtype=np.float32)
        self.program['model'] = model
        self.program['view'] = view
        self.program['texture'] = im # checkerboard()

        self.activate_zoom()

        self.phi, self.theta = 0, 0

        # OpenGL initalization
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)
        self.timer.start()

        self.show()

    def on_draw(self, event):
        gloo.clear(color=True, depth=True)
        self.program.draw('triangles', self.indices)

    def on_resize(self, event):
        self.activate_zoom()

    def activate_zoom(self):
        gloo.set_viewport(0, 0, *self.physical_size)
        projection = perspective(45.0, self.size[0] / float(self.size[1]),
                                 2.0, 10.0)
        self.program['projection'] = projection

    def on_timer(self, event):
        self.theta += .5
        self.phi += .5
        self.program['model'] = np.dot(rotate(self.theta, (0, 1, 0)),
                                       rotate(self.phi, (0, 1, 0)))
        self.update()

if __name__ == '__main__':
    c = Canvas()
    app.run()
</code>```

答:
A gif or a movie is essentially many image frames, coming one after the other.

What you would need to do is read the images from the GIF into an array containing the RGB(A) values of each image (for GIF, you can use the code from e.g. https://gist.github.com/BigglesZX/4016539), and then advance self.program['texture'] to the next frame of the GIF in on_timer.

In case you want to loop the texture, you could use the modulo operator %, so you don't run over the array boundaries, with something like

```<code># gif_array is the array populated with GIF frames
self.program['texture'] = gif_array[index % (len(gif_array) - 1)]
index = index + 1
</code>```

Body:
I am using Vispy to rotate a cube. I can use imageio to use a custom texture in the face of the rotating cube successfully, but I don't understand how to use a movie or gif image.

Full source code:

import numpy as np

from vispy import gloo, app
from vispy.gloo import Program, VertexBuffer, IndexBuffer
from vispy.util.transforms import perspective, translate, rotate
from vispy.geometry import create_cube
import imageio

im = imageio.imread('C:\\vhosts\\VIDEO_TWO_CLONE\\shape.jpg')

vertex = """
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
uniform sampler2D texture;

attribute vec3 position;
attribute vec2 texcoord;
attribute vec3 normal;
attribute vec4 color;

varying vec2 v_texcoord;
void main()
{
    gl_Position = projection * view * model * vec4(position,1.0);
    v_texcoord = texcoord;
}
"""

fragment = """
uniform sampler2D texture;
varying vec2 v_texcoord;
void main()
{
    gl_FragColor = texture2D(texture, v_texcoord);
}
"""

def checkerboard(grid_num=8, grid_size=32):
    row_even = grid_num // 2 * [0, 1]
    row_odd = grid_num // 2 * [1, 0]
    Z = np.row_stack(grid_num // 2 * (row_even, row_odd)).astype(np.uint8)
    return 255 * Z.repeat(grid_size, axis=0).repeat(grid_size, axis=1)

class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, size=(750, 750), title='Textured cube',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = translate((0, 0, -5))
        model = np.eye(4, dtype=np.float32)
        self.program['model'] = model
        self.program['view'] = view
        self.program['texture'] = im # checkerboard()

        self.activate_zoom()

        self.phi, self.theta = 0, 0

        # OpenGL initalization
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)
        self.timer.start()

        self.show()

    def on_draw(self, event):
        gloo.clear(color=True, depth=True)
        self.program.draw('triangles', self.indices)

    def on_resize(self, event):
        self.activate_zoom()

    def activate_zoom(self):
        gloo.set_viewport(0, 0, *self.physical_size)
        projection = perspective(45.0, self.size[0] / float(self.size[1]),
                                 2.0, 10.0)
        self.program['projection'] = projection

    def on_timer(self, event):
        self.theta += .5
        self.phi += .5
        self.program['model'] = np.dot(rotate(self.theta, (0, 1, 0)),
                                       rotate(self.phi, (0, 1, 0)))
        self.update()

if __name__ == '__main__':
    c = Canvas()
    app.run()

Body:
A gif or a movie is essentially many image frames, coming one after the other.

What you would need to do is read the images from the GIF into an array containing the RGB(A) values of each image (for GIF, you can use the code from e.g. https://gist.github.com/BigglesZX/4016539), and then advance self.program['texture'] to the next frame of the GIF in on_timer.

In case you want to loop the texture, you could use the modulo operator %, so you don't run over the array boundaries, with something like

# gif_array is the array populated with GIF frames
self.program['texture'] = gif_array[index % (len(gif_array) - 1)]
index = index + 1


问:
Organize php project files
I'm new to the web development, recently I create a web application with Php/Mysql, and now I want to put it on to the server but I feel that my files organization is bad (very bad).

my project files structure looks something like that

```
|--XAMPP htdocs
    |--MyProject
        |--config.php
        |--functions.php
        |--header.php
        |--nav.php
        |--index.php
        |--js
        |--css
        |--images
        |--register
            |--index.php
        |--messages
            |--inbox
                |--index.php
                |--handle_inbox.php
            |--outbox
                |--index.php
                |--handle_outbox.php
            |--trash
                |--index.php
                |--handle_trash.php
            |--uploaded_files
        |-- ...
```

what I can do to improve this structure and make it secure ?!

答:
Paul M. Jones has done some fantastic research into common practice of tens of thousands of github projects in the realm of PHP. He has compiled a standard filesystem structure based on this research. Take a look at the Standard PHP Package Skeleton and base your project off of it.

You do not need all of the file structure that he recommends, but it's a great place to start. If you are planning to open-source your project, this file structure will make the most sense to your potential contributors and users.

Title: Organize php project files

Body:
I'm new to the web development, recently I create a web application with Php/Mysql, and now I want to put it on to the server but I feel that my files organization is bad (very bad).

my project files structure looks something like that

|--XAMPP htdocs
    |--MyProject
        |--config.php
        |--functions.php
        |--header.php
        |--nav.php
        |--index.php
        |--js
        |--css
        |--images
        |--register
            |--index.php
        |--messages
            |--inbox
                |--index.php
                |--handle_inbox.php
            |--outbox
                |--index.php
                |--handle_outbox.php
            |--trash
                |--index.php
                |--handle_trash.php
            |--uploaded_files
        |-- ...

what I can do to improve this structure and make it secure ?!


问:
How to Forward a DNS subdomain in my DNS server to be fulfilled by Azure DNS
I have a set of DNS servers in my company that host many web sites. we are experimenting with hosting some of them in Azure. I would like to create a sub domain like  xxx.myazure.mycompany.com where the DNS servers can forward the sub domain myazure zones to azure DNS, to be specific I would like to have my servers resolve all mycompany.com requests and have azure dns resolve all myazue.mycompany.com queries. Is this possible?</p>

答:
The following article describes how to delegate a sub-domain. In this example both zones are hosted by Azure DNS, but you should be able to use the corresponding workflow with the provider hosting your parent zone to achieve what you are looking for.

https://learn.microsoft.com/en-us/azure/dns/dns-delegate-domain-azure-dns#delegate-sub-domains-in-azure-dns


问:
Expensive renderInContext memory usage on main thread
I am using the follow code that is executed on the main thread to take a screenshot of an off screen (not a subview of self.view) view that then is displayed in an UIImageView. Everything works fine in terms of functionality, however because this code is being run on an extension, there are much stricter memory bounds (I've read ~30 MB is the cap?),

```<code>UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.screenshotView.frame.size.width, self.screenshotView.frame.size.height-2), YES, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.screenshotView.layer renderInContext:context];
_generatedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.previewImageView.image = _generatedImage;
</code>```

The method this code resides in gets called using performSelectorOnMainThread whenever a UIButton is pressed. A UIAlertController is also presented to handle the freezing of the UI, but if the button is pressed continuously (after dismissal of the UIAlertController), the first few times the memory usage will stay around the baseline (~15 MB), but then spike to ~30 MB and stay there until the method is called again a few seconds later and then when it is done rendering, it falls back to ~15 MB.

I'm unsure what is causing this behavior, why the memory usage doesn't stick around ~15 MB all the time, and I'm unsure as to what is the reason it spikes like that when the method is called continuously. It sounds like more that one thing is happening at once sometimes? How can I make sure this doesn't happen and only dismiss the UIAlertController when it is safe to render again without spiking memory usage.

答:
1.Could you elaborate more on why are you trying to capture screenshot on main thread? Run it async with:

```<code>dispatch_async(dispatch_get_global_queue(0, 0), ^{
});
</code>```

This might resolve the hang issue & try to execute these line of codes inside autoreleasepool which will help in reducing memory foot print.

2.Have you tried drawViewHierarchyInRect: afterScreenUpdates: It's much faster & could be more efficient and help with your memory issue.

That method renders to the context and then you can just call:

```<code>CGImageRef image = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());
</code>```

but it should be executed inside an autoreleasepool. If not then memory keeps on rising.

EDIT

3.If you can prevent multiple context creation with synchronizing capture method.It might help in spiking memory:

```<code>dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_queue_t renderQueue = dispatch_queue_create("com.throttling.queue", NULL);

- (void) captureScreen {
    if (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW) == 0) {
        dispatch_async(renderQueue, ^{
            // capture
            dispatch_semaphore_signal(semaphore);
        });
    }
}
</code>```

Body:
I am using the follow code that is executed on the main thread to take a screenshot of an off screen (not a subview of self.view) view that then is displayed in an UIImageView. Everything works fine in terms of functionality, however because this code is being run on an extension, there are much stricter memory bounds (I've read ~30 MB is the cap?),

UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.screenshotView.frame.size.width, self.screenshotView.frame.size.height-2), YES, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.screenshotView.layer renderInContext:context];
_generatedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.previewImageView.image = _generatedImage;

The method this code resides in gets called using performSelectorOnMainThread whenever a UIButton is pressed. A UIAlertController is also presented to handle the freezing of the UI, but if the button is pressed continuously (after dismissal of the UIAlertController), the first few times the memory usage will stay around the baseline (~15 MB), but then spike to ~30 MB and stay there until the method is called again a few seconds later and then when it is done rendering, it falls back to ~15 MB.

I'm unsure what is causing this behavior, why the memory usage doesn't stick around ~15 MB all the time, and I'm unsure as to what is the reason it spikes like that when the method is called continuously. It sounds like more that one thing is happening at once sometimes? How can I make sure this doesn't happen and only dismiss the UIAlertController when it is safe to render again without spiking memory usage.

Body:
1.Could you elaborate more on why are you trying to capture screenshot on main thread? Run it async with:

dispatch_async(dispatch_get_global_queue(0, 0), ^{
});

This might resolve the hang issue & try to execute these line of codes inside autoreleasepool which will help in reducing memory foot print.

2.Have you tried drawViewHierarchyInRect: afterScreenUpdates: It's much faster & could be more efficient and help with your memory issue.

That method renders to the context and then you can just call:

CGImageRef image = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());

but it should be executed inside an autoreleasepool. If not then memory keeps on rising.

EDIT

3.If you can prevent multiple context creation with synchronizing capture method.It might help in spiking memory:

dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_queue_t renderQueue = dispatch_queue_create("com.throttling.queue", NULL);

- (void) captureScreen {
    if (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW) == 0) {
        dispatch_async(renderQueue, ^{
            // capture
            dispatch_semaphore_signal(semaphore);
        });
    }
}


问:
Text analysis-Unable to write output of Python program in csv or xls file
Hi I am trying to do a sentiment analysis using Naive Bayes classifier in python 2.x. It reads the sentiment using a txt file and then gives output as positive or negative based on the sample txt file sentiments.
I want the output the same form as input e.g. I have a text file of lets sat 1000 raw  sentiments and I want the output to show positive or negative against each sentiment.
Please help.
Below is the code i am using</p>

```<code>import math
import string

def Naive_Bayes_Classifier(positive, negative, total_negative, total_positive, test_string):
    y_values = [0,1]
    prob_values = [None, None]

    for y_value in y_values:
        posterior_prob = 1.0

        for word in test_string.split():
            word = word.lower().translate(None,string.punctuation).strip()
            if y_value == 0:
                if word not in negative:
                    posterior_prob *= 0.0
                else:
                    posterior_prob *= negative[word]
            else:
                if word not in positive:
                    posterior_prob *= 0.0
                else:
                    posterior_prob *= positive[word]

        if y_value == 0:
            prob_values[y_value] = posterior_prob * float(total_negative) / (total_negative + total_positive)
        else:
            prob_values[y_value] = posterior_prob * float(total_positive) / (total_negative + total_positive)

    total_prob_values = 0
    for i in prob_values:
        total_prob_values += i

    for i in range(0,len(prob_values)):
        prob_values[i] = float(prob_values[i]) / total_prob_values

    print prob_values

    if prob_values[0] > prob_values[1]:
        return 0
    else:
        return 1

if __name__ == '__main__':
    sentiment = open(r'C:/Users/documents/sample.txt')

    #Preprocessing of training set
    vocabulary = {}
    positive = {}
    negative = {}
    training_set = []
    TOTAL_WORDS = 0
    total_negative = 0
    total_positive = 0

    for line in sentiment:
        words = line.split()
        y = words[-1].strip()
        y = int(y)

        if y == 0:
            total_negative += 1
        else:
            total_positive += 1

        for word in words:
            word = word.lower().translate(None,string.punctuation).strip()
            if word not in vocabulary and word.isdigit() is False:
                vocabulary[word] = 1
                TOTAL_WORDS += 1
            elif word in vocabulary:
                vocabulary[word] += 1
                TOTAL_WORDS += 1

            #Training
            if y == 0:
                if word not in negative:
                    negative[word] = 1
                else:
                    negative[word] += 1
            else:
                if word not in positive:
                    positive[word] = 1
                else:
                    positive[word] += 1

    for word in vocabulary.keys():
        vocabulary[word] = float(vocabulary[word])/TOTAL_WORDS

    for word in positive.keys():
        positive[word] = float(positive[word])/total_positive

    for word in negative.keys():
        negative[word] = float(negative[word])/total_negative

    test_string = raw_input("Enter the review: \n")

    classifier = Naive_Bayes_Classifier(positive, negative, total_negative, total_positive, test_string)
    if classifier == 0:
        print "Negative review"
    else:
        print "Positive review"
</code>```

答:
```<code>> with open("test11.txt") as f:
>     for line in f:
>         classifier = Naive_Bayes_Classifier(positive, negative, total_negative, total_positive, line) if classifier == 0:
>       f.write(line + 'Negative') else:
>        f.write(line + 'Positive')
>
> #        result = 'Positive' if classifier == 0 else 'Negative'
> #        data_to_be_written += ([line, result],)
>
> # Create a workbook and add a worksheet. workbook = xlsxwriter.Workbook('test.xls') worksheet = workbook.add_worksheet()
>
> # Start from the first cell. Rows and columns are zero indexed. row = 0 col = 0
>
> # Iterate over the data and write it out row by row. for item, cost in f:    worksheet.write(row, col,     item) worksheet.write(row, col +
> 1, cost) row += 1
>
> workbook.close()
</code>```

Body:
Hi I am trying to do a sentiment analysis using Naive Bayes classifier in python 2.x. It reads the sentiment using a txt file and then gives output as positive or negative based on the sample txt file sentiments.
I want the output the same form as input e.g. I have a text file of lets sat 1000 raw  sentiments and I want the output to show positive or negative against each sentiment.
Please help.
Below is the code i am using

import math
import string

def Naive_Bayes_Classifier(positive, negative, total_negative, total_positive, test_string):
    y_values = [0,1]
    prob_values = [None, None]

    for y_value in y_values:
        posterior_prob = 1.0

        for word in test_string.split():
            word = word.lower().translate(None,string.punctuation).strip()
            if y_value == 0:
                if word not in negative:
                    posterior_prob *= 0.0
                else:
                    posterior_prob *= negative[word]
            else:
                if word not in positive:
                    posterior_prob *= 0.0
                else:
                    posterior_prob *= positive[word]

        if y_value == 0:
            prob_values[y_value] = posterior_prob * float(total_negative) / (total_negative + total_positive)
        else:
            prob_values[y_value] = posterior_prob * float(total_positive) / (total_negative + total_positive)

    total_prob_values = 0
    for i in prob_values:
        total_prob_values += i

    for i in range(0,len(prob_values)):
        prob_values[i] = float(prob_values[i]) / total_prob_values

    print prob_values

    if prob_values[0] > prob_values[1]:
        return 0
    else:
        return 1

if __name__ == '__main__':
    sentiment = open(r'C:/Users/documents/sample.txt')

    #Preprocessing of training set
    vocabulary = {}
    positive = {}
    negative = {}
    training_set = []
    TOTAL_WORDS = 0
    total_negative = 0
    total_positive = 0

    for line in sentiment:
        words = line.split()
        y = words[-1].strip()
        y = int(y)

        if y == 0:
            total_negative += 1
        else:
            total_positive += 1

        for word in words:
            word = word.lower().translate(None,string.punctuation).strip()
            if word not in vocabulary and word.isdigit() is False:
                vocabulary[word] = 1
                TOTAL_WORDS += 1
            elif word in vocabulary:
                vocabulary[word] += 1
                TOTAL_WORDS += 1

            #Training
            if y == 0:
                if word not in negative:
                    negative[word] = 1
                else:
                    negative[word] += 1
            else:
                if word not in positive:
                    positive[word] = 1
                else:
                    positive[word] += 1

    for word in vocabulary.keys():
        vocabulary[word] = float(vocabulary[word])/TOTAL_WORDS

    for word in positive.keys():
        positive[word] = float(positive[word])/total_positive

    for word in negative.keys():
        negative[word] = float(negative[word])/total_negative

    test_string = raw_input("Enter the review: \n")

    classifier = Naive_Bayes_Classifier(positive, negative, total_negative, total_positive, test_string)
    if classifier == 0:
        print "Negative review"
    else:
        print "Positive review"


问:
when I use resourcePrefix attribute in gradle config, how to exclude dependencies lib at lint check?
When I configure the resourcePrefix property in a module build.gradle, lint checks the dependency library when I build it.
enter image description here

I want to retain this property, but I want lint not to check the libraries that depend on them. What should I do?

答:
If you are using Android studio, the lint option can be customized via the menu option Analyze -> Inspect code -> custom scope

Reference : https://developer.android.com/studio/write/lint.html#studio_config (see "Set the inspection scope and profile")


问:
jsonix - How to create an element with prefix and without namespace?
I'm required to send an XML with the following elements:

```<code><return>
    <getrooms>true</getrooms>
    <filters xmlns:a="http://some.com/xsd/atomicCondition" xmlns:c="http://some.com/xsd/complexCondition">
        <city></city>
        <country></country>
        <c:condition>
            <a:condition>
                <fieldname>fieldName</fieldname>
                <fieldtest>fieldTest</fieldtest>
                <fieldvalues>
                    <fieldvalue>fieldValue</fieldvalue>
                </fieldvalues>
            </a:condition>
            <operator>operator</operator>
            <a:condition>
                <fieldname>fieldName</fieldname>
                <fieldtest>fieldTest</fieldtest>
                <fieldvalues>
                    <fieldvalue>fieldValue</fieldvalue>
                 </fieldvalues>
            </a:condition>
         </c:condition>
    </filters>
    <resultsperpage></resultsperpage>
    <page></page>
</return>
</code>```

I'm having difficulty forming the "c:condition" and "a:condition" Qname using Jsonix. Both Qname contains a Prefix but don't have the namespace.

My current code is:

```<code>{
    type: 'element',
    name: 'ccondition',
    elementName: {
        localPart: 'condition',
        prefix: 'c',
        namespaceURI: 'c'
    },
    typeInfo: 'DOXML.ComplexCondition'
},
</code>```

This will result in the following:

<c:condition xmlns:c="c">

Anyone knows how to use Jsonix to generate the required Qname - "c:condition" that is without the namespaceURI?

答:
In your example, the prefix c is actually bound to the namespace http://some.com/xsd/complexCondition in this line:

<filters xmlns:a="http://some.com/xsd/atomicCondition" xmlns:c="http://some.com/xsd/complexCondition">

Both you prefixes a und c are bound to non-empty namespaces within the scope of the filters element.

So you should actually do:

{
    type: 'element',
    name: 'ccondition',
    elementName: {
        localPart: 'condition',
        prefix: 'c',
        namespaceURI: 'http://some.com/xsd/complexCondition'
    },
    typeInfo: 'DOXML.ComplexCondition'
}

I think you should be able to map to the empty namespace with namespaceURI: '', but this is not what you need in your case, if I see it correctly.

Body:
I'm required to send an XML with the following elements:

<return>
    <getrooms>true</getrooms>
    <filters xmlns:a="http://some.com/xsd/atomicCondition" xmlns:c="http://some.com/xsd/complexCondition">
        <city></city>
        <country></country>
        <c:condition>

                <fieldname>fieldName</fieldname>
                <fieldtest>fieldTest</fieldtest>
                <fieldvalues>
                    <fieldvalue>fieldValue</fieldvalue>
                </fieldvalues>

            <operator>operator</operator>

                <fieldname>fieldName</fieldname>
                <fieldtest>fieldTest</fieldtest>
                <fieldvalues>
                    <fieldvalue>fieldValue</fieldvalue>
                 </fieldvalues>

         </c:condition>
    </filters>
    <resultsperpage></resultsperpage>
    <page></page>
</return>

I'm having difficulty forming the "c:condition" and "a:condition" Qname using Jsonix. Both Qname contains a Prefix but don't have the namespace.

My current code is:

{
    type: 'element',
    name: 'ccondition',
    elementName: {
        localPart: 'condition',
        prefix: 'c',
        namespaceURI: 'c'
    },
    typeInfo: 'DOXML.ComplexCondition'
},

This will result in the following:

<c:condition xmlns:c="c">

Anyone knows how to use Jsonix to generate the required Qname - "c:condition" that is without the namespaceURI?


问:
How to draw a round image with PDFsharp
I am using PDFsharp to make a PDF file, and have succeeded to put an image on my page.

```<code>        byte[] imgBytes = interview.Application.CandidateImage.ImageBinary.ToArray();
        Stream stream = new MemoryStream(imgBytes);
        MemoryStream strm = new MemoryStream();
        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
        img.Save(strm, System.Drawing.Imaging.ImageFormat.Png);

        XImage xfoto = XImage.FromGdiPlusImage(img);

        gfx.DrawImage(xfoto, 30, 130, 300, 300);
</code>```

This gets the binary image data and the DrawImage will draw this image retrieved from the stream.

The thing is, I want to make the image round just as if I used img-circle class on HTML. Is there a function for this with PDFsharp? If not, how can I do this?

EDIT:

```<code>    void DrawClipPath(XGraphics gfx, PdfPage page)
    {

        XGraphicsPath path = new XGraphicsPath();
        path.AddEllipse((page.Width / 2) - 150, (page.Height / 2) - 120, 300, 300);
        gfx.Save();
        gfx.IntersectClip(path);

        // Draw a beam of dotted lines
        XPen pen = XPens.DarkRed.Clone();
        pen.DashStyle = XDashStyle.Dot;
        for (double r = 0; r <= 90; r += 0.5)
            gfx.DrawLine(pen, 0, 0, 250 * Math.Cos(r / 90 * Math.PI), 250 * Math.Sin(r / 90 * Math.PI));

        gfx.Restore();

    }
</code>```

答:
You can use images with transparency so that only the round part in the centre is visible.

Or use a hack: draw the image first, then draw a white mask over the image, leaving just the round part in the centre showing.

Title: How to draw a round image with PDFsharp

Body:
I am using PDFsharp to make a PDF file, and have succeeded to put an image on my page.

        byte[] imgBytes = interview.Application.CandidateImage.ImageBinary.ToArray();
        Stream stream = new MemoryStream(imgBytes);
        MemoryStream strm = new MemoryStream();
        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
        img.Save(strm, System.Drawing.Imaging.ImageFormat.Png);

        XImage xfoto = XImage.FromGdiPlusImage(img);

        gfx.DrawImage(xfoto, 30, 130, 300, 300);

This gets the binary image data and the DrawImage will draw this image retrieved from the stream.

The thing is, I want to make the image round just as if I used img-circle class on HTML. Is there a function for this with PDFsharp? If not, how can I do this?

EDIT:

    void DrawClipPath(XGraphics gfx, PdfPage page)
    {

        XGraphicsPath path = new XGraphicsPath();
        path.AddEllipse((page.Width / 2) - 150, (page.Height / 2) - 120, 300, 300);
        gfx.Save();
        gfx.IntersectClip(path);

        // Draw a beam of dotted lines
        XPen pen = XPens.DarkRed.Clone();
        pen.DashStyle = XDashStyle.Dot;
        for (double r = 0; r <= 90; r += 0.5)
            gfx.DrawLine(pen, 0, 0, 250 * Math.Cos(r / 90 * Math.PI), 250 * Math.Sin(r / 90 * Math.PI));

        gfx.Restore();

    }


问:
How to execute stored procedure by select in instead of =
How to execute stored procedure by select in instead of = by vb.net and mssql stored procedure</p>

```<code>Dim sSQL As String
Dim objConn As SqlConnection
Dim objcmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds = New DataSet()

sSQL = "getinvoice"
objConn = utility.getconnect
objcmd = New SqlCommand(sSQL, objConn)
objcmd.CommandType = CommandType.StoredProcedure
objcmd.Parameters.Add("@invoiceid", SqlDbType.VarChar)
objcmd.Parameters.Item("@invoiceid").Value = "1,5,13,18"    '<-- problem
da = New SqlDataAdapter(objcmd)
da.Fill(ds)

ALTER PROCEDURE [dbo].[getinvoices]
@invoiceid varchar(50)
AS
BEGIN
select * from invoice where invoiceid in @invoiceid     '<-- problem
END
</code>```

答:
I think you need to use dynamic query. Change the procedure as

```<code>ALTER PROCEDURE [dbo].[getinvoices]
    @invoiceid varchar(50)
    AS
    BEGIN
    declare @sql nvarchar(4000)
    set @sql =' select * from invoice where invoiceid in  ( '+ @invoiceid     +')'
    EXEC (@sql)
    END
</code>```

Or Use a split function to split the values out into a table variable (there's a lot of split functions out there, quick search will throw one up).

```<code> ALTER PROCEDURE [dbo].[getinvoices] @invoiceid VARCHAR(50)
AS
    BEGIN
        SELECT  *
        FROM    invoice
        WHERE   invoiceid IN ( SELECT   *
                               FROM     dbo.splitstring(@invoiceid) )

    END
</code>```

Check here for Split string function

Body:
How to execute stored procedure by select in instead of = by vb.net and mssql stored procedure

Dim sSQL As String
Dim objConn As SqlConnection
Dim objcmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds = New DataSet()

sSQL = "getinvoice"
objConn = utility.getconnect
objcmd = New SqlCommand(sSQL, objConn)
objcmd.CommandType = CommandType.StoredProcedure
objcmd.Parameters.Add("@invoiceid", SqlDbType.VarChar)
objcmd.Parameters.Item("@invoiceid").Value = "1,5,13,18"    '<-- problem
da = New SqlDataAdapter(objcmd)
da.Fill(ds)

ALTER PROCEDURE [dbo].[getinvoices]
@invoiceid varchar(50)
AS
BEGIN
select * from invoice where invoiceid in @invoiceid     '<-- problem
END

Body:
I think you need to use dynamic query. Change the procedure as

ALTER PROCEDURE [dbo].[getinvoices]
    @invoiceid varchar(50)
    AS
    BEGIN
    declare @sql nvarchar(4000)
    set @sql =' select * from invoice where invoiceid in  ( '+ @invoiceid     +')'
    EXEC (@sql)
    END

Or Use a split function to split the values out into a table variable (there's a lot of split functions out there, quick search will throw one up).

 ALTER PROCEDURE [dbo].[getinvoices] @invoiceid VARCHAR(50)
AS
    BEGIN
        SELECT  *
        FROM    invoice
        WHERE   invoiceid IN ( SELECT   *
                               FROM     dbo.splitstring(@invoiceid) )

    END

Check here for Split string function


问:
Sticky Sidebar with JavaScript - Sticky only until specifed element
I want to create a sticky sidebar. But the sticky sidebar should only be stick until the ending of the sidebar has reached a specifed element.

Here is the webpage I want to get worked with the sidebar:
https://digital-hacks.de/vpn-verbindung-einrichten/

You can see the code in the head section or here.

```<code><script>
    var sidebar = $('#sidebar-content'),
        nav = $('.sidebar-content'),
        startPosition = sidebar .offset().top,
        stopPosition = $('#abspann').offset().top - nav.outerHeight();

    $(document).scroll(function () {
        //stick nav to top of page
        var y = $(this).scrollTop()

        if (y > startPosition) {
            nav.addClass('sticky');
            if (y > stopPosition) {
                nav.css('top', stopPosition - y);
            } else {
                nav.css('top', 0);
            }
        } else {
            nav.removeClass('sticky');
        }
    });
</script>
</code>```

I want that the sidebar gets attached to the screen if the user scrolls down and it should end if the ending of the sidebar has reached the element #abspann.

But I get a error in my code:
Uncaught TypeError: $ is not a function at (index):415

How can I get this working?

I found the sourcecode here.

Greetings

答:
First you have to replace $ with jQuery and then try this,

```<code>var sidebar = jQuery('#sidebar-wrap'),
    nav = jQuery('.sidebar-content'),
    startPosition = sidebar.offset().top,
    stopPosition = jQuery('#abspann').offset().top - nav.outerHeight();

jQuery(document).scroll(function () {
    //stick nav to top of page
    var y = jQuery(this).scrollTop()

    if (y > startPosition) {
        nav.addClass('sticky');
        if (y > stopPosition) {
            nav.css('top', stopPosition - y);
        } else {
            nav.css('top', 0);
        }
    } else {
        nav.removeClass('sticky');
    }
});
</code>```

Also you have to add id here

```<code><div class="wpb_wrapper" id="sidebar-wrap">
</code>```

in wrapper of sidebar
and add style for sticky

```<code>.sticky {
    position: fixed;
    top:0;
}
</code>```

Body:
I want to create a sticky sidebar. But the sticky sidebar should only be stick until the ending of the sidebar has reached a specifed element.

Here is the webpage I want to get worked with the sidebar:
https://digital-hacks.de/vpn-verbindung-einrichten/

You can see the code in the head section or here.

I want that the sidebar gets attached to the screen if the user scrolls down and it should end if the ending of the sidebar has reached the element #abspann.

But I get a error in my code:
Uncaught TypeError: $ is not a function at (index):415

How can I get this working?

I found the sourcecode here.

Greetings

Body:
First you have to replace $ with jQuery and then try this,

var sidebar = jQuery('#sidebar-wrap'),
    nav = jQuery('.sidebar-content'),
    startPosition = sidebar.offset().top,
    stopPosition = jQuery('#abspann').offset().top - nav.outerHeight();

jQuery(document).scroll(function () {
    //stick nav to top of page
    var y = jQuery(this).scrollTop()

    if (y > startPosition) {
        nav.addClass('sticky');
        if (y > stopPosition) {
            nav.css('top', stopPosition - y);
        } else {
            nav.css('top', 0);
        }
    } else {
        nav.removeClass('sticky');
    }
});

Also you have to add id here

<div class="wpb_wrapper" id="sidebar-wrap">

in wrapper of sidebar
and add style for sticky

.sticky {
    position: fixed;
    top:0;
}


问:
Polymer2.0- Trying to download DIV content of custom element
I am trying to download div content of custom element using document.getElementById of the div and trying to implement download option from the JS FIddle - http://jsfiddle.net/evx9stLb/

From console, I am getting below error

pen.js:6 Uncaught TypeError: Cannot read property 'innerHTML' of null
    at download (pen.js:6)
    at HTMLButtonElement.onclick (index.html:15)

HTML:

```<code><head>
  <base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-collapse/iron-collapse.html">
</head>
<body>

  <x-foo></x-foo>

<button onClick="download()">Download</button>
  <dom-module id="x-foo">
    <template>

      <button on-click="toggle">toggle collapse</button>
      <div id="content">
<iron-collapse id="collapse">
  <div>Content goes here...</div>
</iron-collapse>
      </div>
    </template>
  </dom-module>
</body>
</code>```

JS:

```<code>function download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("content").innerHTML;
    a.click();
}

    class XFoo extends Polymer.Element {
      static get is() { return 'x-foo'; }

      static get properties() {
        return {};

      }
         toggle() {
    this.$.collapse.toggle();
  }

    }
    customElements.define(XFoo.is, XFoo);
</code>```

Code which I am below - https://codepen.io/nagasai/pen/ZyRKxj

答:
Make some updates, and help this would help,

HTML

```<code><head>
  <base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-collapse/iron-collapse.html">
</head>
<body>

  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
<button on-click="download">Download</button>

      <button on-click="toggle">toggle collapse</button>
      <div id="content">
<iron-collapse id="collapse">
  <div>Content goes here...</div>
</iron-collapse>
      </div>
    </template>
  </dom-module>
</body>
</code>```

JS

```<code>    class XFoo extends Polymer.Element {
      static get is() { return 'x-foo'; }

      static get properties() {
        return {};

      }
         toggle() {
    this.$.collapse.toggle();
  }
download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + this.$.content.innerHTML;
    a.click();
  console.log(this.$.content.innerHTML);
}

    }
    customElements.define(XFoo.is, XFoo);
</code>```

https://codepen.io/renfeng/pen/BZOQro

Body:
I am trying to download div content of custom element using document.getElementById of the div and trying to implement download option from the JS FIddle - http://jsfiddle.net/evx9stLb/

From console, I am getting below error

pen.js:6 Uncaught TypeError: Cannot read property 'innerHTML' of null
    at download (pen.js:6)
    at HTMLButtonElement.onclick (index.html:15)

HTML:

  <base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-collapse/iron-collapse.html">

  <x-foo></x-foo>

<button onClick="download()">Download</button>
  <dom-module id="x-foo">
    <template>

      <button on-click="toggle">toggle collapse</button>

<iron-collapse id="collapse">

Content goes here...

</iron-collapse>

    </template>
  </dom-module>

JS:

function download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("content").innerHTML;
    a.click();
}

    class XFoo extends Polymer.Element {
      static get is() { return 'x-foo'; }

      static get properties() {
        return {};

      }
         toggle() {
    this.$.collapse.toggle();
  }

    }
    customElements.define(XFoo.is, XFoo);

Code which I am below - https://codepen.io/nagasai/pen/ZyRKxj

Body:
Make some updates, and help this would help,

HTML

<head>
  <base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-collapse/iron-collapse.html">
</head>
<body>

  <x-foo></x-foo>

  <dom-module id="x-foo">
    <template>
<button on-click="download">Download</button>

      <button on-click="toggle">toggle collapse</button>
      <div id="content">
<iron-collapse id="collapse">
  <div>Content goes here...</div>
</iron-collapse>
      </div>
    </template>
  </dom-module>
</body>

JS

    class XFoo extends Polymer.Element {
      static get is() { return 'x-foo'; }

      static get properties() {
        return {};

      }
         toggle() {
    this.$.collapse.toggle();
  }
download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + this.$.content.innerHTML;
    a.click();
  console.log(this.$.content.innerHTML);
}

    }
    customElements.define(XFoo.is, XFoo);

https://codepen.io/renfeng/pen/BZOQro


问:
Group values of keys in ruby hash in one hash and print specific value
This is my hash:

```<code>{"Specialty"=>"Other (note in description);Medical;Dental;Vision", "Value"=>"https://www.example.com/ca"}
{"Value"=>"P.O. BOX 60007 LOS ANGELES, CA 90060"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"800-824-0898"}
{"Specialty"=>"Urgent Care;Medical", "Value"=>"800-700-9186"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"800-677-6669"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"https://www.example.com"}
{"Specialty"=>"Claims", "Value"=>"https://www.example.com/consumer/claims/claimsoverview"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"https://example/example/apps/services/www/ABCBS/mobilewebapp/default/index.html#/providers/search"}
{""Specialty"=>"Claims;Customer Service;Medical", "Value"=>"800-888-8288"}
</code>```

You can see from this that the key value has differed values in each hash table, and I would like to print only one specific value, that is P.O. BOX 60007 LOS ANGELES, CA 90060

I tried printing the values of the hash by hash["value"] and it prints all the contents of the values. I tried loading them into an array[] by using to_s function to print the value I want, but one array is loaded with all these values or I may be loading the array wrong.

```<code>array = []
array = medical.split("\n")
text = array.to_s
text1 = array.index{|s| s.include?("P.O.")}
puts text1
</code>```

Can someone help me with how do I print that specific hash value inspite of various values existing in the key named value

答:
```<code>array_hashes = [
    {"Specialty"=>"Other (note in description);Medical;Dental;Vision", "Value"=>"https://www.example.com/ca"},
    {"Value"=>"P.O. BOX 60007 LOS ANGELES, CA 90060"},
    {"Specialty"=>"Pharmacy;Medical", "Value"=>"800-824-0898"},
    {"Specialty"=>"Urgent Care;Medical", "Value"=>"800-700-9186"},
    {"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"800-677-6669"},
    {"Specialty"=>"Pharmacy;Medical", "Value"=>"https://www.example.com"},
    {"Specialty"=>"Claims", "Value"=>"https://www.example.com/consumer/claims/claimsoverview"},
    {"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"https://example/example/apps/services/www/ABCBS/mobilewebapp/default/index.html#/providers/search"},
    {"Specialty"=>"Claims;Customer Service;Medical", "Value" => "800-888-8288"}]

> array_hashes.select{|h| h["Value"].include?("P.O.")}.flat_map(&:values).first
#=> "P.O. BOX 60007 LOS ANGELES, CA 90060"
</code>```

Body:
This is my hash:

{"Specialty"=>"Other (note in description);Medical;Dental;Vision", "Value"=>"https://www.example.com/ca"}
{"Value"=>"P.O. BOX 60007 LOS ANGELES, CA 90060"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"800-824-0898"}
{"Specialty"=>"Urgent Care;Medical", "Value"=>"800-700-9186"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"800-677-6669"}
{"Specialty"=>"Pharmacy;Medical", "Value"=>"https://www.example.com"}
{"Specialty"=>"Claims", "Value"=>"https://www.example.com/consumer/claims/claimsoverview"}
{"Specialty"=>"Urgent Care;Emergency Care;Medical;Chiropractor;Acupuncture", "Value"=>"https://example/example/apps/services/www/ABCBS/mobilewebapp/default/index.html#/providers/search"}
{""Specialty"=>"Claims;Customer Service;Medical", "Value"=>"800-888-8288"}

You can see from this that the key value has differed values in each hash table, and I would like to print only one specific value, that is P.O. BOX 60007 LOS ANGELES, CA 90060

I tried printing the values of the hash by hash["value"] and it prints all the contents of the values. I tried loading them into an array[] by using to_s function to print the value I want, but one array is loaded with all these values or I may be loading the array wrong.

array = []
array = medical.split("\n")
text = array.to_s
text1 = array.index{|s| s.include?("P.O.")}
puts text1

Can someone help me with how do I print that specific hash value inspite of various values existing in the key named value


Title: C# How can i split strings?

Body:
There is a file includes some strings, i'm gonna code a C# form project. I need to split them in their ":" and after splitting labels will show that splitted strings.

Here is the text i supposed to split

1096:001:161208:092218:1935:001:H:101:0006:                :00+00000+000000001
1096:001:161208:092218:1935:002:w:100:0006:                :00:00000:00000000R
1096:001:161208:092218:1935:003:S:101:0508:   2416100000006+00010010*000000140
1096:001:161208:092221:1935:004:S:101:0501:   8691397181056+00010010*000000250
1096:001:161208:092228:1935:005:l:100:0000:LCS SUCCESS     :00000000+000000000
1096:001:161208:092231:1935:006:T:110:0006:                :01+00001+000002000
1096:001:161208:092231:1935:007:T:114:0006:                :01+00000-000001610
1096:001:161208:092231:1935:008:V:111:0006:          %1    :00+00001+000000248
1096:001:161208:092231:1935:009:V:110:0006:          %1    :00+00001+000000002
1096:001:161208:092231:1935:010:V:121:0006:          %8    :00+00001+000000130
1096:001:161208:092231:1935:011:V:120:0006:          %8    :00+00001+000000010
1096:001:161208:092231:1935:012:w:100:0006:                :00:00000:00000000R
1096:001:161208:092231:1935:013:q:100:0000:                :000000000000000000
1096:001:161208:092231:1935:014:F:100:0006:                :00+00002+000000390
FIS :001:161208:092231:1935:015: :100:0006:TN 13091080     :00+01178+000000390

The software will import these data from a txt file, after that it will split all ":" and it will write to the labels in form.

It should be like this:

Label1=1096 Label2=001 Label3=161208 Label4=092218 Label5=1935 Label6=001
Label7=H Label8=101 Label9=0006 Label10=00 Label11=00000 Label12=000000001

Also it should sum %1 %1 %8 %8 located spaces between ":" in Label13

Body:
String.Split()

While I have that feeling you didn't even try to google your issue, and have no clue how to code anything (String.Split is pretty straight forward), here's some code to get you started:

            string source = @"
1096:001:161208:092218:1935:001:H:101:0006:                :00+00000+000000001
1096:001:161208:092218:1935:002:w:100:0006:                :00:00000:00000000R
1096:001:161208:092218:1935:003:S:101:0508:   2416100000006+00010010*000000140
1096:001:161208:092221:1935:004:S:101:0501:   8691397181056+00010010*000000250
1096:001:161208:092228:1935:005:l:100:0000:LCS SUCCESS     :00000000+000000000
1096:001:161208:092231:1935:006:T:110:0006:                :01+00001+000002000
1096:001:161208:092231:1935:007:T:114:0006:                :01+00000-000001610
1096:001:161208:092231:1935:008:V:111:0006:          %1    :00+00001+000000248
1096:001:161208:092231:1935:009:V:110:0006:          %1    :00+00001+000000002
1096:001:161208:092231:1935:010:V:121:0006:          %8    :00+00001+000000130
1096:001:161208:092231:1935:011:V:120:0006:          %8    :00+00001+000000010
1096:001:161208:092231:1935:012:w:100:0006:                :00:00000:00000000R
1096:001:161208:092231:1935:013:q:100:0000:                :000000000000000000
1096:001:161208:092231:1935:014:F:100:0006:                :00+00002+000000390
FIS :001:161208:092231:1935:015: :100:0006:TN 13091080     :00+01178+000000390
            ";
            string[] lines = source.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            foreach(string line in lines) {
                string[] values = line.Split(new char[] {':'}, StringSplitOptions.RemoveEmptyEntries);
                int counter = 1;
                foreach(string value in values) {
                    Console.Write("Label" + counter + ": " + value + "   ");
                    counter++;
                }
                Console.WriteLine("-");
            }

            Console.ReadLine();

Just start a new Console Project and paste this in Main(). The rest is up to you.


问:
swing layout: vertical flow
What LayoutManager should I use to achieve a transposed version of FlowLayout?

Essentially, I want a vertical list which occupies multiple columns if it can't fit all of it's components within one column.

```<code>+------------------------+
| item 1                 |
| item 2                 |
| item 3                 |
| item 4                 |
| item 5                 |
| item 6                 |
| item 7                 |
| item 8                 |
+------------------------+
</code>```

or

```<code>+------------------------+
| item 1  item 7         |
| item 2  item 8         |
| item 3                 |
| item 4                 |
| item 5                 |
| item 6                 |
+------------------------+
</code>```

this wrapping logic needs to happen dynamically, ie as the container is resized.

答:
I modified the GridLayout to layout components by column first instead of by row:

http://forums.oracle.com/forums/thread.jspa?messageID=5716765#5716765

Title: swing layout: vertical flow

Body:
What LayoutManager should I use to achieve a transposed version of FlowLayout?

Essentially, I want a vertical list which occupies multiple columns if it can't fit all of it's components within one column.

+------------------------+
| item 1                 |
| item 2                 |
| item 3                 |
| item 4                 |
| item 5                 |
| item 6                 |
| item 7                 |
| item 8                 |
+------------------------+

or

+------------------------+
| item 1  item 7         |
| item 2  item 8         |
| item 3                 |
| item 4                 |
| item 5                 |
| item 6                 |
+------------------------+

this wrapping logic needs to happen dynamically, ie as the container is resized.


问:
Android: Keep asynctask even after app is killed
I have this code below that I'm using to test the life cycle of the asynctask. What I want to do is to let the asynctask finish even if the app is forcibly closed by the user. It shows a notification which increments the progress every second. The asynctask is called from a Fragment. However, when I forcibly terminate the app by pressing all apps then swiping it off, the notification stops and no longer increments. See my code below.

Is this the case or am I doing something wrong?

Also, the reason I'm using asynctask is because I want to allow the user to cancel the task whenever possible. I believe this can't be done with IntentService? (Correct me if I'm wrong on this).

Appreciate any help.

UPDATE: I am now trying foreground service as suggested by @John Wick and @Abishek. However, I am not able to stop the service the way I want it to. When I click stop, the loop goes on and does not stop.

public class ForegroundService extends Service {

```<code>    boolean isCancelled = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent.getAction().equals("Start")) {
            Log.d("Action", "Start");
            Intent notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.setAction("Start");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Intent closeIntent = new Intent(this, ForegroundService.class);
            closeIntent.setAction("Stop");
            PendingIntent pCloseIntent = PendingIntent.getService(this, 0, closeIntent, 0);

            Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            NotificationManagerCompat manager = (NotificationManagerCompat.from(this));
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

            builder.setContentTitle("Truiton Music Player");
            builder.setTicker("Truiton Music Player");
            builder.setContentText("My Music");
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false));
            builder.setContentIntent(pendingIntent);
            builder.addAction(android.R.drawable.ic_media_pause, "Stop", pCloseIntent);

            startForeground(1, builder.build());
            for (int i = 0; i < 10; i++) {
                Log.d("Service", String.valueOf(i));
                builder.setProgress(9, i, false);

                if (isCancelled) {
                    builder.setContentTitle("Cancelled");
                    builder.setContentText("");
                    builder.setProgress(0, 0, false);
                    builder.mActions.clear();
                    manager.notify(1, builder.build());
                } else {
                    if (i == 9) {
                        builder.setContentTitle("Done");
                        builder.setContentText("");
                        builder.setProgress(0, 0, false);
                        manager.notify(1, builder.build());
                    } else {
                        manager.notify(1, builder.build());
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            stopForeground(true);
        } else {
            Log.d("Action", "Start");
            isCancelled = true;
            stopForeground(true);
            stopSelf();
        }

        return START_STICKY;
    }

}
</code>```

答:
What you need here is Service and yes it can be stopped when you no longer need it, the advantage over AysncTask is even when you terminate your app from task manager you service whon't get affected.

To stop a service you will need to call

stopService(new Intent(//Service));

Now if you want to show notification which updates a counter then use foreground service for this.

https://developer.android.com/guide/components/services.html#Foreground

Body:
I have this code below that I'm using to test the life cycle of the asynctask. What I want to do is to let the asynctask finish even if the app is forcibly closed by the user. It shows a notification which increments the progress every second. The asynctask is called from a Fragment. However, when I forcibly terminate the app by pressing all apps then swiping it off, the notification stops and no longer increments. See my code below.

Is this the case or am I doing something wrong?

Also, the reason I'm using asynctask is because I want to allow the user to cancel the task whenever possible. I believe this can't be done with IntentService? (Correct me if I'm wrong on this).

Appreciate any help.

UPDATE: I am now trying foreground service as suggested by @John Wick and @Abishek. However, I am not able to stop the service the way I want it to. When I click stop, the loop goes on and does not stop.

public class ForegroundService extends Service {

    boolean isCancelled = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent.getAction().equals("Start")) {
            Log.d("Action", "Start");
            Intent notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.setAction("Start");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Intent closeIntent = new Intent(this, ForegroundService.class);
            closeIntent.setAction("Stop");
            PendingIntent pCloseIntent = PendingIntent.getService(this, 0, closeIntent, 0);

            Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            NotificationManagerCompat manager = (NotificationManagerCompat.from(this));
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

            builder.setContentTitle("Truiton Music Player");
            builder.setTicker("Truiton Music Player");
            builder.setContentText("My Music");
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false));
            builder.setContentIntent(pendingIntent);
            builder.addAction(android.R.drawable.ic_media_pause, "Stop", pCloseIntent);

            startForeground(1, builder.build());
            for (int i = 0; i < 10; i++) {
                Log.d("Service", String.valueOf(i));
                builder.setProgress(9, i, false);

                if (isCancelled) {
                    builder.setContentTitle("Cancelled");
                    builder.setContentText("");
                    builder.setProgress(0, 0, false);
                    builder.mActions.clear();
                    manager.notify(1, builder.build());
                } else {
                    if (i == 9) {
                        builder.setContentTitle("Done");
                        builder.setContentText("");
                        builder.setProgress(0, 0, false);
                        manager.notify(1, builder.build());
                    } else {
                        manager.notify(1, builder.build());
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            stopForeground(true);
        } else {
            Log.d("Action", "Start");
            isCancelled = true;
            stopForeground(true);
            stopSelf();
        }

        return START_STICKY;
    }

}


问:
How are the steps to access GPIOs in linux kernel modules?
I am struggling to find out, what steps are necessary to access a gpio-pin from a linux kernel module.
Maybe someone can explain it to me by a simple example. I like to use pin 4(input) and 33(output). My steps so far:

1.) Device Tree(dts): I leave the dts file untouched - Do I need to setup the pin 4 and 33 via pin control?

2.) kernel module: some pseudo code

```<code>gpio_is_valid(4)
gpio_request_one(4, GPIOF_DIR_IN | GPIOF_EXPORT_DIR_FIXED , "myPin4")
gpio_export(4, false)
gpio_get_value(4)

gpio_is_valid(33)
gpio_request_one(33, GPIOF_DIR_OUT | GPIOF_INIT_LOW | GPIOF_OPEN_SOURCE | GPIOF_EXPORT_DIR_FIXED , "myPin33")
gpio_export(33, false)
gpio_set_value(33, 1)
</code>```

How to do it in a proper way?

答:
I would suggest the combination of an own device tree file + a platform driver + character driver

0.) RTF

check how device trees(dts) are working

check how a platform device works

check how a character device works

gain some knowledge about gpios and dts

@gpio mappings

@subsystems using gpios

@Specifying GPIO information for devices

Read the informations provided by your SOC manufacturer.

The state-of-the-art way to access the gpios is via struct gpio_desc variables. They are created form the device tree.

1.) approach

To toggle a pin under linux you need to make shure, that 3 units are working togehter.

The pin-controller(pinctrl) defines how the output is driven. Open source, pull up etc.

The pin-multiplexer(pinmux) defines different functions for the pin.

The gpio-controller(gpioctrl) translates the gpio number. p.E.: 44 -> GPIO A 11

These components are implemented by the SOC manufacturer. For each platform there are differences. An example for the SAMA5D35xxx follows.

@the device tree

Define the pin controller

```<code>pinctrl@fffff200 {
    pinctrl_myPins: myPins {
        atmel,pins = <AT91_PIOA 2 AT91_PERIPH_GPIO AT91_PINCTRL_NONE  // pin 1
            AT91_PIOD 19 AT91_PERIPH_GPIO AT91_PINCTRL_NONE>; // pin 2
    };
};
</code>```

Create a node witch is linked to the own platform device:

```<code>myPins {
    compatible = "myPlatformDevice";

    pinctrl-names = "default";
    pinctrl-0 = <&pinctrl_myPins>;

    pin1 = <&pioA 2 GPIO_ACTIVE_HIGH>;
    pin2 = <&pioD 19 GPIO_ACTIVE_HIGH>;
};
</code>```

@create platform + char driver (pseudo code):

```<code>// ----------------------
// kernel message support(via dmesg)
// ----------------------
#define KMSG_DEBUG(fmt,args...) printk(KERN_DEBUG "myDrv" ": "fmt"\n", ##args)
#define KMSG_PERR(fmt,args...) printk(KERN_ERR "myDrv" ": "fmt"\n", ##args)
#define KMSG_PINFO(fmt,args...) printk(KERN_INFO "myDrv" ": "fmt"\n", ##args)
// ----------------------
// trace support via defining dMyDrvTrace
// ----------------------
#ifndef dMyDrvTrace
    #define TRACE(...)
#else
    #define TRACE(fmt,args...) printk(KERN_INFO "myDrv" ": [%s] "fmt"\n", __FUNCTION__, ##args)
#endif

typedef struct SMyDrvDrvData {
    struct platform_device *pdev; //!< next device
    // here goes the local/private data
    int gpiod_pin1;
    int gpiod_pin2;

    u32 pin1;
    u32 pin2;
} TMyDrvDrvData;

static struct dentry * gmyPlattformDrvDebugfsRootDir; //!< root dir at debugfs

static int myPlattformDrv_probe(struct platform_device *pdev);
static int myPlattformDrv_remove(struct platform_device *pdev);

#if defined(CONFIG_OF)
    //! filter for the device tree class
    static struct of_device_id gMyPlattformDrvdtsFilter[] = {
        {.compatible = "myPlatformDevice"},
        {}
    };
    MODULE_DEVICE_TABLE(of, gMyPlattformDrvdtsFilter);
#else
    #define gmyPlattformDrvdtsFilter (NULL)
#endif

static struct platform_device *MyPlattformDrv_devs[] = {
};

static struct platform_driver myPlattformDrv_driver = {
        .driver = {
            .name   = dMyPlattformDrvdriver,
            .owner  = THIS_MODULE,
            .of_match_table =  of_match_ptr(gMyPlattformDrvdtsFilter),
        },
        .probe      = myPlattformDrv_probe,
        .remove     = myPlattformDrv_remove,
};

// char device

static dev_t gMyCharDev;
static struct class *gMyCharDevClass;
static struct cdev gMyCharDev_cdev;

static int dev_open      (struct inode *, struct file *);
static int dev_release   (struct inode *, struct file *);
static ssize_t dev_read  (struct file *, char *, size_t, loff_t *);
static ssize_t dev_write (struct file *, const char *, size_t, loff_t *);

static const struct file_operations gMyCharDevOps =
{
    .read    = dev_read,
    .open    = dev_open,
    .write   = dev_write,
    .release = dev_release
};

//! looks up for the gpio name and request it
static int get_gpio(struct platform_device *pdev, const char * name, int * pGPIOnum)
{
    int n,i;
    int r;
    struct device_node * pDN;

    TRACE("look at %s for %s ...", pdev->name, name);
    // reset return value
    *pGPIOnum = 0;

    // parse device tree

    // get device tree entries associated with the device
    pDN = of_find_node_by_name(NULL, pdev->name);

    // parse pins
    n = of_gpio_named_count(pDN, name);
    if (n <= 0) {
        TRACE("no gpios found");
        return -1;
    }
    for (i = 0; i < n; i++) {
        // get pin number
        *pGPIOnum = of_get_named_gpio(pDN,name, i);
        if (*pGPIOnum == -EPROBE_DEFER) {
            return r;
        }
        // check if pin number is valid
        if (gpio_is_valid(*pGPIOnum)) {
            // yes
            // request pin
            r = devm_gpio_request(&pdev->dev, *pGPIOnum, name);
            if (r) {
                return r;
            } else {
                r = gpio_direction_output(*pGPIOnum, 0);
                }
                if (r) return r;
            }
        }
    }
    return 0;
}

//! probes the platform driver
static int myPlattformDrv_probe(struct platform_device *pdev)
{
    struct TMyDrvDrvData *priv;
    int i,j,r,gpioNum, ret;

    KMSG_PINFO("probe my driver ...");

    priv = kzalloc(sizeof(*priv), GFP_KERNEL);
    if (!priv) {
        KMSG_PERR("Failed to allocate memory for the private data structure");
        return -ENOMEM;
    }

    priv->pdev = pdev;
    platform_set_drvdata(pdev, priv);

    TRACE("setup gpios ...");
    r = get_gpio(pdev, "pin1", &gpioNum);
    if (r) {
        KMSG_PERR("Failed to find gpio \"pin1\" in device tree");
    }
    // save number
    priv->gpiod_pin1 = gpioNum;

    // create "pin1" debugfs entry
    debugfs_create_u32("pin1", S_IRUGO, gmyPlattformDrvDebugfsRootDir, &priv->Pin1);

    r = get_gpio(pdev, "pin2", &gpioNum);
    if (r) {
        KMSG_PERR("Failed to find gpio \"pin2\" in device tree");
    }
    // save number
    priv->gpiod_pin2 = gpioNum;

    // create "pin2" debugfs entry
    debugfs_create_u32("pin1", S_IRUGO, gmyPlattformDrvDebugfsRootDir, &priv->Pin2);

    // create device class
    TRACE("create myCharDev char device class");

    // create char dev region
    ret = alloc_chrdev_region(&gMyCharDev, 0, 1, "myCharDev");
    if( ret < 0) {
        KMSG_PERR("alloc_chrdev_region error %i", ret);
        goto error;
    }

    // create device class
    if((gMyCharDevClass = class_create(THIS_MODULE, dSEK4DevClass)) == NULL)
    {
        KMSG_PERR("class_create error");
        goto error_classCreate;
    }

    if(NULL == device_create(gMyCharDevClass, NULL, gMyCharDev, NULL, "myCharDev"))
    {
        KMSG_PERR("device_create error");
        goto error_deviceCreate;
    }

    cdev_init(&gMyCharDev_cdev, &gMyCharDevOps);
    ret = cdev_add(&gMyCharDev_cdev, gMyCharDev, 1);
    if(-1 == ret) {
        KMSG_PERR("cdev_add error %i", ret);
        goto error_device_add;
        return -1;
    }
    TRACE("added myCharDev char device");

    return 0;
// error handling block
error_std:
error_device_add:
    device_destroy(gMyCharDevClass, gMyCharDev);
error_deviceCreate:
    class_destroy(gMyCharDevClass);
error_classCreate:
    unregister_chrdev_region(gMyCharDev, 1);
error:
    return -1;
}
</code>```

Body:
I am struggling to find out, what steps are necessary to access a gpio-pin from a linux kernel module.
Maybe someone can explain it to me by a simple example. I like to use pin 4(input) and 33(output). My steps so far:

1.) Device Tree(dts): I leave the dts file untouched - Do I need to setup the pin 4 and 33 via pin control?

2.) kernel module: some pseudo code

gpio_is_valid(4)
gpio_request_one(4, GPIOF_DIR_IN | GPIOF_EXPORT_DIR_FIXED , "myPin4")
gpio_export(4, false)
gpio_get_value(4)

gpio_is_valid(33)
gpio_request_one(33, GPIOF_DIR_OUT | GPIOF_INIT_LOW | GPIOF_OPEN_SOURCE | GPIOF_EXPORT_DIR_FIXED , "myPin33")
gpio_export(33, false)
gpio_set_value(33, 1)

How to do it in a proper way?

Body:
I would suggest the combination of an own device tree file + a platform driver + character driver

0.) RTF

check how device trees(dts) are working

check how a platform device works

check how a character device works

gain some knowledge about gpios and dts

@gpio mappings

@subsystems using gpios

@Specifying GPIO information for devices

Read the informations provided by your SOC manufacturer.

The state-of-the-art way to access the gpios is via struct gpio_desc variables. They are created form the device tree.

1.) approach

To toggle a pin under linux you need to make shure, that 3 units are working togehter.

The pin-controller(pinctrl) defines how the output is driven. Open source, pull up etc.

The pin-multiplexer(pinmux) defines different functions for the pin.

The gpio-controller(gpioctrl) translates the gpio number. p.E.: 44 -> GPIO A 11

These components are implemented by the SOC manufacturer. For each platform there are differences. An example for the SAMA5D35xxx follows.

@the device tree

Define the pin controller

pinctrl@fffff200 {
    pinctrl_myPins: myPins {
        atmel,pins = <AT91_PIOA 2 AT91_PERIPH_GPIO AT91_PINCTRL_NONE  // pin 1
            AT91_PIOD 19 AT91_PERIPH_GPIO AT91_PINCTRL_NONE>; // pin 2
    };
};

Create a node witch is linked to the own platform device:

myPins {
    compatible = "myPlatformDevice";

    pinctrl-names = "default";
    pinctrl-0 = <&pinctrl_myPins>;

    pin1 = <&pioA 2 GPIO_ACTIVE_HIGH>;
    pin2 = <&pioD 19 GPIO_ACTIVE_HIGH>;
};

@create platform + char driver (pseudo code):

// ----------------------
// kernel message support(via dmesg)
// ----------------------
#define KMSG_DEBUG(fmt,args...) printk(KERN_DEBUG "myDrv" ": "fmt"\n", ##args)
#define KMSG_PERR(fmt,args...) printk(KERN_ERR "myDrv" ": "fmt"\n", ##args)
#define KMSG_PINFO(fmt,args...) printk(KERN_INFO "myDrv" ": "fmt"\n", ##args)
// ----------------------
// trace support via defining dMyDrvTrace
// ----------------------
#ifndef dMyDrvTrace
    #define TRACE(...)
#else
    #define TRACE(fmt,args...) printk(KERN_INFO "myDrv" ": [%s] "fmt"\n", __FUNCTION__, ##args)
#endif

typedef struct SMyDrvDrvData {
    struct platform_device *pdev; //!< next device
    // here goes the local/private data
    int gpiod_pin1;
    int gpiod_pin2;

    u32 pin1;
    u32 pin2;
} TMyDrvDrvData;

static struct dentry * gmyPlattformDrvDebugfsRootDir; //!< root dir at debugfs

static int myPlattformDrv_probe(struct platform_device *pdev);
static int myPlattformDrv_remove(struct platform_device *pdev);

#if defined(CONFIG_OF)
    //! filter for the device tree class
    static struct of_device_id gMyPlattformDrvdtsFilter[] = {
        {.compatible = "myPlatformDevice"},
        {}
    };
    MODULE_DEVICE_TABLE(of, gMyPlattformDrvdtsFilter);
#else
    #define gmyPlattformDrvdtsFilter (NULL)
#endif

static struct platform_device *MyPlattformDrv_devs[] = {
};

static struct platform_driver myPlattformDrv_driver = {
        .driver = {
            .name   = dMyPlattformDrvdriver,
            .owner  = THIS_MODULE,
            .of_match_table =  of_match_ptr(gMyPlattformDrvdtsFilter),
        },
        .probe      = myPlattformDrv_probe,
        .remove     = myPlattformDrv_remove,
};

// char device

static dev_t gMyCharDev;
static struct class *gMyCharDevClass;
static struct cdev gMyCharDev_cdev;

static int dev_open      (struct inode *, struct file *);
static int dev_release   (struct inode *, struct file *);
static ssize_t dev_read  (struct file *, char *, size_t, loff_t *);
static ssize_t dev_write (struct file *, const char *, size_t, loff_t *);

static const struct file_operations gMyCharDevOps =
{
    .read    = dev_read,
    .open    = dev_open,
    .write   = dev_write,
    .release = dev_release
};

//! looks up for the gpio name and request it
static int get_gpio(struct platform_device *pdev, const char * name, int * pGPIOnum)
{
    int n,i;
    int r;
    struct device_node * pDN;

    TRACE("look at %s for %s ...", pdev->name, name);
    // reset return value
    *pGPIOnum = 0;

    // parse device tree

    // get device tree entries associated with the device
    pDN = of_find_node_by_name(NULL, pdev->name);

    // parse pins
    n = of_gpio_named_count(pDN, name);
    if (n <= 0) {
        TRACE("no gpios found");
        return -1;
    }
    for (i = 0; i < n; i++) {
        // get pin number
        *pGPIOnum = of_get_named_gpio(pDN,name, i);
        if (*pGPIOnum == -EPROBE_DEFER) {
            return r;
        }
        // check if pin number is valid
        if (gpio_is_valid(*pGPIOnum)) {
            // yes
            // request pin
            r = devm_gpio_request(&pdev->dev, *pGPIOnum, name);
            if (r) {
                return r;
            } else {
                r = gpio_direction_output(*pGPIOnum, 0);
                }
                if (r) return r;
            }
        }
    }
    return 0;
}

//! probes the platform driver
static int myPlattformDrv_probe(struct platform_device *pdev)
{
    struct TMyDrvDrvData *priv;
    int i,j,r,gpioNum, ret;

    KMSG_PINFO("probe my driver ...");

    priv = kzalloc(sizeof(*priv), GFP_KERNEL);
    if (!priv) {
        KMSG_PERR("Failed to allocate memory for the private data structure");
        return -ENOMEM;
    }

    priv->pdev = pdev;
    platform_set_drvdata(pdev, priv);

    TRACE("setup gpios ...");
    r = get_gpio(pdev, "pin1", &gpioNum);
    if (r) {
        KMSG_PERR("Failed to find gpio \"pin1\" in device tree");
    }
    // save number
    priv->gpiod_pin1 = gpioNum;

    // create "pin1" debugfs entry
    debugfs_create_u32("pin1", S_IRUGO, gmyPlattformDrvDebugfsRootDir, &priv->Pin1);

    r = get_gpio(pdev, "pin2", &gpioNum);
    if (r) {
        KMSG_PERR("Failed to find gpio \"pin2\" in device tree");
    }
    // save number
    priv->gpiod_pin2 = gpioNum;

    // create "pin2" debugfs entry
    debugfs_create_u32("pin1", S_IRUGO, gmyPlattformDrvDebugfsRootDir, &priv->Pin2);

    // create device class
    TRACE("create myCharDev char device class");

    // create char dev region
    ret = alloc_chrdev_region(&gMyCharDev, 0, 1, "myCharDev");
    if( ret < 0) {
        KMSG_PERR("alloc_chrdev_region error %i", ret);
        goto error;
    }

    // create device class
    if((gMyCharDevClass = class_create(THIS_MODULE, dSEK4DevClass)) == NULL)
    {
        KMSG_PERR("class_create error");
        goto error_classCreate;
    }

    if(NULL == device_create(gMyCharDevClass, NULL, gMyCharDev, NULL, "myCharDev"))
    {
        KMSG_PERR("device_create error");
        goto error_deviceCreate;
    }

    cdev_init(&gMyCharDev_cdev, &gMyCharDevOps);
    ret = cdev_add(&gMyCharDev_cdev, gMyCharDev, 1);
    if(-1 == ret) {
        KMSG_PERR("cdev_add error %i", ret);
        goto error_device_add;
        return -1;
    }
    TRACE("added myCharDev char device");

    return 0;
// error handling block
error_std:
error_device_add:
    device_destroy(gMyCharDevClass, gMyCharDev);
error_deviceCreate:
    class_destroy(gMyCharDevClass);
error_classCreate:
    unregister_chrdev_region(gMyCharDev, 1);
error:
    return -1;
}


问:
C# Execute the catch block when the type is string
Here I'm struggling to work with catch block like I wanted to execute the catch block when the value type is a string.

Here I'm using dynamic type to accept all the type of values when the method will returns.

Now I wanted to execute the catch block when the method will return the string type.
Here my code is

```<code>dynamic paymentResult = null;
try
{
    paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
}
catch (Exception ex) when (paymentResult is string)
{
    return Content(HttpStatusCode.InternalServerError,
        $"{Messages.DonationPaymentFailed} {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
}
</code>```

答:
You don't need a catch block for this. try-catch is used to handle exceptions. If it is an expected behavior just test for the type:

```<code> dynamic paymentResult = null;

 paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);

 if(paymentResult is string)
 {
      return Content(HttpStatusCode.InternalServerError, $"
           {Messages.DonationPaymentFailed}
           {checkoutViewModel.PaymentMethod} : paymentResult is a string");
 }
</code>```

If for some reason you really need to do it in a catch block you will have to throw an Exception:

```<code>dynamic paymentResult = null;

try
{
     paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);

     if(paymentResult is string)
     {
         throw new Exception("The result was of type string");
     }
 }
 catch (Exception ex)
 {
    return Content(HttpStatusCode.InternalServerError, $"
           {Messages.DonationPaymentFailed}
           {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
 }
</code>```

Body:
Here I'm struggling to work with catch block like I wanted to execute the catch block when the value type is a string.

Here I'm using dynamic type to accept all the type of values when the method will returns.

Now I wanted to execute the catch block when the method will return the string type.
Here my code is

dynamic paymentResult = null;
try
{
    paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
}
catch (Exception ex) when (paymentResult is string)
{
    return Content(HttpStatusCode.InternalServerError,
        $"{Messages.DonationPaymentFailed} {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
}

Body:
You don't need a catch block for this. try-catch is used to handle exceptions. If it is an expected behavior just test for the type:

 dynamic paymentResult = null;

 paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);

 if(paymentResult is string)
 {
      return Content(HttpStatusCode.InternalServerError, $"
           {Messages.DonationPaymentFailed}
           {checkoutViewModel.PaymentMethod} : paymentResult is a string");
 }

If for some reason you really need to do it in a catch block you will have to throw an Exception:

dynamic paymentResult = null;

try
{
     paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);

     if(paymentResult is string)
     {
         throw new Exception("The result was of type string");
     }
 }
 catch (Exception ex)
 {
    return Content(HttpStatusCode.InternalServerError, $"
           {Messages.DonationPaymentFailed}
           {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
 }


问:
Execute Immediate fails even with CREATE table grant
I have a problem where I am creating a table using the execute immediate command in the stored procedure. However I get the error of "insufficient privileges". I checked other threads and made sure that the user has "CREATE TABLE" privilege granted to it. However I still keep seeing the same error.

```<code>SQL> select * from USER_SYS_PRIVS;

USERNAME                       PRIVILEGE                                ADM
------------------------------ ---------------------------------------- ---
MYUSER            CREATE VIEW                              NO
MYUSER            UNLIMITED TABLESPACE                     NO

SQL> select * from session_privs;

PRIVILEGE
----------------------------------------
CREATE SESSION
UNLIMITED TABLESPACE
CREATE TABLE
CREATE CLUSTER
CREATE VIEW
CREATE SEQUENCE
CREATE PROCEDURE
CREATE TRIGGER
CREATE TYPE
CREATE OPERATOR
CREATE INDEXTYPE

11 rows selected.
</code>```

The Dummy procedure I created is :

```<code>create or replace procedure sp_dummy
   as
   begin
      execute immediate 'Create table Dummy99_99 (Dummy_Field number)';
   end sp_dummy;
   /
</code>```

Detailed error :

```<code>ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "MYUSER.SP_DUMMY", line 4
ORA-06512: at line 1
</code>```

Is there something wrong I am doing ?

答:
When using execute immediate, procedure must explicitly tell oracle that it must run with privileges of a particular user.

AUTHID CURRENT_USER, to use the privileges of user running the procedure.
AUTHID DEFINER, to use the privileges of owner of the procedure.

This is done using AUTHID option while creating a procedure.

```<code>CREATE OR REPLACE PROCEDURE PROC_NAME AUTHID CURRENT_USER
IS
.....
</code>```

I faced a similar issue and got the understanding from:
Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Body:
I have a problem where I am creating a table using the execute immediate command in the stored procedure. However I get the error of "insufficient privileges". I checked other threads and made sure that the user has "CREATE TABLE" privilege granted to it. However I still keep seeing the same error.

SQL> select * from USER_SYS_PRIVS;

USERNAME                       PRIVILEGE                                ADM
------------------------------ ---------------------------------------- ---
MYUSER            CREATE VIEW                              NO
MYUSER            UNLIMITED TABLESPACE                     NO

SQL> select * from session_privs;

PRIVILEGE
----------------------------------------
CREATE SESSION
UNLIMITED TABLESPACE
CREATE TABLE
CREATE CLUSTER
CREATE VIEW
CREATE SEQUENCE
CREATE PROCEDURE
CREATE TRIGGER
CREATE TYPE
CREATE OPERATOR
CREATE INDEXTYPE

11 rows selected.

The Dummy procedure I created is :

create or replace procedure sp_dummy
   as
   begin
      execute immediate 'Create table Dummy99_99 (Dummy_Field number)';
   end sp_dummy;
   /

Detailed error :

ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "MYUSER.SP_DUMMY", line 4
ORA-06512: at line 1

Is there something wrong I am doing ?

Body:
When using execute immediate, procedure must explicitly tell oracle that it must run with privileges of a particular user.

AUTHID CURRENT_USER, to use the privileges of user running the procedure.
AUTHID DEFINER, to use the privileges of owner of the procedure.

This is done using AUTHID option while creating a procedure.

CREATE OR REPLACE PROCEDURE PROC_NAME AUTHID CURRENT_USER
IS
.....

I faced a similar issue and got the understanding from:
Execute Immediate within a stored procedure keeps giving insufficient priviliges error


问:
SQL object_definition returning definition of different, non-existent object?
I've encountered something I find very, very strange. I'm using something like object_definition(object_id('StoredProcedureName')) to get the definition of a stored procedure. However, I noticed that on some of our databases, the output was

Create Procedure dbo.SomeOtherStoredProcedure

This was an issue, because I was using the object_definition to alter the stored procedure, and when I tried to execute the new query it would say that the stored procedure 'SomeOtherStoredProcedure' didn't exist.

I know I'm not specifying the object type when using object_id, but (correct me if I'm wrong) since the returned definition is also a stored procedure, I don't think that's the issue here.

Is there some quirk to object_definition or object_id that I don't know about? What could cause this?

(SQL Azure, SSMS 2012)

答:
As Aaron mentioned, the cause is sp_rename. As MSDN says:

Renaming a stored procedure, function, view, or trigger will not change the name of the corresponding object name in the definition column of the sys.sql_modules catalog view

You can get the updated object name from sys.objects. And a "true" definition can be found by fiddling with strings: find where the old object name is located in a corrupted definition and replace it with a new object name. Hope that's clear enough.