问:
Changing "if" python statement to apply to any obstacle instead of specific obstacles
(Disclaimer: I'm very new to coding so sorry if this is a ridiculously stupid question!)

I'm currently trying to change the Python code below so that instead of needing 4 obstacles to not be false in order to call the obstacle_detection method (which is defined earlier in the program), it will call the method if any number of obstacles are not False.

```<code>if obstacle is not False and obstacle2 is not False and obstacle3 is not False and obstacle4 is not False:
    test = obstacle_detection(obstacle, pos)
    test2 = obstacle_detection(obstacle2, pos)
    test3 = obstacle_detection(obstacle3, pos)
    test4 = obstacle_detection(obstacle4, pos)

else:
    test = 0
    test2 = 0
    test3 = 0
    test4 = 0
</code>```

I the tried changing it to something like below but I get the error of "iteration over non sequence" (and I wouldn't be surprised if this is completely the wrong idea):

```<code>if any(obstacle) is not False:
    for i in obstacle:
        test = obstacle_detection(obstacle, pos)

else:
    test = 0
</code>```

答:
As mentioned in comments this will work

```<code>if obstacle and obstacle2 and obstacle3 and obstacle4:
</code>```

Also python has an any and all operater that can be used on any sequence (lists, tuples, dict)

let's say you have a list filled with obstacles like this obstacle_list = [True, True, True, True] then the above statement can be rewritten like this

```<code>if all(obstacle_list):
</code>```

Body:
(Disclaimer: I'm very new to coding so sorry if this is a ridiculously stupid question!)

I'm currently trying to change the Python code below so that instead of needing 4 obstacles to not be false in order to call the obstacle_detection method (which is defined earlier in the program), it will call the method if any number of obstacles are not False.

if obstacle is not False and obstacle2 is not False and obstacle3 is not False and obstacle4 is not False:
    test = obstacle_detection(obstacle, pos)
    test2 = obstacle_detection(obstacle2, pos)
    test3 = obstacle_detection(obstacle3, pos)
    test4 = obstacle_detection(obstacle4, pos)

else:
    test = 0
    test2 = 0
    test3 = 0
    test4 = 0

I the tried changing it to something like below but I get the error of "iteration over non sequence" (and I wouldn't be surprised if this is completely the wrong idea):

if any(obstacle) is not False:
    for i in obstacle:
        test = obstacle_detection(obstacle, pos)

else:
    test = 0

Body:
As mentioned in comments this will work

if obstacle and obstacle2 and obstacle3 and obstacle4:

Also python has an any and all operater that can be used on any sequence (lists, tuples, dict)

let's say you have a list filled with obstacles like this obstacle_list = [True, True, True, True] then the above statement can be rewritten like this

if all(obstacle_list):


来源: stackexchange

问:
Tap Gesture on List View Items
I am trying to open another view after tapping on an item in the list view.
I have tried adding a TapGestureRegonizer and even adding ViewCell with grids etc. None of these seem to work. I have added a tap gesture to a label and that seemed to work but the same does not work for list view items. This seems like a simple problem for something like list view, but there doesnt seem to be a built in functionality for this.

The Xaml:

```<code><ListView x:Name="dataList"
      ItemsSource="{Binding routeLabels}"
      HasUnevenRows="True"
      Grid.Row="1"
      Grid.Column="0"
      Grid.ColumnSpan="3">
</ListView>
</code>```

The code behind:

```<code>var listviewgesture = new TapGestureRecognizer();
listviewgesture.SetBinding(TapGestureRecognizer.CommandProperty,"LoadRoutePage");
dataList.GestureRecognizers.Add(listviewgesture);
</code>```

The view model:

```<code>public ICommand LoadRoutePage { get; protected set; }

public DriverDashboardViewModel(INavigation navigation,MessagDatabase database)
    {
        this._database = database;
        this.Navigation = navigation;
        this.LoadNotifications = new Command(async () => await OpenNotificationsPage());
        this.LoadRoutePage = new Command(async () => await OpenRoutePage());

    }

public async Task OpenRoutePage()
    {

        await Navigation.PushAsync(new RoutePageView());
    }
</code>```

Just to be clear the LoadNotifications method does work in opening a page but LoadRoutePage does not. So I know there is some level of communication between the view and viewmodel.

答:
You're binding a command instead of an event to the "Tapped" event. Try something like this:

code behind:

```<code>var listviewgesture = new TapGestureRecognizer();
listviewgesture.Tapped += Handle_listViewItemTapped;
dataList.GestureRecognizers.Add(listviewgesture);
</code>```

ViewModel:

```<code>private void Handle_listViewItemTapped(object sender, EventArgs e)
{
    viewModel.OpenRoutePage();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Tap Gesture on List View Items

Body:
I am trying to open another view after tapping on an item in the list view.
I have tried adding a TapGestureRegonizer and even adding ViewCell with grids etc. None of these seem to work. I have added a tap gesture to a label and that seemed to work but the same does not work for list view items. This seems like a simple problem for something like list view, but there doesnt seem to be a built in functionality for this.

The Xaml:

<ListView x:Name="dataList"
      ItemsSource="{Binding routeLabels}"
      HasUnevenRows="True"
      Grid.Row="1"
      Grid.Column="0"
      Grid.ColumnSpan="3">
</ListView>

The code behind:

var listviewgesture = new TapGestureRecognizer();
listviewgesture.SetBinding(TapGestureRecognizer.CommandProperty,"LoadRoutePage");
dataList.GestureRecognizers.Add(listviewgesture);

The view model:

public ICommand LoadRoutePage { get; protected set; }

public DriverDashboardViewModel(INavigation navigation,MessagDatabase database)
    {
        this._database = database;
        this.Navigation = navigation;
        this.LoadNotifications = new Command(async () => await OpenNotificationsPage());
        this.LoadRoutePage = new Command(async () => await OpenRoutePage());

    }

public async Task OpenRoutePage()
    {

        await Navigation.PushAsync(new RoutePageView());
    }

Just to be clear the LoadNotifications method does work in opening a page but LoadRoutePage does not. So I know there is some level of communication between the view and viewmodel.

Body:
You're binding a command instead of an event to the "Tapped" event. Try something like this:

code behind:

var listviewgesture = new TapGestureRecognizer();
listviewgesture.Tapped += Handle_listViewItemTapped;
dataList.GestureRecognizers.Add(listviewgesture);

ViewModel:

private void Handle_listViewItemTapped(object sender, EventArgs e)
{
    viewModel.OpenRoutePage();
}


问:
wordpress pagination ads extra slashes to url
Working with custom post types I cant seem to get the pagination to work correct. All is working but when I click to the next page the url will get a extra slash in the url, not sure why this is happening but when using the pagination a lot will add every time a new slash to the url.

// out

```<code>site.com/projects/ ,
site.com/projects//page/2,
site.com/projects///page/3,
site.com/projects////page/4

...and so on.
</code>```

// the code used

```<code>    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

    $query = new WP_Query( array(
        'post_type'      => 'projects',
        'posts_per_page' => 5,
        'paged'          => $paged

    ) );

    if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

       the_title();

    endwhile;

        $total_pages = $query->max_num_pages;

        if ($total_pages > 1){

            $current_page = max(1, get_query_var('paged'));

            echo paginate_links(array(
                'base'      => get_pagenum_link(1) . '%_%',
                'format'    => '/page/%#%',
                'current'   => $current_page,
                'total'     => $total_pages,
                'prev_text' =>  esc_html__('volgende »', 'infrafocus'),
                'next_text' =>  esc_html__('« vorige' , 'infrafocus'),
            ));
        }

    }

    wp_reset_postdata();

    endif;
</code>```

答: Try changing 'format'    => '/page/%#%',  to 'format'    => 'page/%#%',

Body:
Working with custom post types I cant seem to get the pagination to work correct. All is working but when I click to the next page the url will get a extra slash in the url, not sure why this is happening but when using the pagination a lot will add every time a new slash to the url.

// out

site.com/projects/ ,
site.com/projects//page/2,
site.com/projects///page/3,
site.com/projects////page/4

...and so on.

// the code used

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

    $query = new WP_Query( array(
        'post_type'      => 'projects',
        'posts_per_page' => 5,
        'paged'          => $paged

    ) );

    if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

       the_title();

    endwhile;

        $total_pages = $query->max_num_pages;

        if ($total_pages > 1){

            $current_page = max(1, get_query_var('paged'));

            echo paginate_links(array(
                'base'      => get_pagenum_link(1) . '%_%',
                'format'    => '/page/%#%',
                'current'   => $current_page,
                'total'     => $total_pages,
                'prev_text' =>  esc_html__('volgende »', 'infrafocus'),
                'next_text' =>  esc_html__('« vorige' , 'infrafocus'),
            ));
        }

    }

    wp_reset_postdata();

    endif;


问:
sanitize data for SQL with JavaScript
I have a bunch of forms that have various input elements. I want to sanitize these on the server side (yes, I'm using server-side JavaScript) to use these inputs as parameters, and prevent special characters to be malformed.

Before you go, like "this belongs not in the realm of JavaScript", etc., etc.

I am using a multi-million licensed software solution, that well has JavaScript but apparently has no standard functions like this out of the box. So, whatever I am using, I can assure you that you probably have never touched it or heard of it. And it supports server side javascript, because well, the language is cool.

My first objective is to sanitize data before it goes in the database, and I just love the way for example how Ruby labels foreign data: tainted. And I rather have no tainted data. So I could google and copy paste some poor regex from here and there, and I got some sad example. However, I would like to have a function that would be said "well, that takes off 70% of the possible stuff from that data and a pretty darn good sanitize".

Basically a string from these elements should be escaped and I assume best practices are already existing for this wish of mine.

```<code>function sanitize(myString) { ... ; return myString }
</code>```

How can I escape symbols like '#!? and other special characters and how i can i get them back in reverse? I am aware of the JavaScript escape method, but I want to know if a function is already debugged and public available before I re-invent the wheel.

I considered:
- JavaScript Escape
- Base64 Encoding
- Regex

I just rather ask the people who have written such functions before.

Thanks,

答:
See update below

You're reinventing the wheel. Whatever you're using to talk to your database should have some kind of "prepared statement" concept. In Java it's literally the PreparedStatement class, but essentially any database access system should have something similar. You use these so that you're not building up SQL statements as strings. So for instance, conceptually:

```<code>preparedStatement = prepare("insert into mytable (id, name) values (?, ?)")
preparedStatement.setField(0, theId);
preparedStatement.setField(1, theName);
</code>```

Not:

```<code>statement = "insert into mytable (id, name) values ('" + theId + "', '" + theName + "')"
</code>```

...which is asking for injection attacks.

The "prepared statement" concept centralizes escaping to the database link layer, which is well-prepared to handle it. <s>If you tell people what you're using to access your database, they'll be able to point you at the relevant mechanism.</s> See below.

Just for the avoidance of doubt: You're doing this escaping on the server, right? I mean, that's how I read it, you've actually said "I want to sanitize these on the server side...". But just in case you were thinking of doing it client-side: You can't. Nothing, absolutely nothing, that the client-side sends you can be trusted, as it can be faked. You must do this server-side.

Update: You've commented that you're using Rhino in an application server. Excellent! Then just PreparedStatement and let your JDBC driver handle it for you. (For non-Java lurkers: Rhino is JavaScript for the Java VM. It's brilliant.)

ContentLicense: CC BY-SA 2.5

Title: sanitize data for SQL with JavaScript

Body:
I have a bunch of forms that have various input elements. I want to sanitize these on the server side (yes, I'm using server-side JavaScript) to use these inputs as parameters, and prevent special characters to be malformed.

Before you go, like "this belongs not in the realm of JavaScript", etc., etc.

I am using a multi-million licensed software solution, that well has JavaScript but apparently has no standard functions like this out of the box. So, whatever I am using, I can assure you that you probably have never touched it or heard of it. And it supports server side javascript, because well, the language is cool.

My first objective is to sanitize data before it goes in the database, and I just love the way for example how Ruby labels foreign data: tainted. And I rather have no tainted data. So I could google and copy paste some poor regex from here and there, and I got some sad example. However, I would like to have a function that would be said "well, that takes off 70% of the possible stuff from that data and a pretty darn good sanitize".

Basically a string from these elements should be escaped and I assume best practices are already existing for this wish of mine.

function sanitize(myString) { ... ; return myString }

How can I escape symbols like '#!? and other special characters and how i can i get them back in reverse? I am aware of the JavaScript escape method, but I want to know if a function is already debugged and public available before I re-invent the wheel.

I considered:
- JavaScript Escape
- Base64 Encoding
- Regex

I just rather ask the people who have written such functions before.

Thanks,

Body:
See update below

You're reinventing the wheel. Whatever you're using to talk to your database should have some kind of "prepared statement" concept. In Java it's literally the PreparedStatement class, but essentially any database access system should have something similar. You use these so that you're not building up SQL statements as strings. So for instance, conceptually:

preparedStatement = prepare("insert into mytable (id, name) values (?, ?)")
preparedStatement.setField(0, theId);
preparedStatement.setField(1, theName);

Not:

statement = "insert into mytable (id, name) values ('" + theId + "', '" + theName + "')"

...which is asking for injection attacks.

The "prepared statement" concept centralizes escaping to the database link layer, which is well-prepared to handle it. <s>If you tell people what you're using to access your database, they'll be able to point you at the relevant mechanism.</s> See below.

Just for the avoidance of doubt: You're doing this escaping on the server, right? I mean, that's how I read it, you've actually said "I want to sanitize these on the server side...". But just in case you were thinking of doing it client-side: You can't. Nothing, absolutely nothing, that the client-side sends you can be trusted, as it can be faked. You must do this server-side.

Update: You've commented that you're using Rhino in an application server. Excellent! Then just PreparedStatement and let your JDBC driver handle it for you. (For non-Java lurkers: Rhino is JavaScript for the Java VM. It's brilliant.)


答:
try to put obstacle variables into array</p>

```<code>obstacle_item=[obstacle,obstacle2,obstacle3,obstacle4]
test = 0

if any(obstacle_item) is not False:
    #call obstacle detection function
    for item in obstacle_item:
        test = obstacle_detection(obstacle_item,pos)

print test
</code>```

Title: Changing "if" python statement to apply to any obstacle instead of specific obstacles

Body:
try to put obstacle variables into array

obstacle_item=[obstacle,obstacle2,obstacle3,obstacle4]
test = 0

if any(obstacle_item) is not False:
    #call obstacle detection function
    for item in obstacle_item:
        test = obstacle_detection(obstacle_item,pos)

print test


问:
C++ sector aligned read
Im asking this because i am having trouble understanding sector aligned reading when we are reading raw device.

Lets assume whe are in a Windows machined, and we are using the ReadFile() C function to read x bytes from a device.

I know we can only read sector aligned data, but recently i discovered the SetFilePointer() function, that allow us to put a pointer in x bytes of the device we have previously opened with CreateFile().

My question is, if we need to read sector aligned data, if we use SetFilePointer() for example like this:

```<code>SetFilePointer(device, 12, NULL, FILE_BEGIN);
</code>```

(device is a HANDLE to an existing device,for the sake of this example lets assume its a USB pen drive), in that example we set a pointer thatis pointing to the 12th byte starting from FILE_BEGIN.

If i were to read the equivalent of one sector (512 bytes) starting from that 12th byte, would i need to make my read fucntion like this:

```<code>ReadFile(device, sector, (512 - 12), &bytesRead, NULL)
</code>```

or like this:

```<code>ReadFile(device, sector, 512, &bytesRead, NULL)
</code>```

Regardless, thanks!

答:
Well, it depends..

if you want what's in your buffer to represent an entire sector of the device, and map it using a struct* or byte offsets - that's usually how it's done.  then your offsets sent to SetFilePointer should be aligned on the sector size, then read sector sized buffers. So SetFilePointer(0) -> ReadFile(512 bytes)

If you don't care, and just want bytes 12-16, SetFilePointer(12) -> Read(4bytes).

I'd go for solution 1, because it would probably make the code easier to read and maintain in the long run.

Title: C++ sector aligned read

Body:
Im asking this because i am having trouble understanding sector aligned reading when we are reading raw device.

Lets assume whe are in a Windows machined, and we are using the ReadFile() C function to read x bytes from a device.

I know we can only read sector aligned data, but recently i discovered the SetFilePointer() function, that allow us to put a pointer in x bytes of the device we have previously opened with CreateFile().

My question is, if we need to read sector aligned data, if we use SetFilePointer() for example like this:

SetFilePointer(device, 12, NULL, FILE_BEGIN);

(device is a HANDLE to an existing device,for the sake of this example lets assume its a USB pen drive), in that example we set a pointer thatis pointing to the 12th byte starting from FILE_BEGIN.

If i were to read the equivalent of one sector (512 bytes) starting from that 12th byte, would i need to make my read fucntion like this:

ReadFile(device, sector, (512 - 12), &bytesRead, NULL)

or like this:

ReadFile(device, sector, 512, &bytesRead, NULL)

Regardless, thanks!


问:
How to create two triangles with overlaying?
I need to create the following shape on the image. Where is the photo there will variable content as a slider. What I tried so far is create it with border-width, but the problem is that I'm not able to put the small triangle under photo because of the bigger triangle.

What I've done you can find here on live demo. Maybe I have to use other approaches? Does someone how to solve it?

    .header {
  float: left;
  width: 100%;
  background: red;
  padding-top: 50px;
  padding-bottom: 200px; }

  .content {
    float: left;
    width: 100%;
    background: blue;
    padding: 50px 0; }

    .shape {
      position: relative;
      float: left;
      width: 100%; }
      .shape--1:before {
        border-top-color: yellow;
        border-right-color: transparent;
        border-left-color: transparent;
        border-bottom-color: transparent;
        border-style: solid;
        border-width: 160px 330px 0 0;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 30; }
      .shape--2:before {
        background: transparent;
        border-bottom-color: transparent;
        border-left-color: blue;
        border-right-color: transparent;
        border-style: solid;
        border-top-color: transparent;
        border-width: 130px 0 0 100vw;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 20; }

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod? - There will be slider with different background, same color should be also in the shape.
</div>

<div class="shape">
  <div class="shape--1"></div>
  <div class="shape--2"></div>
</div>

<div class="content">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente eos maiores repellendus doloribus dignissimos iusto neque accusantium itaque. Aspernatur, cupiditate ab debitis placeat ad harum, nobis, iste deserunt impedit quaerat dicta nemo accusamus velit mollitia quis quos numquam labore distinctio eveniet. Consequatur culpa dicta harum quo quia similique, numquam tempore.
</div></code>```

答:
I noticed that you have already accepted an answer, but I figured I would still post some code that could help. This would require some fine tuning given what else you may have going on in your project, but it could get the job done.

.LeftT {
  position: absolute;
  top: 0rem;
  left: 0rem;
  border-left: 30rem solid #02A698;
  border-right: 6rem solid transparent;
  border-bottom: 8rem solid transparent;
  border-top: 0rem solid transparent;
}

.RightT {
  position: absolute;
  top: 0rem;
  left: -5rem;
  border-top: 0rem solid #004F49;
  border-left: 0rem solid transparent;
  border-bottom: 8rem solid transparent;
  border-right: 45rem solid #004F49;
}
p{
  position: absolute;
  top: 0rem;
  left: 15rem;
  z-index: 1;
}
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="LeftT"></div>
<div class="RightT"></div>
<p style="color:white;text-align:right;padding-right:1rem;font-size:1.1rem;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in turpis velit.
</p></code>```

Body:
I need to create the following shape on the image. Where is the photo there will variable content as a slider. What I tried so far is create it with border-width, but the problem is that I'm not able to put the small triangle under photo because of the bigger triangle.

What I've done you can find here on live demo. Maybe I have to use other approaches? Does someone how to solve it?

    .header {
  float: left;
  width: 100%;
  background: red;
  padding-top: 50px;
  padding-bottom: 200px; }

  .content {
    float: left;
    width: 100%;
    background: blue;
    padding: 50px 0; }

    .shape {
      position: relative;
      float: left;
      width: 100%; }
      .shape--1:before {
        border-top-color: yellow;
        border-right-color: transparent;
        border-left-color: transparent;
        border-bottom-color: transparent;
        border-style: solid;
        border-width: 160px 330px 0 0;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 30; }
      .shape--2:before {
        background: transparent;
        border-bottom-color: transparent;
        border-left-color: blue;
        border-right-color: transparent;
        border-style: solid;
        border-top-color: transparent;
        border-width: 130px 0 0 100vw;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 20; }

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod? - There will be slider with different background, same color should be also in the shape.

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente eos maiores repellendus doloribus dignissimos iusto neque accusantium itaque. Aspernatur, cupiditate ab debitis placeat ad harum, nobis, iste deserunt impedit quaerat dicta nemo accusamus velit mollitia quis quos numquam labore distinctio eveniet. Consequatur culpa dicta harum quo quia similique, numquam tempore.

Body:
I noticed that you have already accepted an answer, but I figured I would still post some code that could help. This would require some fine tuning given what else you may have going on in your project, but it could get the job done.

.LeftT {
  position: absolute;
  top: 0rem;
  left: 0rem;
  border-left: 30rem solid #02A698;
  border-right: 6rem solid transparent;
  border-bottom: 8rem solid transparent;
  border-top: 0rem solid transparent;
}

.RightT {
  position: absolute;
  top: 0rem;
  left: -5rem;
  border-top: 0rem solid #004F49;
  border-left: 0rem solid transparent;
  border-bottom: 8rem solid transparent;
  border-right: 45rem solid #004F49;
}
p{
  position: absolute;
  top: 0rem;
  left: 15rem;
  z-index: 1;
}

<div class="LeftT"></div>
<div class="RightT"></div>
<p style="color:white;text-align:right;padding-right:1rem;font-size:1.1rem;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in turpis velit.
</p>


问:
Throttling simulator for WebRTC for Windows
Since Throttling in Firefox & Chrome doesn't work with WebRTC yet, i'm looking for other solutions.

Need to make latency worse only for one tab in browser or only for one browser.

Netlimiter 4 would be fine, but they still hasn't latency limiting feautre.

Programs without UI aren't good in my case.

Do you know some?

答:
I know there is an option in Chrome to throttle network traffic in diffrent cellular or Wifi network. Is this not working for you attaching snapenter image description here

You can check under network tab " No throttling " and change option as per your need.


问:
Does anyone use Swagger Codegen or OpenAPI Generator SDKs in Production?
Swagger Code Generator can generate SDKs in many languages (listed below from the Github project page). Does anyone use any of Swagger's auto-generated SDKs in production, both as alpha/beta and as GA, and if so, what organizations and for what languages?

I've done some Google searches and asked around. While I have found many examples of Swagger UI deployed, I haven't found any Code Gen SDKs yet.

Project page: https://github.com/swagger-api/swagger-codegen

Languages:

```<code>$ ls -1 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/
AndroidClientCodegen.java
AsyncScalaClientCodegen.java
CSharpClientCodegen.java
JavaClientCodegen.java
JaxRSServerCodegen.java
NodeJSServerCodegen.java
ObjcClientCodegen.java
PhpClientCodegen.java
PythonClientCodegen.java
RubyClientCodegen.java
ScalaClientCodegen.java
ScalatraServerCodegen.java
SpringMVCServerCodegen.java
StaticDocCodegen.java
StaticHtmlGenerator.java
SwaggerGenerator.java
SwaggerYamlGenerator.java
TizenClientCodegen.java
</code>```

Update - Major Project Official SDK Tracking (Jun 2018)

I'm keeping a track of identifiable official codegen SDKs from larger organizations here to better track adoption. Many organizations that list themselves as using some codegen projects haven't published SDKs on their GitHub accounts.

https://github.com/grokify/api-specs/blob/master/official_codegen_sdks.tsv

Update - Personal Experience (Dec 2017)

I've been actively using Swagger Codegen for Go now (2.2.3 - 2.3.1). So far my experience has been that it does a decent job but variety of hand tweaks can be necessary to get a working SDK so a GitHub package/repo is still nice. You can see some of the issues in the GitHub issues for the SDKs I maintain. I also add post processing to the codegen/swagger_codegen_command.sh files in each repo.

https://github.com/grokify/go-aha

https://github.com/grokify/go-ringcentral

https://github.com/grokify/go-visa

https://github.com/grokify/go-voicebase-v3

Update - Add OpenAPI Generator (Jul 2018)

OpenAPI Generator is a fork of Swagger Codegen so this is now mentioned as well.

答:
I used it to bootstrap our API based on the spring codegen and now use it to change and add the domain models and API endpoints. You still have to change some aspects of the generated classes but it makes refactoring very painless and prevents me from piling on technical debt. Its extremely helpful to have the generated swagger-ui for manual testing and you can import the spec to Postman which generate stubs so you have a nice starting point for and TODO overview for writing your tests.

Haven't used the SDKs yet though. I tried to use the various js clients but they didn't provide any advantage over simple fetch libraries.

I see great potential in codegen for more complex js frameworks like Angular or React + Redux and also test automation.

ContentLicense: CC BY-SA 4.0

Body:
Swagger Code Generator can generate SDKs in many languages (listed below from the Github project page). Does anyone use any of Swagger's auto-generated SDKs in production, both as alpha/beta and as GA, and if so, what organizations and for what languages?

I've done some Google searches and asked around. While I have found many examples of Swagger UI deployed, I haven't found any Code Gen SDKs yet.

Project page: https://github.com/swagger-api/swagger-codegen

Languages:

$ ls -1 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/
AndroidClientCodegen.java
AsyncScalaClientCodegen.java
CSharpClientCodegen.java
JavaClientCodegen.java
JaxRSServerCodegen.java
NodeJSServerCodegen.java
ObjcClientCodegen.java
PhpClientCodegen.java
PythonClientCodegen.java
RubyClientCodegen.java
ScalaClientCodegen.java
ScalatraServerCodegen.java
SpringMVCServerCodegen.java
StaticDocCodegen.java
StaticHtmlGenerator.java
SwaggerGenerator.java
SwaggerYamlGenerator.java
TizenClientCodegen.java

Update - Major Project Official SDK Tracking (Jun 2018)

I'm keeping a track of identifiable official codegen SDKs from larger organizations here to better track adoption. Many organizations that list themselves as using some codegen projects haven't published SDKs on their GitHub accounts.

https://github.com/grokify/api-specs/blob/master/official_codegen_sdks.tsv

Update - Personal Experience (Dec 2017)

I've been actively using Swagger Codegen for Go now (2.2.3 - 2.3.1). So far my experience has been that it does a decent job but variety of hand tweaks can be necessary to get a working SDK so a GitHub package/repo is still nice. You can see some of the issues in the GitHub issues for the SDKs I maintain. I also add post processing to the codegen/swagger_codegen_command.sh files in each repo.

https://github.com/grokify/go-aha

https://github.com/grokify/go-ringcentral

https://github.com/grokify/go-visa

https://github.com/grokify/go-voicebase-v3

Update - Add OpenAPI Generator (Jul 2018)

OpenAPI Generator is a fork of Swagger Codegen so this is now mentioned as well.


问:
Pandas DataFrame correlation on part date
I have a Pandas Data Frame that has a DateTime index over a seven-year horizon and price data for 10 different assets.  I want to run the dataframe.corr function to evaluate relationships between the assets, my problem is I want to run the corr function on a specific month.  So in January of all years what is the correlation?

From what I have been reading if I group by the time I could loose the correct progression of time which would make the correlation analysis useless.

How can I group the data frame by month and maintain the sequence of time?

答:
Use df['month'] = df.index.month to extract the month from the DatetimeIndex. Then groupby month:

```<code>import numpy as np
import pandas as pd
N = 100
index = pd.date_range('2000-1-1', periods=N, freq='B')
df = pd.DataFrame(np.random.random((N,3)), index=index)
df['month'] = df.index.month
result = df.groupby('month').corr()
print(result.head(9))
</code>```

yields a DataFrame whose first few rows looks like this:

```<code>                0         1         2
month
1     0  1.000000 -0.000325 -0.208282
      1 -0.000325  1.000000 -0.236316
      2 -0.208282 -0.236316  1.000000
2     0  1.000000  0.056222 -0.010197
      1  0.056222  1.000000 -0.140247
      2 -0.010197 -0.140247  1.000000
3     0  1.000000 -0.064615 -0.111025
      1 -0.064615  1.000000 -0.100798
      2 -0.111025 -0.100798  1.000000
</code>```

This shows the correlations between the columns of the DataFrame.  Notice that
the index is a MultiIndex whose first level is the month and whose second level
refers to one of the two DataFrame columns associated with the correlation.

The corr method ignores the index -- it treats the two columns of the DataFrame as arrays.
So there is no problem with the grouped data having gaps in time.

Body:
Use df['month'] = df.index.month to extract the month from the DatetimeIndex. Then groupby month:

import numpy as np
import pandas as pd
N = 100
index = pd.date_range('2000-1-1', periods=N, freq='B')
df = pd.DataFrame(np.random.random((N,3)), index=index)
df['month'] = df.index.month
result = df.groupby('month').corr()
print(result.head(9))

yields a DataFrame whose first few rows looks like this:

                0         1         2
month
1     0  1.000000 -0.000325 -0.208282
      1 -0.000325  1.000000 -0.236316
      2 -0.208282 -0.236316  1.000000
2     0  1.000000  0.056222 -0.010197
      1  0.056222  1.000000 -0.140247
      2 -0.010197 -0.140247  1.000000
3     0  1.000000 -0.064615 -0.111025
      1 -0.064615  1.000000 -0.100798
      2 -0.111025 -0.100798  1.000000

This shows the correlations between the columns of the DataFrame.  Notice that
the index is a MultiIndex whose first level is the month and whose second level
refers to one of the two DataFrame columns associated with the correlation.

The corr method ignores the index -- it treats the two columns of the DataFrame as arrays.
So there is no problem with the grouped data having gaps in time.


问:
Can't access Mac server from Xcode
I wanted to create a remote repository in my Mac server. I have installed the app, configured and started the Xcode service as per the Apple docs. But when I try to add the server to my accounts in Xcode, the server name is there, but on adding, it is giving the following error.

Unable to perform the request. CFNetwork error: The network connection
  was lost. (-1005 - kCFURLErrorNetworkConnectionLost)

The server is hosted on the same Mac in which I am developing.

答:
Just do the following steps :

1.Remove your Server from Xcode

2.Quit Xcode

3.Restart/Shutdown machine (If I don't restart/shutdown machine, unable to add server again in my case)

4.Open Xcode

5.Add Server again

This Solution works for me, but its not proper solution. It's headache to repeat the above steps every time while facing same issue, I research more on this but did not get any proper satisfactory  solution.

Title: Can't access Mac server from Xcode


问:
Extract REGEXP Substring SQL Server
I want to extract a specific number value from this query...

Column: name
Four rows for this example:

1/2 Product1 some_description 1200 GR more data... (UND)

1/4 Product2 some_description 2400G more data (KG more data)

Product3 some_description 2200 GRS more data...

1/4 Product4 some_description 1800GR more data UND...

I want the integer value only. I want with the query:

1200

2400

2200

1800

The patterns are:

[0-9]{4} G

[0-9]{4}GR

[0-9]{4} GRS

How can i use this regexp on a SQL Query to parse an attribute value?

SELECT FROM myTable
SUBSTRING(name, (PATINDEX('%[0-9]%', [name])),4) as peso

This extract some values, but not in correct order... I think that i can apply LEFT with length until integer value, but i don't know how resolve it.

答:
You are close.  In SQL Server, the simplest method for your data is:

```<code>select left(name, 4) as peso
from mytable t;
</code>```

That is, the first four characters seem to be what you want.

If the first four characters may not all be digits, then you want to use patindex():

```<code>select left(name, patindex('%[^0-9]%', name + ' ') - 1) as peso
from myTable t;
</code>```

Title: Extract REGEXP Substring SQL Server

Body:
You are close.  In SQL Server, the simplest method for your data is:

select left(name, 4) as peso
from mytable t;

That is, the first four characters seem to be what you want.

If the first four characters may not all be digits, then you want to use patindex():

select left(name, patindex('%[^0-9]%', name + ' ') - 1) as peso
from myTable t;


问:
How does c++ handle 0*(large expression)
Concerning speed, if I need to calculate a large expression, say:

```<code>switch1*(large expression 1)+switch2*(large expression 2)
</code>```

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?

答:
If depends on the exact conditions. CPU, compiler, the exact expressions.

An if can slow down a program, if if becomes a conditional jump in the assembly code, and the condition cannot be predicted.

If the conditional cannot be predicted, and the "large expressions" are actually simple, it may be faster to do the "multiply-way".

However, if the expressions are slow to calculate, or the if can be branch predicted perfectly (or it doesn't compile to a conditional jump), then I think the if way will be faster.

All in all, you should try both solutions, and check which is faster.

Body:
Concerning speed, if I need to calculate a large expression, say:

switch1*(large expression 1)+switch2*(large expression 2)

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?


问:
CassandraPojoSink no error, however data is not getting written into the cassandra
I am trying to write Flink's Cassandra SINK connector using CassandraPojoSink class. I am not getting any error/exception, but No records committed into the Cassandra table.

I am using following code.

========= Sink connector code snapshot ==================

```<code>DataStream<Event> stream = eventStream.flatMap(new EventTransformation());

    try {
        stream.addSink(new CassandraPojoSink<>(Event.class, new ClusterBuilder() {

          private static final long serialVersionUID = -2485105213096858846L;

          @Override
          public Cluster buildCluster(Cluster.Builder builder) {
            return builder.addContactPoint("localhost").withPort(9042).build();
         }
        }));
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

====== POJO CLASS ================

```<code>@Table(keyspace= "cloud", name = "event")
public class Event implements Serializable {

    private static final long serialVersionUID = 3284839826384795926L;

    @Column(name = "name")
    private String name;

    @Column(name = "msg")
        private String msg;

    public Event(){

    }

    //......

}
</code>```

答:
On changing POJO to Tuple, adding timestamp watermarks code is working perfectly.
I am able to see my data is written into the Cassandra database.

DataStream> events = event_stream.flatMap(new EventTransformation()).assignTimestampsAndWatermarks(
                                    new AssignerWithPeriodicWatermarks>() {

```<code>        private static final long serialVersionUID = 1L;
        private final long maxOutOfOrderness = 1_000L; // 1
        // second
        private long currentMaxTimestamp = 0;

        @Override
        public long extractTimestamp(Tuple3<String, String, Long> arg0,
                                            long arg1) {
                long timestamp = arg0.f3; // get
                currentMaxTimestamp = Math.max(timestamp, currentMaxTimestamp);
                return timestamp;
        }

        @Override
        public Watermark getCurrentWatermark() {
            return new Watermark(currentMaxTimestamp - maxOutOfOrderness);
        }
    });

                event_stream.addSink(new CassandraTupleSink<Tuple3<String, String, Long>("INSERT INTO cloud.condition (name, msg, time) VALUES (?,?,?);", new ClusterBuilder() {

                            /**
                             *
                             */
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected Cluster buildCluster(Builder builder) {
                                return builder.addContactPoint("localhost").withPort(9042).build();
                            }
                        }));

                env.setParallelism(2);

                env.execute();
</code>```

Body:
I am trying to write Flink's Cassandra SINK connector using CassandraPojoSink class. I am not getting any error/exception, but No records committed into the Cassandra table.

I am using following code.

========= Sink connector code snapshot ==================

DataStream<Event> stream = eventStream.flatMap(new EventTransformation());

    try {
        stream.addSink(new CassandraPojoSink<>(Event.class, new ClusterBuilder() {

          private static final long serialVersionUID = -2485105213096858846L;

          @Override
          public Cluster buildCluster(Cluster.Builder builder) {
            return builder.addContactPoint("localhost").withPort(9042).build();
         }
        }));
    } catch (Exception e) {
        e.printStackTrace();
    }

====== POJO CLASS ================

@Table(keyspace= "cloud", name = "event")
public class Event implements Serializable {

    private static final long serialVersionUID = 3284839826384795926L;

    @Column(name = "name")
    private String name;

    @Column(name = "msg")
        private String msg;

    public Event(){

    }

    //......

}

Body:
On changing POJO to Tuple, adding timestamp watermarks code is working perfectly.
I am able to see my data is written into the Cassandra database.

DataStream> events = event_stream.flatMap(new EventTransformation()).assignTimestampsAndWatermarks(
                                    new AssignerWithPeriodicWatermarks>() {

        private static final long serialVersionUID = 1L;
        private final long maxOutOfOrderness = 1_000L; // 1
        // second
        private long currentMaxTimestamp = 0;

        @Override
        public long extractTimestamp(Tuple3<String, String, Long> arg0,
                                            long arg1) {
                long timestamp = arg0.f3; // get
                currentMaxTimestamp = Math.max(timestamp, currentMaxTimestamp);
                return timestamp;
        }

        @Override
        public Watermark getCurrentWatermark() {
            return new Watermark(currentMaxTimestamp - maxOutOfOrderness);
        }
    });

                event_stream.addSink(new CassandraTupleSink<Tuple3<String, String, Long>("INSERT INTO cloud.condition (name, msg, time) VALUES (?,?,?);", new ClusterBuilder() {

                            /**
                             *
                             */
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected Cluster buildCluster(Builder builder) {
                                return builder.addContactPoint("localhost").withPort(9042).build();
                            }
                        }));

                env.setParallelism(2);

                env.execute();


问:
Closure tuple does not support destructuring in Xcode 9 Swift 4
After the gloss project for Swift 4 in Xcode 9

I am getting following error which i have no idea

Closure tuple parameter '(key: _, value: _)' does not support
  destructuring

Code:

```<code>extension Dictionary
{
    init(elements: [Element]) {
        self.init()
        for (key, value) in elements {
            self[key] = value
        }
    }

    func flatMap<KeyPrime, ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime:ValuePrime] {
        return Dictionary<KeyPrime, ValuePrime>(elements: try flatMap({ (key, value) in
            return try transform(key, value)
        }))
    }
}
</code>```

Error comes at this point try flatMap({ (key, value)in

答:
Let's start with the definition of flatMap for a dictionary which is the following:

```<code>func flatMap(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
</code>```

You see that the transform closure takes only one parameter of type Element where Element is just a typealias for a tuple:

```<code>public typealias Element = (key: Key, value: Value)
</code>```

So the first and only argument of the closure should be a tuple of two elements (key of type Key and value of type Value).

Now, if you look at your code (which compiles in Swift 3), you will see that this is not the case, and you should be asking why does this even work in Swift 3.

```<code>try flatMap({ (key, value) in
    return try transform(key, value)
})
</code>```

Your closure takes 2 arguments instead of one (key of type Key and value of type Value). This works in Swift 3 thanks to a feature called destructuring where the compiler will automatically transform a tuple of 2 elements into 2 arguments.

<s>But this feature is weird, rarely used and gives unexpected results most of the time so it has been removed in Swift 4.</s>

Edit: As pointed out by OOPer, this feature has been temporarily removed in Swift 4 beta but should be re-added before the final version is out.

Instead you should be writing:

```<code>try flatMap({ tupleArgument in
    return try transform(tupleArgument.key, tupleArgument.value)
})
</code>```

And your flatMap function becomes:

```<code>func flatMap<KeyPrime, ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime:ValuePrime] {
    return Dictionary<KeyPrime, ValuePrime>(elements: try flatMap({ element in
        return try transform(element.key, element.value)
    }))
}
</code>```

Body:
After the gloss project for Swift 4 in Xcode 9

I am getting following error which i have no idea

Closure tuple parameter '(key: _, value: _)' does not support
  destructuring

Code:

extension Dictionary
{
    init(elements: [Element]) {
        self.init()
        for (key, value) in elements {
            self[key] = value
        }
    }

    func flatMap<KeyPrime, ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime:ValuePrime] {
        return Dictionary<KeyPrime, ValuePrime>(elements: try flatMap({ (key, value) in
            return try transform(key, value)
        }))
    }
}

Error comes at this point try flatMap({ (key, value)in

Body:
Let's start with the definition of flatMap for a dictionary which is the following:

func flatMap(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

You see that the transform closure takes only one parameter of type Element where Element is just a typealias for a tuple:

public typealias Element = (key: Key, value: Value)

So the first and only argument of the closure should be a tuple of two elements (key of type Key and value of type Value).

Now, if you look at your code (which compiles in Swift 3), you will see that this is not the case, and you should be asking why does this even work in Swift 3.

try flatMap({ (key, value) in
    return try transform(key, value)
})

Your closure takes 2 arguments instead of one (key of type Key and value of type Value). This works in Swift 3 thanks to a feature called destructuring where the compiler will automatically transform a tuple of 2 elements into 2 arguments.

<s>But this feature is weird, rarely used and gives unexpected results most of the time so it has been removed in Swift 4.</s>

Edit: As pointed out by OOPer, this feature has been temporarily removed in Swift 4 beta but should be re-added before the final version is out.

Instead you should be writing:

try flatMap({ tupleArgument in
    return try transform(tupleArgument.key, tupleArgument.value)
})

And your flatMap function becomes:

func flatMap<KeyPrime, ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime:ValuePrime] {
    return Dictionary<KeyPrime, ValuePrime>(elements: try flatMap({ element in
        return try transform(element.key, element.value)
    }))
}


问:
Lda using mallet
I run the file simple lda.java and I got
 exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at cc.mallet.topics.SimpleLDA.main(SimpleLDA.java:560)

答:
It looks like you are using the command line interface without any parameters.

If you look at the source file at https://github.com/mimno/Mallet/blob/master/src/cc/mallet/topics/SimpleLDA.java, you can see that line 560 is expecting to find that there is a command line argument specifying a file at the first position in the arguments array.

If you need to train a topic model from the command line, there is information here: http://mallet.cs.umass.edu/topics.php

The interface you are using is intended as a base for constructing new, custom topic models in Java. Without significant programming experience in Java this will be frustrating and unlikely to succeed.

Title: Lda using mallet


问:
Do I need to dispose a web service reference in ASP.NET?
Does the garbage collector clean up web service references or do I need to call dispose on the service reference after I'm finished calling whatever method I call?</p>

答:
what are you trying to accomplish here?

If your worried about performance, then I would worry more about the responsiveness of the server hosting the webservice and the network speed, as they can dramatically affect the length of time you have to wait for the webservice call to complete (unless its asynchronous).

The examples on MSDN dont call 'Dispose' and its quite obvious that the garbage collector will do its job, so unless your working on a realtime system that needs to process over 100,000 records in memory every second, then maybe you dont need to come up with a way to dispose resources or manage memory.

OwnerDisplayName: BeaverProj

OwnerDisplayName: Jobo


答:
It's a side-effect of this proposal for Swift 4:

SE-0110 Distinguish between single-tuple and multiple-argument function types.

But some features included in this proposal caused some regression which is addressed in this post of the evolution-announce mailing list:

[swift-evolution-announce] [Core team] Addressing the SE-0110  usability regression in Swift 4

So, you can expect in the future beta or GM version of Xcode 9, your code would compile well again. Until then, you can use this sort of workaround:

```<code>internal func flatMap<KeyPrime , ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime : ValuePrime] {
    return Dictionary<KeyPrime,ValuePrime>(elements: try flatMap({ pair in
        let (key, value) = pair
        return try transform(key, value)
    }))
}
</code>```

By the way, in Swift 4, Dictionary has some new initializers which take Sequence of (Key, Value) pair. For example:

init(uniqueKeysWithValues: S)

Title: Closure tuple does not support destructuring in Xcode 9 Swift 4

Body:
It's a side-effect of this proposal for Swift 4:

SE-0110 Distinguish between single-tuple and multiple-argument function types.

But some features included in this proposal caused some regression which is addressed in this post of the evolution-announce mailing list:

[swift-evolution-announce] [Core team] Addressing the SE-0110  usability regression in Swift 4

So, you can expect in the future beta or GM version of Xcode 9, your code would compile well again. Until then, you can use this sort of workaround:

internal func flatMap<KeyPrime , ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime : ValuePrime] {
    return Dictionary<KeyPrime,ValuePrime>(elements: try flatMap({ pair in
        let (key, value) = pair
        return try transform(key, value)
    }))
}

By the way, in Swift 4, Dictionary has some new initializers which take Sequence of (Key, Value) pair. For example:

init(uniqueKeysWithValues: S)


问:
SQL - Salary difference between 2 months (Variance)
There are 2 separate SQL queries that returning NetPay amount MonthWise. I
want to combine them means i want Variance between 2 months
(Month 2 Amount - Month 1 Amount) as output.</p>

```<code>Query - 1
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

Query - 2
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6
</code>```

答:
You can use Conditional Aggregation to combine those two queries

```<code>Select Sum(case EPS.Month_Id when 6 then EPS.Amount else -EPS.Amount end) as Variance
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id in (6,5)
</code>```

or

```<code>Select Sum(case EPS.Month_Id when 6 then EPS.Amount else 0 end) -
       Sum(case EPS.Month_Id when 5 then EPS.Amount else 0 end)
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id in (6,5)
</code>```

You can replace the months in where clause and Case statement if it is not fixed.

Another approach for using months dynamic

```<code>SELECT Isnull(A.Amount, 0) - Isnull(B.amount, 0)
FROM   (SELECT months,
               Amount = Sum(Amount)
        FROM   #payslips
        GROUP  BY months) a
        INNER JOIN (SELECT months,
                         Amount = Sum(Amount)
                  FROM   #payslips
                  GROUP  BY months) b
              ON a.months = b.months + 1
WHERE  a.months = 6
       AND b.months = 5
</code>```

For newer versions we can use LAG window function

Body:
There are 2 separate SQL queries that returning NetPay amount MonthWise. I
want to combine them means i want Variance between 2 months
(Month 2 Amount - Month 1 Amount) as output.

Query - 1
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

Query - 2
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6

Body:
You can use Conditional Aggregation to combine those two queries

Select Sum(case EPS.Month_Id when 6 then EPS.Amount else -EPS.Amount end) as Variance
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id in (6,5)

or

Select Sum(case EPS.Month_Id when 6 then EPS.Amount else 0 end) -
       Sum(case EPS.Month_Id when 5 then EPS.Amount else 0 end)
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id in (6,5)

You can replace the months in where clause and Case statement if it is not fixed.

Another approach for using months dynamic

SELECT Isnull(A.Amount, 0) - Isnull(B.amount, 0)
FROM   (SELECT months,
               Amount = Sum(Amount)
        FROM   #payslips
        GROUP  BY months) a
        INNER JOIN (SELECT months,
                         Amount = Sum(Amount)
                  FROM   #payslips
                  GROUP  BY months) b
              ON a.months = b.months + 1
WHERE  a.months = 6
       AND b.months = 5

For newer versions we can use LAG window function


问:
Dapper transaction for delegate method
I am using dapper with repository pattern. Below is the code for single repository insert. I need to call 2 or more repositories in service layer with transaction (in savecustomer method). How to apply transaction for the following method?

```<code>Protected void Execute(Action<IDbConnection> query) {
      using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
        {
            query.Invoke(db);
        }
    }
</code>```

And my simplified call site:

```<code>public void SaveCustomer(CustomerDTO custDTO)
{
    Execute(db => db.Execute(saveCustSp, custDTO, CommandType.StoredProcedure));
}
</code>```

答:
If you want to extend your transaction outside the repositories, please consider using UnitOfWork. The detailed code could be found here: https://stackoverflow.com/a/45029588/5779732

With this code, you can span transaction across multiple repositories like below:

```<code>using(DalSession dalSession = new DalSession())
{
    UnitOfWork unitOfWork = dalSession.UnitOfWork;
    unitOfWork.Begin();
    try
    {
        //Your database code here
        repository1.DoThis();
        repository2.DoThat();

        unitOfWork.Commit();
    }
    catch
    {
        unitOfWork.Rollback();
        throw;
    }
}
</code>```

You can also get sample code for generic repository with Dapper here: https://stackoverflow.com/a/45460483/5779732

Title: Dapper transaction for delegate method

Body:
I am using dapper with repository pattern. Below is the code for single repository insert. I need to call 2 or more repositories in service layer with transaction (in savecustomer method). How to apply transaction for the following method?

Protected void Execute(Action<IDbConnection> query) {
      using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
        {
            query.Invoke(db);
        }
    }

And my simplified call site:

public void SaveCustomer(CustomerDTO custDTO)
{
    Execute(db => db.Execute(saveCustSp, custDTO, CommandType.StoredProcedure));
}

Body:
If you want to extend your transaction outside the repositories, please consider using UnitOfWork. The detailed code could be found here: https://stackoverflow.com/a/45029588/5779732

With this code, you can span transaction across multiple repositories like below:

using(DalSession dalSession = new DalSession())
{
    UnitOfWork unitOfWork = dalSession.UnitOfWork;
    unitOfWork.Begin();
    try
    {
        //Your database code here
        repository1.DoThis();
        repository2.DoThat();

        unitOfWork.Commit();
    }
    catch
    {
        unitOfWork.Rollback();
        throw;
    }
}

You can also get sample code for generic repository with Dapper here: https://stackoverflow.com/a/45460483/5779732


问:
Avoiding a div's background image to go under the navbar in Bootstrap when the viewport is shrinked
In the blog I am currently designing there is a div right below the navbar with a background image. The image goes under the navbar when the viewport is scaled to 768 px or less. How can I avoid it to go under it?

The other problem is that, the text on that background image is currently centered, but when scaled it moves away. How can I solve that?

The code: https://codepen.io/anon/pen/JJBpax

HTML:

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>SINEMACERA</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>

<!--NAVBAR STARTS-->

<nav class="navbar navbar-default navbar-fixed-top">

    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">SINEMACERA</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">

        <li class="active"><a href="#">Anasayfa</a></li>

      </ul>

      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Hakkımda</a></li>
        <li><a href="#">İletişim</a></li>

      </ul>
    </div><!-- /.navbar-collapse -->
</nav>

<!--NAVBAR ENDS-->

<div id="COVERPHOTO"><div id="COVER">SİNEMACERA</div></div>

<div class="container-fluid">
    <div class="row">
    <div id="MAJORCONTENT">

        <div class="col-lg-12">
<h1>Lorem Ipsum Üzerine</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<span class="readmore">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</span>
<button type="button" class="btn btn-primary">Devamını oku!</button>
</div>

        <div class="col-lg-12">
<h1>Lorem Ipsum Üzerine</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<span class="readmore">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</span>
<button type="button" class="btn btn-primary">Devamını oku!</button>
</div>

<div class="col-lg-12">
<h1>Lorem Ipsum Üzerine</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<span class="readmore">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</span>
<button type="button" class="btn btn-primary">Devamını oku!</button>
</div>

</div>
    </div>
</div>

<script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>

<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="sinemacera.js"></script>
</body>
</html>
</code>```

CSS:

```<code>body {
    background: black;
    color:white;
}

button {
    width:100%;
}

h1 {

    text-align: center;
    text-shadow: 0px 4px 3px rgba(255, 255, 255, 0.4),
             0px 8px 13px rgba(255, 255, 255, 0.1),
             0px 18px 23px rgba(255, 255, 255,0.1)

}

.col-lg-6 {
    margin-top:10px;
}

.row {
    float:left;
}

.readmore {
    display:none;
}

#COVERPHOTO {
background:linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0.7),
      rgba(0, 0, 0, 0),
      rgba(0, 0, 0, 0.7)
    ),
url("http://cdn.highdefdigest.com/uploads/2014/12/02/Dolce_Vita_Marcello_Mastroianni.jpg");
background-size: cover;
background-position: 50% 20%;
margin-top: 50px;
padding-top: 10%;
padding-bottom: 10%;

}

#COVER {
    position: relative;
    font-size: 40px;
    text-align: center;
}
#MAJORCONTENT {
text-align: justify;
}
</code>```

JS:

```<code>$(".btn-primary").click(function() {

var thisBTN = $(this);
var RM = $(this).prev();

RM.slideToggle(1000, function() {
    thisBTN.toggleClass("btn-info")
    if(thisBTN.text()==="Küçült") {
        thisBTN.text("Devamını oku");
    }
    else {
        thisBTN.text("Küçült")
    }
});
});
</code>```

答:
This is what is causing the issue.

```<code>button {
    width:100%;
}
</code>```

It is not good practice to apply CSS to HTML tags as it can cause unintended output like what happened here (The button in the navbar was also inheriting width: 100%). So apply CSS through classes or IDs.

Solution :
https://codepen.io/anon/pen/RgBQzr

I have defined a class called wide-button and added that class to buttons which you want to have width:100%.

As for the text not being centered, it is also not happening in this code-pen.

Body:
In the blog I am currently designing there is a div right below the navbar with a background image. The image goes under the navbar when the viewport is scaled to 768 px or less. How can I avoid it to go under it?

The other problem is that, the text on that background image is currently centered, but when scaled it moves away. How can I solve that?

The code: https://codepen.io/anon/pen/JJBpax

HTML:

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>SINEMACERA</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="styles.css">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      SINEMACERA

Anasayfa

Hakkımda

İletişim

SİNEMACERA

Lorem Ipsum Üzerine

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<button type="button" class="btn btn-primary">Devamını oku!</button>

Lorem Ipsum Üzerine

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<button type="button" class="btn btn-primary">Devamını oku!</button>

Lorem Ipsum Üzerine

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<button type="button" class="btn btn-primary">Devamını oku!</button>

CSS:

body {
    background: black;
    color:white;
}

button {
    width:100%;
}

h1 {

    text-align: center;
    text-shadow: 0px 4px 3px rgba(255, 255, 255, 0.4),
             0px 8px 13px rgba(255, 255, 255, 0.1),
             0px 18px 23px rgba(255, 255, 255,0.1)

}

.col-lg-6 {
    margin-top:10px;
}

.row {
    float:left;
}

.readmore {
    display:none;
}

#COVERPHOTO {
background:linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0.7),
      rgba(0, 0, 0, 0),
      rgba(0, 0, 0, 0.7)
    ),
url("http://cdn.highdefdigest.com/uploads/2014/12/02/Dolce_Vita_Marcello_Mastroianni.jpg");
background-size: cover;
background-position: 50% 20%;
margin-top: 50px;
padding-top: 10%;
padding-bottom: 10%;

}

#COVER {
    position: relative;
    font-size: 40px;
    text-align: center;
}
#MAJORCONTENT {
text-align: justify;
}

JS:

$(".btn-primary").click(function() {

var thisBTN = $(this);
var RM = $(this).prev();

RM.slideToggle(1000, function() {
    thisBTN.toggleClass("btn-info")
    if(thisBTN.text()==="Küçült") {
        thisBTN.text("Devamını oku");
    }
    else {
        thisBTN.text("Küçült")
    }
});
});

Body:
This is what is causing the issue.

button {
    width:100%;
}

It is not good practice to apply CSS to HTML tags as it can cause unintended output like what happened here (The button in the navbar was also inheriting width: 100%). So apply CSS through classes or IDs.

Solution :
https://codepen.io/anon/pen/RgBQzr

I have defined a class called wide-button and added that class to buttons which you want to have width:100%.

As for the text not being centered, it is also not happening in this code-pen.


答:
In Zeppelin you can use z.show(df) to show a pretty table. Here's an example:

```<code>val df = Seq(
  (1,1,1), (2,2,2), (3,3,3)
).toDF("first_column", "second_column", "third_column")

z.show(df)
</code>```

Title: How can I pretty print a data frame in Zeppelin/Spark/Scala?

Body:
I am using Spark 2 and Scala 2.11 in a Zeppelin 0.7 notebook. I have a dataframe that I can print like this:

dfLemma.select("text", "lemma").show(20,false)

and the output looks like:

+---------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|text                                                                                |lemma                                                                                |
+---------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|RT @Dope_Promo: When you and your crew beat your high scores on FUGLY FROG  https://time.com/Sxp3Onz1w8                    |[rt, @dope_promo, :, when, you, and, you, crew, beat, you, high, score, on, FUGLY, FROG, https://time.com/sxp3onz1w8]                                                      |
|RT @axolROSE: Did yall just call Kermit the frog a lizard?  https://time.com/wDAEAEr1Ay                                        |[rt, @axolrose, :, do, yall, just, call, Kermit, the, frog, a, lizard, ?, https://time.com/wdaeaer1ay]                                                                     |

I am trying to make the output nicer in Zeppelin, by:

val printcols= dfLemma.select("text", "lemma")
println("%table " + printcols)

which gives this output:

printcols: org.apache.spark.sql.DataFrame = [text: string, lemma: array<string>]

and a new blank Zeppelin paragraph headed

[text: string, lemma: array]

Is there a way of getting the dataframe to show as a nicely formatted table?
TIA!

Body:
In Zeppelin you can use z.show(df) to show a pretty table. Here's an example:

val df = Seq(
  (1,1,1), (2,2,2), (3,3,3)
).toDF("first_column", "second_column", "third_column")

z.show(df)


问:
How to create instance of an object?
I am using Json.Net library to convert objects to json and back to objects.

I have an interface:

```<code>public interface IGoods
{
    List<IPen> Pens { get; set; }
    List<IPencil> Pencils{ get; set; }
    void Deserialize(String json);

}
</code>```

implementation:

```<code>new public void Deserialize(String json)
    {
        JsonConvert.DeserializeObject<Goods>(json);
    }
</code>```

The obvious error I got is: Could not create an instance of type Project.IPen. Type is an interface or abstract class and cannot be instantated.

How do I overcome this error?

Thanks!

答: See Using Json.NET converters to deserialize properties</p>

Title: How to create instance of an object?

Body:
I am using Json.Net library to convert objects to json and back to objects.

I have an interface:

public interface IGoods
{
    List<IPen> Pens { get; set; }
    List<IPencil> Pencils{ get; set; }
    void Deserialize(String json);

}

implementation:

new public void Deserialize(String json)
    {
        JsonConvert.DeserializeObject<Goods>(json);
    }

The obvious error I got is: Could not create an instance of type Project.IPen. Type is an interface or abstract class and cannot be instantated.

How do I overcome this error?

Thanks!


问:
Selenium Basic HTTP Authentication popup
Is there any way to handle basic http authentication popup?
There are several ancient answers that you can provide authentication using https://username:password@www.example.com/ url pattern, but as mentioned here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
this is deprecated and do not work anymore.

Can't handle it with webdriver Alert API (because this is browser alert not js), getting

selenium.common.exceptions.NoAlertPresentException: Message: no alert open

Chrome driver revision: 2.29.461571

答:
Yes, this issue can be resolved by doing some settings in IE.
You can follow below steps -

Open IE browser

Open the site, you want to automate in IE.

Enter your credentials to login to your site

Once your are logged in, Go to -
        Tools -> Internet Options -> Security -> Trusted sites

Click on Sites

Add your site url under websites and close it.

Click on Custom level

Under User Authentication, select "Automatic logon with current user name and password"

Click "OK"

Now you can execute your script in any browser like chrome and it will not ask for the credentials for this particular site.

Hope, this will be helpful for you.


问:
Is there any way to adjust column width in md-data-table?
I was working on an example for md-datatable found on Git Hub It worked well but when I tried to adjust thw column size as it consumes extra space in table th styling codes where overirdden by md-data-table.min.css file. Please help me to reduce the spacing between columns of table.

答:
Have a look at the less file https://github.com/daniel-nagy/md-data-table/blob/master/app/styles/app.less and try to alter everything under following selector (line 41):</p>

```<code>md-toolbar.md-table-toolbar.alternate {
  color: #1e88e5;
  background-color: #e3f2fd;

  .md-toolbar-tools {
    font-size: 16px;
  }
}
</code>```

Body:
Have a look at the less file https://github.com/daniel-nagy/md-data-table/blob/master/app/styles/app.less and try to alter everything under following selector (line 41):

md-toolbar.md-table-toolbar.alternate {
  color: #1e88e5;
  background-color: #e3f2fd;

  .md-toolbar-tools {
    font-size: 16px;
  }
}


问:
C++ sector aligned read
Im asking this because i am having trouble understanding sector aligned reading when we are reading raw device.

Lets assume whe are in a Windows machined, and we are using the ReadFile() C function to read x bytes from a device.

I know we can only read sector aligned data, but recently i discovered the SetFilePointer() function, that allow us to put a pointer in x bytes of the device we have previously opened with CreateFile().

My question is, if we need to read sector aligned data, if we use SetFilePointer() for example like this:

```<code>SetFilePointer(device, 12, NULL, FILE_BEGIN);
</code>```

(device is a HANDLE to an existing device,for the sake of this example lets assume its a USB pen drive), in that example we set a pointer thatis pointing to the 12th byte starting from FILE_BEGIN.

If i were to read the equivalent of one sector (512 bytes) starting from that 12th byte, would i need to make my read fucntion like this:

```<code>ReadFile(device, sector, (512 - 12), &bytesRead, NULL)
</code>```

or like this:

```<code>ReadFile(device, sector, 512, &bytesRead, NULL)
</code>```

Regardless, thanks!

答:
My question is, if we need to read sector aligned data, if we use SetFilePointer() for example like this:

```<code>SetFilePointer(device, 12, NULL, FILE_BEGIN);
</code>```

... then you are no longer reading sector-aligned data, and you'll get error 87 in the ReadFile call. Reading sector-aligned data doesn't just mean that you have to read in sector-sized blocks, but you must always read blocks that start on sector boundaries.

You have to seek to the sector containing the bytes of your interest (so, position/sector_size*sector_size), read the whole sector and extract the bytes of your interest from the data you read.

Title: C++ sector aligned read

Body:
Im asking this because i am having trouble understanding sector aligned reading when we are reading raw device.

Lets assume whe are in a Windows machined, and we are using the ReadFile() C function to read x bytes from a device.

I know we can only read sector aligned data, but recently i discovered the SetFilePointer() function, that allow us to put a pointer in x bytes of the device we have previously opened with CreateFile().

My question is, if we need to read sector aligned data, if we use SetFilePointer() for example like this:

SetFilePointer(device, 12, NULL, FILE_BEGIN);

(device is a HANDLE to an existing device,for the sake of this example lets assume its a USB pen drive), in that example we set a pointer thatis pointing to the 12th byte starting from FILE_BEGIN.

If i were to read the equivalent of one sector (512 bytes) starting from that 12th byte, would i need to make my read fucntion like this:

ReadFile(device, sector, (512 - 12), &bytesRead, NULL)

or like this:

ReadFile(device, sector, 512, &bytesRead, NULL)

Regardless, thanks!

Body:
My question is, if we need to read sector aligned data, if we use SetFilePointer() for example like this:

SetFilePointer(device, 12, NULL, FILE_BEGIN);

... then you are no longer reading sector-aligned data, and you'll get error 87 in the ReadFile call. Reading sector-aligned data doesn't just mean that you have to read in sector-sized blocks, but you must always read blocks that start on sector boundaries.

You have to seek to the sector containing the bytes of your interest (so, position/sector_size*sector_size), read the whole sector and extract the bytes of your interest from the data you read.


问:
DocuSign SDK Assembly Dependency Versions
I am integrating the DocuSign SDK into my application (from the github page here: https://github.com/docusign/docusign-csharp-client) and can see it has two dependencies:
- Netwtonsoft.JSON
- RestSharp

However, it seems the included dependency assemblies are not the same versions that were used to create the DocuSign SDK assembly.
The included NewtonSoft.JSON assembly is v8, but the SDK uses v7.
The included RestSharp assembly is 105.2.3, but the SDK uses v105.1.0.0

Is it possible to get an updated SDK with the correct dependencies?

答:
Thank you for the links, it appears the SDK I downloaded from GitHub was perhaps an older version.

Installing the NuGet package worked a charm.


问:
How to receive time format changed 12 to 24 vice versa from native device settings?
I have a requirement to update the current time in my application as per device time format(12/24). I need any callback/listeners/receivers which will let me know that time format has been changed so that i can update time in my application accordingly.

I got the way to get current timeformat using below code snippet

```<code>String value = android.provider.Settings.System.getString(this.getContentResolver(), android.provider.Settings.System.TIME_12_24);
</code>```

But looking for any callback which will let me know the same in run time.

Thanks in advance.

答:
android.text.format.DateFormat.is24HourFormat(Context context);
  Use this function to get the time format.
  Register a Broadcast receiver which listens to ACTION_TIMEZONE_CHANGED,ACTION_TIME_CHANGED,ACTION_TIME_TICK.

Something like this,

```<code>IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(Intent.ACTION_TIME_TICK);
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
registerReceiver(youReciverHere,intentFilter);
</code>```

Do work on the receiver s onReceive() function.

Body:
I have a requirement to update the current time in my application as per device time format(12/24). I need any callback/listeners/receivers which will let me know that time format has been changed so that i can update time in my application accordingly.

I got the way to get current timeformat using below code snippet

String value = android.provider.Settings.System.getString(this.getContentResolver(), android.provider.Settings.System.TIME_12_24);

But looking for any callback which will let me know the same in run time.

Thanks in advance.

Body:
android.text.format.DateFormat.is24HourFormat(Context context);
  Use this function to get the time format.
  Register a Broadcast receiver which listens to ACTION_TIMEZONE_CHANGED,ACTION_TIME_CHANGED,ACTION_TIME_TICK.

Something like this,

IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(Intent.ACTION_TIME_TICK);
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
registerReceiver(youReciverHere,intentFilter);

Do work on the receiver s onReceive() function.