问:
How can I combine two object in one of the object in RxJava?
I have Data and DataDetail classes, each of them contains data that neighter of them
don’t contain.
I have List class which I fetch from backend,
having Data which has id field  I can request DataDetail, and DataDetail have some info which in Data object are null, so I can get from DataDetail and set in Data class .

```<code>`fetchData()
.toFlowable()
.flatMapIterable(datas->datas).map(new Function<Data, Flowable<DataDetail>>() {
@Override
 public Flowable<DataDetail>`apply(@io.reactivex.annotations.NonNull Data data) throws Exception {
return

</code>```

fetchDataDetail(data()).toFlowable();
  }
})
.map(new Function<DataDetail, Flowable<Data>>() {

@Override

public Flowable<DataDetail> apply(@io.reactivex.annotations.NonNull DataDetail dataDetail) throws Exception {

return //I want to have access data and dataDetail object   }
})
.toList();

.map() ? in map as argument I get DataDetail  object which is Flowable,
Flowable  but I need to have access both Data and DataDetail  to get some data from DataDetail and set in Data object

答:
I believe that this is what your api is returning.

```<code>api.getList() // this returns a Single<List<Data>>
</code>```

If that is correct may be this is what you are trying to achieve.

```<code>Single<List<Pair<Data,Detail>>> dataSingle = api.getList()
    .toFlowable()
    .flatMap(Flowable::fromIterable) // Convert the list to single emissions
    .flatMap(data -> {
            // Make api call to get details
            return api.getDetails(data.getId())
                .flatMap(dataDetails -> {
                    return Flowable.just(Pair.create(data,dataDetail));
                });
        }).toList();
</code>```

And obviously if you need to convert that to Flowable , you can easily do that with toFlowable.

The Pair is from android.support.v4.util.Pair. Ideally you create a separate model to represent the data from data and detail instead. But as a quick hack you can use Pair

Hope it helps.

Body:
I have Data and DataDetail classes, each of them contains data that neighter of them
don’t contain.
I have List class which I fetch from backend,
having Data which has id field  I can request DataDetail, and DataDetail have some info which in Data object are null, so I can get from DataDetail and set in Data class .

`fetchData()
.toFlowable()
.flatMapIterable(datas->datas).map(new Function<Data, Flowable<DataDetail>>() {
@Override
 public Flowable<DataDetail>`apply(@io.reactivex.annotations.NonNull Data data) throws Exception {
return

fetchDataDetail(data()).toFlowable();
  }
})
.map(new Function<DataDetail, Flowable<Data>>() {

@Override

public Flowable<DataDetail> apply(@io.reactivex.annotations.NonNull DataDetail dataDetail) throws Exception {

return //I want to have access data and dataDetail object   }
})
.toList();

.map() ? in map as argument I get DataDetail  object which is Flowable,
Flowable  but I need to have access both Data and DataDetail  to get some data from DataDetail and set in Data object

Body:
I believe that this is what your api is returning.

api.getList() // this returns a Single<List<Data>>

If that is correct may be this is what you are trying to achieve.

Single<List<Pair<Data,Detail>>> dataSingle = api.getList()
    .toFlowable()
    .flatMap(Flowable::fromIterable) // Convert the list to single emissions
    .flatMap(data -> {
            // Make api call to get details
            return api.getDetails(data.getId())
                .flatMap(dataDetails -> {
                    return Flowable.just(Pair.create(data,dataDetail));
                });
        }).toList();

And obviously if you need to convert that to Flowable , you can easily do that with toFlowable.

The Pair is from android.support.v4.util.Pair. Ideally you create a separate model to represent the data from data and detail instead. But as a quick hack you can use Pair

Hope it helps.


来源: stackexchange

问:
Migrating portlets to Spring MVC
I have been assigned to restructure an existing portlet application which is based on jboss portal & spring portlets to spring web mvc. Has anyone faced with this situation before? I did find several post on going from web mvc to portlets though but nothing on portlets to web mvc.

Is there a cleaner approach on handling this migration? Is it even possible without involving a huge re-writing of code? The portlets looks simple and does not seems to have too many methods or complex code. I would appreciate any directions or pointers on this.

How to handle the actionRequest and RenderRequest method conversion? Would there be two methods which would be GET and POST or can it be handled in just one method?

Thanks

答:
I am posting my answer based on the research that I have done so far. There is no set of rules for this conversion but the basic start point would be to change the portlets classes to servlets or controller. Removing the portal/portlet dependency from the java classes and jsp one by one.
Spring mvc servlets provide similar functionality to the spring mvc portlets so the back end conversion is not that tough, changing the jsp can be little bothersome but using the jstl, spring tags , these can be converted easily. I creates some include jsp and scripts to carry the common styling,javascripts,css etc which portal used to insert. So far, I have changed a major portion of the project and it seems to be working.</p>

ContentLicense: CC BY-SA 3.0

Title: Migrating portlets to Spring MVC


问:
Managing multiple solutions with NDepend
Suppose you have two Visual Studio solutions, each of which builds three assemblies - for example:

SolutionA: A1.dll, A2.dll, A3.dll.

SolutionB: B1.dll, B2.dll, B3.dll.

Further, suppose that you have created two corresponding NDepend projects - NDependA and NDependB.

I have two questions to this scenario:

No. 1: Is there an easy way to create a third, combined NDepend project ("NDependAB")?

No. 2: If you add something like A4.dll to SolutionA, do you have to update both NDependA and NDependAB, or is there a way to update NDependAB "automatically"?

答:
1) Just create a new NDepend project and add assemblies of the 2 solutions. This is possible thanks to the link label on the start page: Analyze : VS solutions and VS projects

2) No, there is no out-of-the-box way to update the NDepend project from the solution change. This is something we are thinking for the future.

ContentLicense: CC BY-SA 2.5


问:
Importing external js library in Vue.js Single File Component
I have the following Single File Component in Vue.js.

The plasmid tag is meant to get rendered by the angularplasmid.complete.min.js file but isn't for some reason. Is this the correct way to import a library in a component?

I am restructuring an old Vue project to be better designed but I know that the plasmid tag renders on here (which doesn't use single file components): https://github.com/asselinpaul/dnaviewer/blob/master/app/index.html

Any help much appreciated.

```<code><template>
<div id="DNA Plasmid">
    <h3>Plasmid Visualisation</h3>
    <div class="section">
        <plasmid id='p1' plasmidheight="800" plasmidwidth="800" v-bind:sequencelength="sequenceLength">
            <plasmidtrack id='t1' radius="200" width="55">
                <trackmarker v-for="(bound, index) in bounds" class='marker' v-bind:start="bound.start" v-bind:end="bound.end" v-bind:style="{ fill: bound.color }" v-bind:key="bound.start">
                    <markerlabel v-bind:text="bound.name" v-bind:vadjust='bound.vadjust' style='font-size:12px'></markerlabel>
                </trackmarker>
                <tracklabel v-bind:text="name" style='font-size:25px;font-weight:bold'></tracklabel>
            </plasmidtrack>
        </plasmid>
    </div>
</div>

</template>

<script>
import './angularplasmid.complete.min.js'

...
</code>```

答:
Solved by requiring the file when my component is mounted:</p>

```<code>mounted: function(){
    require('./angularplasmid.complete.min.js')
  }
</code>```

Body:
I have the following Single File Component in Vue.js.

The plasmid tag is meant to get rendered by the angularplasmid.complete.min.js file but isn't for some reason. Is this the correct way to import a library in a component?

I am restructuring an old Vue project to be better designed but I know that the plasmid tag renders on here (which doesn't use single file components): https://github.com/asselinpaul/dnaviewer/blob/master/app/index.html

Any help much appreciated.

<template>

Plasmid Visualisation

        <plasmid id='p1' plasmidheight="800" plasmidwidth="800" v-bind:sequencelength="sequenceLength">
            <plasmidtrack id='t1' radius="200" width="55">
                <trackmarker v-for="(bound, index) in bounds" class='marker' v-bind:start="bound.start" v-bind:end="bound.end" v-bind:style="{ fill: bound.color }" v-bind:key="bound.start">
                    <markerlabel v-bind:text="bound.name" v-bind:vadjust='bound.vadjust' style='font-size:12px'></markerlabel>
                </trackmarker>
                <tracklabel v-bind:text="name" style='font-size:25px;font-weight:bold'></tracklabel>
            </plasmidtrack>
        </plasmid>

</template>

Body:
Solved by requiring the file when my component is mounted:

mounted: function(){
    require('./angularplasmid.complete.min.js')
  }


问:
MATLAB: How to count number frequency columnwise, in continuous blocks
I have a matrix a in Matlab that looks like the following:

```<code>a = zeros(10,3);
a(3:6,1)=2; a(5:9,3)=1; a(5:7,2)=3; a(8:10,1)=2;

a =
 0     0     0
 0     0     0
 2     0     0
 2     0     0
 2     3     1
 2     3     1
 0     3     1
 2     0     1
 2     0     1
 2     0     0
</code>```

I would like to obtain a cell array with the number of times that each number appears in a column. Also, it should be ordered depending on the element value, regardless of the column number. In the example above I would like to obtain the cell:

```<code>b = {[5],[4,3],[3]}
</code>```

Because the number 1 appears once for 5 times, the number 2 twice in blocks of 4 and 3, and the number 3 once for 3 times. As you can see the recurrences are ordered according to the element value and not to the number of the column where the elements appear.

答:
Since you're not concerned with the column, you can string all the columns into a single column vector, padding with zeroes on either end to prevent spans at the start and end of columns from running together:

```<code>v = reshape(padarray(a, [1 0]), [], 1);
% Or if you don't have the Image Processing Toolbox function padarray...
v = reshape([zeros(1, size(a, 2)); a; zeros(1, size(a, 2))], [], 1);
</code>```

Now, assuming spans are always separated by 1 or more zeroes, you can find the length of each span as follows:

```<code>endPoints = find(diff(v) ~= 0);  % Find where transitions to or from 0 occur
spans = endPoints(2:2:end)-endPoints(1:2:end); % Index of transitions to 0 minus
                                               % index of transitions from 0
</code>```

And finally you can accumulate the spans based on the value present in those spans:

```<code>b = accumarray(v(endPoints(1:2:end)+1), spans, [], @(v) {v(:).'}).';
</code>```

And for your example:

```<code>b =

  1×3 cell array

    [5]    [1×2 double]    [3]
</code>```

Note:

The ordering of values in the resulting cell array is not guaranteed to match the order in spans (i.e. b{2} above is [3 4] instead of [4 3]). If order matters, you'll need to sort your subscripts as per this section of the documentation. Here's how you would change the computation of b:

```<code>[vals, index] = sort(v(endPoints(1:2:end)+1));
b = accumarray(vals, spans(index), [], @(v) {v(:).'}).';
</code>```

Body:
I have a matrix a in Matlab that looks like the following:

a = zeros(10,3);
a(3:6,1)=2; a(5:9,3)=1; a(5:7,2)=3; a(8:10,1)=2;

a =
 0     0     0
 0     0     0
 2     0     0
 2     0     0
 2     3     1
 2     3     1
 0     3     1
 2     0     1
 2     0     1
 2     0     0

I would like to obtain a cell array with the number of times that each number appears in a column. Also, it should be ordered depending on the element value, regardless of the column number. In the example above I would like to obtain the cell:

b = {[5],[4,3],[3]}

Because the number 1 appears once for 5 times, the number 2 twice in blocks of 4 and 3, and the number 3 once for 3 times. As you can see the recurrences are ordered according to the element value and not to the number of the column where the elements appear.

Body:
Since you're not concerned with the column, you can string all the columns into a single column vector, padding with zeroes on either end to prevent spans at the start and end of columns from running together:

v = reshape(padarray(a, [1 0]), [], 1);
% Or if you don't have the Image Processing Toolbox function padarray...
v = reshape([zeros(1, size(a, 2)); a; zeros(1, size(a, 2))], [], 1);

Now, assuming spans are always separated by 1 or more zeroes, you can find the length of each span as follows:

endPoints = find(diff(v) ~= 0);  % Find where transitions to or from 0 occur
spans = endPoints(2:2:end)-endPoints(1:2:end); % Index of transitions to 0 minus
                                               % index of transitions from 0

And finally you can accumulate the spans based on the value present in those spans:

b = accumarray(v(endPoints(1:2:end)+1), spans, [], @(v) {v(:).'}).';

And for your example:

b =

  1×3 cell array

    [5]    [1×2 double]    [3]

Note:

The ordering of values in the resulting cell array is not guaranteed to match the order in spans (i.e. b{2} above is [3 4] instead of [4 3]). If order matters, you'll need to sort your subscripts as per this section of the documentation. Here's how you would change the computation of b:

[vals, index] = sort(v(endPoints(1:2:end)+1));
b = accumarray(vals, spans(index), [], @(v) {v(:).'}).';


问:
Cross-Origin Request Blocked in Angular2
I am new to Angular2.  I have created a service in my local machine in WCF and runs it.  A simple method is created that returns a string, codes is shown below.

```<code>    public string JSONData(string id)
    {
        return "You requested product is " + id;
    }
</code>```

Now I want to access that service in my Angular2 app in my service.ts file.  Code in accessing the service method is shown below:

```<code>   testService(){
        return this._http.get('http://localhost:49753/RestServiceImpl.svc/json/4')
        .map(res => res.json())
        .do(data => console.log("Testing service" + JSON.stringify(data)))
        .catch(this.handleError);
    }
</code>```

But when I run the codes, I got the error below:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http...."

Is there a way to call my WCF service without hosting my service in other machine?

答:
You are getting this problem as header which you are sending is not matched with the headers in backend

So let suppose In frontend you sending headers

```<code>contentHeaders = new Headers();
contentHeaders.append('Authorization', 'Basic YW5ndWxhci13YXJlaG91c2Utc2VydmljZXM6MTIzNDU2');
contentHeaders.append('Content-Type', 'application/json');
contentHeaders.append('Access-Control-Allow-Origin', '*');
</code>```

So those headers like 'Authorization','Content-type', 'Access-Control-Allow-Origin' should matched with your header allow in backend.

So in backend 'Access-Control-Allow-Headers' should have all above headers
see below

```<code>res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization,content-type,Access-Control-Allow-Origin");
</code>```

So here in Access-Control-Allow-Headers you have to passed all headers which you send from frontend : 'Authorization','Content-type', 'Access-Control-Allow-Origin'.

It will work perfectly when you use above concept.

Body:
I am new to Angular2.  I have created a service in my local machine in WCF and runs it.  A simple method is created that returns a string, codes is shown below.

    public string JSONData(string id)
    {
        return "You requested product is " + id;
    }

Now I want to access that service in my Angular2 app in my service.ts file.  Code in accessing the service method is shown below:

   testService(){
        return this._http.get('http://localhost:49753/RestServiceImpl.svc/json/4')
        .map(res => res.json())
        .do(data => console.log("Testing service" + JSON.stringify(data)))
        .catch(this.handleError);
    }

But when I run the codes, I got the error below:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http...."

Is there a way to call my WCF service without hosting my service in other machine?

Body:
You are getting this problem as header which you are sending is not matched with the headers in backend

So let suppose In frontend you sending headers

contentHeaders = new Headers();
contentHeaders.append('Authorization', 'Basic YW5ndWxhci13YXJlaG91c2Utc2VydmljZXM6MTIzNDU2');
contentHeaders.append('Content-Type', 'application/json');
contentHeaders.append('Access-Control-Allow-Origin', '*');

So those headers like 'Authorization','Content-type', 'Access-Control-Allow-Origin' should matched with your header allow in backend.

So in backend 'Access-Control-Allow-Headers' should have all above headers
see below

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization,content-type,Access-Control-Allow-Origin");

So here in Access-Control-Allow-Headers you have to passed all headers which you send from frontend : 'Authorization','Content-type', 'Access-Control-Allow-Origin'.

It will work perfectly when you use above concept.


问:
Is it possible to import types from module declaration?
For example, if I have a module declaration:

```<code>declare module 'redux-form' {
  declare type FormConfig = {
    form: string,
    validate?: Function
  };
}
</code>```

Is it possible to somehow use this type in my code?

And if not, what are the ways to share types between several files?

答: Yes, you just need to do import type {FormConfig} from 'redux-form';

Body:
For example, if I have a module declaration:

declare module 'redux-form' {
  declare type FormConfig = {
    form: string,
    validate?: Function
  };
}

Is it possible to somehow use this type in my code?

And if not, what are the ways to share types between several files?


问:
java 7 to java 8 migration spring bean creation exception
I am migrating Java 7 to Java 8 , and trying to continue with Spring 3.2. When try to run the application, throwing spring bean creation errors. Error creating bean with name 'something': cannot create inner bean ...etc.

I dont see any application related issues, Is Spring 3.2 compatible for Java8?
Or else should I upgrade Spring 4.0 .?

答:
Java 8 support in the 3.2.x line:

Spring Framework 3.2.x is based on unpatched repackaged versions of ASM and CGLIB. At this point, that's planned to be ASM 5.0.1 and CGLIB 3.1 for Spring 3.2.9, providing basic Java 8 bytecode compatibility. However, for Spring Framework 4's locally forked version of ASM, there's already a patch beyond ASM 5.0.1 as well as additional CGLIB 3.1 compatibility patches for the "-parameters" compiler flag, all scheduled to go into Spring Framework 4.0.4... So if there are any issues with Java 8 bytecode handling, in particular in combination with the "-parameters" flag, we urge you to upgrade to Spring Framework 4.0.4+. This won't be addressed in 3.2.9 since we're not going to introduce a local ASM fork there anymore.

Spring Framework 3.2.x uses AspectJ 1.7.4. For full Java 8 support in AspectJ, you'll have to use AspectJ 1.8. We're only officially supporting AspectJ 1.8 final in Spring Framework 4.0.4+... Even if it is likely to work with Spring Framework 3.2.x as well, we're not officially supporting it.

All in all, Java 8 support in Spring Framework 3.2.9 will just be "best effort" in terms of accepting the Java 8 bytecode level. For comprehensive Java 8 support, go Spring 4+.

please refer https://jira.spring.io/browse/SPR-11656 for more details.


问:
Powershell force 5 digit format in a string pattern
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

```<code>$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}
</code>```

Thanks.

EDIT: I would like to do the following

```<code>Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####
</code>```

答:
```<code>#example of the text we'd load in from file / whereever
$value = @'
this is an example of a value to be replaced: 1AB-23-45 though
we may also want to replace 0CD-87-6 or even 9ZX-00-12345 that
'@

#regex to detect the #XX-##-##### pattern you mentioned (\b word boundaries included so we don't pick up these patterns if they're somehow part of a larger string; though that seems unlikely in this case)
$pattern = '\b(\d[A-Z][A-Z])-(\d\d)-(\d{1,5})\b'
#what we want our output to look like; with placeholders 0, 1, & 2 taking values from our captures from the above.
$format = '{0}-{1}-{2:D5}'

<#
 # #use select-string to allow us to capture every match, rather than just the first
 # $value | Select-String -Pattern $pattern -AllMatches | %{
 #     #loop through every match replacing the matched string with the reformatted version of itself
 #     $_.matches | %{
 #         #NB: we have to convert the match in group#3 to int to ensure the {2:D3} formatting from above will be applied as expected
 #         $value = $value -replace "\b$($_.value)\b", ($format -f $_.Groups[1].Value,$_.Groups[2].Value,([int]$_.Groups[3].Value))
 #     }
 # }
#>

#or this version's a little more efficient; using the matched positions to replace the strings in those positions with our new formatted value
$value | Select-String -Pattern $pattern -AllMatches | %{
    $_.matches | sort index -Descending | %{
        $value = $value.remove($_.index, $_.value.length).insert($_.index, ($format -f $_.Groups[1].Value,$_.Groups[2].Value,([int]$_.Groups[3].Value)))
    }
}

$value
</code>```

Body:
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}

Thanks.

EDIT: I would like to do the following

Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####


问:
Android O Gradle build fails with travis ci
I'm trying to use Travis CI for my Android Project but my Builds constantly failing but works on local build. I am using Android Studio Preview 3 and gradle 3 alpha 3.

I am getting this error below.

Could not find com.android.tools.build:gradle:3.0.0-alpha3.

Here is my build log

My Travis Config file

My Project gradle file

答:
I'm getting an Access denied error to your build log, and I didn't use it, but I'll try to answer you.

As announced here:

The Android Gradle Plugin 3.0.0-alpha3 was also released through
  maven.google.com.

You can try to fix it by adding Google’s Maven Repository here like this:

```<code>buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
</code>```

Make sure that the repositories section includes a maven section with
  the "https://maven.google.com" endpoint. For example:

```<code>allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
</code>```

As commented here, this version doesn't exist in Bintray JCenter:

com.android.tools.build.gradle
  latest version is 2.5.0-alpha-preview-02, there is no 3.0.0-alpha3

Also be sure to update build tools to the latest version as suggested in this related question:

Update your build tools from SDK manager

I add links to samples using the new sdkmanager command line here.

I would need a sample project reproducing the issue to check my suggestions.

Body:
I'm getting an Access denied error to your build log, and I didn't use it, but I'll try to answer you.

As announced here:

The Android Gradle Plugin 3.0.0-alpha3 was also released through
  maven.google.com.

You can try to fix it by adding Google’s Maven Repository here like this:

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

Make sure that the repositories section includes a maven section with
  the "https://maven.google.com" endpoint. For example:

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

As commented here, this version doesn't exist in Bintray JCenter:

com.android.tools.build.gradle
  latest version is 2.5.0-alpha-preview-02, there is no 3.0.0-alpha3

Also be sure to update build tools to the latest version as suggested in this related question:

Update your build tools from SDK manager

I add links to samples using the new sdkmanager command line here.

I would need a sample project reproducing the issue to check my suggestions.


问:
how to get object value in side of [http post] in mvc 4
```<code>[HttpGet]
        public ActionResult Delete(string ID)
        {
            return View(objDB.SelectDatabyID(ID));
        }

[HttpPost]
        public ActionResult Delete(Customer objCustomer)
        {
            string result = objDB.DeleteData(objCustomer);
            ViewData["result"] = result;
            ModelState.Clear(); //clearing model
            return View();
        }
</code>```

in this code [httppost] side not gettig value..it will be show null value in objCustomer..basically Customer is a modelclass..how to get customerid value in [httppost] side..

答:
Hi you can simply do this by using the form, In a view, put all your controls which has binded with the Customer  model inside the form tag including submit button. thats it

Now if you click submit, mvc will bind all the controls value to the model corresponding property and will give you as a complete model.

Ex: view code

```<code> @model Mul.Models.Customer

@using (Html.BeginForm("Delete", "Home", FormMethod.Post))
    {
                    @Html.TextBoxFor(m => m.customerId)

                    @Html.TextBoxFor(m => m.customerName)

                <input type="submit" value="Submit"/>

    }
</code>```

Same Controller code:

```<code>[HttpPost]
        public ActionResult Delete(Customer objCustomer)
        {
            string result = objDB.DeleteData(objCustomer);
            ViewData["result"] = result;
            ModelState.Clear(); //clearing model
            return View();
        }
</code>```

Note: you should put formmethod.post other you wont get it as a model.

Hope the above information was helpful.

Thanks

Karthik

Body:
[HttpGet]
        public ActionResult Delete(string ID)
        {
            return View(objDB.SelectDatabyID(ID));
        }

[HttpPost]
        public ActionResult Delete(Customer objCustomer)
        {
            string result = objDB.DeleteData(objCustomer);
            ViewData["result"] = result;
            ModelState.Clear(); //clearing model
            return View();
        }

in this code [httppost] side not gettig value..it will be show null value in objCustomer..basically Customer is a modelclass..how to get customerid value in [httppost] side..

Body:
Hi you can simply do this by using the form, In a view, put all your controls which has binded with the Customer  model inside the form tag including submit button. thats it

Now if you click submit, mvc will bind all the controls value to the model corresponding property and will give you as a complete model.

Ex: view code

 @model Mul.Models.Customer

@using (Html.BeginForm("Delete", "Home", FormMethod.Post))
    {
                    @Html.TextBoxFor(m => m.customerId)

                    @Html.TextBoxFor(m => m.customerName)

                <input type="submit" value="Submit"/>

    }

Same Controller code:

[HttpPost]
        public ActionResult Delete(Customer objCustomer)
        {
            string result = objDB.DeleteData(objCustomer);
            ViewData["result"] = result;
            ModelState.Clear(); //clearing model
            return View();
        }

Note: you should put formmethod.post other you wont get it as a model.

Hope the above information was helpful.

Thanks

Karthik


问:
C unsigned int x = 1; smaller than int y = -1;
i do know the differences of signed unsigened etc.
But i don´t understand the following code:

```<code>unsigned int x = 1;
int y = -1;
    if(y < x)
        printf("of course it is");
    else
        printf("strange stuff");
</code>```

1 should be a greater number than -1, no matter which representation is used. Because "strange stuff" will be displayed on the console.

答:
signed 1 (as byte) in bits: 00000001

unsigned 1 in bits: 00000001

signed -1 in bits: 10000001 (or 1 1111111, just details)

unsigned -1 in bits: no valid representation (10000001  is 129)

if you want safely compare signed and unsigned variables, than you have two ways:

1) take in account signs and manually compare them (<s>e. g. isSignedLess = (signed < 0) || ((unsigned <= max_signed) && (signed < unsigned)) </s>)

2) cast both to bigger singed (i. e. signed long long) and than compare them (signed long long can store all diapason of signed/unsigned int's)

As you can see in comments, both ways are kinda tricky. Just don't mix  signed and unsigned wherever you can. It's possible in 99% cases. In last 1% cases you really need to know what you doing (e. g. often had to use signed indexes with vectors, but size() - unsigned, so I ask myself hundred time "can this vector reach MAX_INT or not? have I to do more complex code or it's ok for this task?").

Body:
i do know the differences of signed unsigened etc.
But i don´t understand the following code:

unsigned int x = 1;
int y = -1;
    if(y < x)
        printf("of course it is");
    else
        printf("strange stuff");

1 should be a greater number than -1, no matter which representation is used. Because "strange stuff" will be displayed on the console.


问:
Integrating MailChimp with Django User Workflow
I'd like to leverage the richness of mailchimp (email template design, analytics, etc) on a Django project I'm working on.

I want to essentially use Mailchimp for all email communications - new user registration on the site, forgot password, newsletters, reminders, etc.

The issue I have is that Mailchimp is very much list and campaign oriented. I'm not sure how to achieve the things listed above with the mailchimp workflow.

What I want to do is something like -

Setup a specific email in mailchimp, such as the 'forgot password email'

When a user forgets their password, I want to trigger mailchimp to send the specified mail

Does anyone have experience doing the above?

答:
First, you have create an account on MailChimp, create the List there, and thereafter get the List Key and API key of your account.

Install the package to integrate MailChimp into your Django site

```<code>pip install mailchimp
</code>```

Then send a request to connect with your list in MailChimp

```<code>import mailchimp

API_KEY = <<Your MailChimp API Key>>
LIST_ID = <<Your List Key>>
api = mailchimp.Mailchimp(API_KEY)
api.lists.subscribe(LIST_ID, {'email': 'xyz@gmail.com'})
</code>```

For a detailed explanation and integration step by step, follow this tutorial:
https://djangopy.org/package-of-week/how-to-integrate-mailchimp-on-django-to-increase-subscribers/

ContentLicense: CC BY-SA 4.0

Body:
First, you have create an account on MailChimp, create the List there, and thereafter get the List Key and API key of your account.

Install the package to integrate MailChimp into your Django site

pip install mailchimp

Then send a request to connect with your list in MailChimp

import mailchimp

API_KEY = <<Your MailChimp API Key>>
LIST_ID = <<Your List Key>>
api = mailchimp.Mailchimp(API_KEY)
api.lists.subscribe(LIST_ID, {'email': 'xyz@gmail.com'})

For a detailed explanation and integration step by step, follow this tutorial:
https://djangopy.org/package-of-week/how-to-integrate-mailchimp-on-django-to-increase-subscribers/


问:
passing ng-model input date to a service to make a api consult
I need to pass a user-selected date from my view to my service.

View:

```<code><div class='input-group date'>
    <input type="date" ng-model="dateLinea" class="form-control"/>
</div>
</code>```

Controller:

```<code>function MainCtrl($scope, consumeApi, $filter) {
     consumeApi.getFullByron().success(function(data){
        $scope.dataFromFactory = data;
 });
</code>```

Factory:

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

    // Return the object
    return {

        // Create simple method to get data from $http service
        getFullByron : function() {
            return $http({
                url: 'http://localhost/proveedores_api/core/api/proveedores/negocio_linea/negocio_linea_proveedor.php?api_key=ff19974921e713dd4ae3a6592532cd9d&function=negocio_linea_fecha&fecha=' + dateLinea,
                method: 'GET'
            })
        }
    }

}
</code>```

The url ends before the date, but I need to include the date that was passed in from the view.

I need to pass dateLinea to my service so, when I select a date, that date is added to the url to make the request.

答:
See if this works for you.

function MainCtrl($scope, consumeApi, $filter) {
//instead of null set this value to the whatever initial page load value needed.
  $scope.dateLinea = null;

  consumeApi.getFullByron($scope.dateLinea)
   .then(function(data) {
        $scope.dataFromFactory = data;
   })
   .catch(function(err) {
       console.log(err)
   });

  function consumeApi($http) {

    // Return the object
    return {

      // Create simple method to get data from $http service
      getFullByron: function(dateLinea) {
        return $http.get('http://localhost/proveedores_api/core/api/proveedores/negocio_linea/negocio_linea_proveedor.php?api_key=ff19974921e713dd4ae3a6592532cd9d&function=negocio_linea_fecha&fecha=' + dateLinea)
          .then(function(resp) {
          // here you can return the whole response or just data, depending on what you need or other preprocessing.
            return resp.data;
          })
      }
    }

  }
```

<p>EDIT: </p>

<pre class="lang-js prettyprint-override"><code>function MainCtrl($scope, consumeApi, $filter) {
  //instead of null set this value to the whatever initial page load value needed.
  $scope.dateLinea = null;

  function exampleGetWrapperFunction() {
    if ($scope.dateLinea) {
      consumeApi.getFullByron($scope.dateLinea)
        .then(function(data) {
          $scope.dataFromFactory = data;
        })
        .catch(function(err) {
          console.log(err)
        });
    }
  }
  exampleGetWrapperFunction();
}
</code>```

Body:
I need to pass a user-selected date from my view to my service.

View:

    <input type="date" ng-model="dateLinea" class="form-control"/>

Controller:

function MainCtrl($scope, consumeApi, $filter) {
     consumeApi.getFullByron().success(function(data){
        $scope.dataFromFactory = data;
 });

Factory:

function consumeApi($http) {

    // Return the object
    return {

        // Create simple method to get data from $http service
        getFullByron : function() {
            return $http({
                url: 'http://localhost/proveedores_api/core/api/proveedores/negocio_linea/negocio_linea_proveedor.php?api_key=ff19974921e713dd4ae3a6592532cd9d&function=negocio_linea_fecha&fecha=' + dateLinea,
                method: 'GET'
            })
        }
    }

}

The url ends before the date, but I need to include the date that was passed in from the view.

I need to pass dateLinea to my service so, when I select a date, that date is added to the url to make the request.

Body:
See if this works for you.

function MainCtrl($scope, consumeApi, $filter) {
//instead of null set this value to the whatever initial page load value needed.
  $scope.dateLinea = null;

  consumeApi.getFullByron($scope.dateLinea)
   .then(function(data) {
        $scope.dataFromFactory = data;
   })
   .catch(function(err) {
       console.log(err)
   });

  function consumeApi($http) {

    // Return the object
    return {

      // Create simple method to get data from $http service
      getFullByron: function(dateLinea) {
        return $http.get('http://localhost/proveedores_api/core/api/proveedores/negocio_linea/negocio_linea_proveedor.php?api_key=ff19974921e713dd4ae3a6592532cd9d&function=negocio_linea_fecha&fecha=' + dateLinea)
          .then(function(resp) {
          // here you can return the whole response or just data, depending on what you need or other preprocessing.
            return resp.data;
          })
      }
    }

  }

EDIT:

function MainCtrl($scope, consumeApi, $filter) {
  //instead of null set this value to the whatever initial page load value needed.
  $scope.dateLinea = null;

  function exampleGetWrapperFunction() {
    if ($scope.dateLinea) {
      consumeApi.getFullByron($scope.dateLinea)
        .then(function(data) {
          $scope.dataFromFactory = data;
        })
        .catch(function(err) {
          console.log(err)
        });
    }
  }
  exampleGetWrapperFunction();
}


问:
Pascal Script Fast Reports
EDIT:

Im having to edit some old Pascal Script in Fast Reports and are having a tough time returning only distinct records. Any help would be appreciated.

So Basically, I am calling a stored proc to return data in a table. In one of these columns there sometimes are a 1 letter code (A,B,C) that defines which rtf file to go fetch for the report.

Currently It does go fetch all of the rtf files for the respective codes, but sometimes the code is repeated (A,A) and in that case I need it to return only the DISTINCT rtf files. So If A was pulled allready, Dont Pull again and carry on looking for other codes in that Column

My Code:
NOTE: In Memo93 I am just inserting (table."Class")

```<code>    procedure GroupHeader17OnBeforePrint(Sender: TfrxComponent );
var
       CarGroup: String     ;
       CarGroupLoop: String;
begin
                       CarGroup := Memo93.Value;
                       if not(CarGroup = CarGroupLoop) then
                       begin
                               try
                                       GroupHeader17.Visible := TRUE;
                                       rich23.richedit.lines.LoadFromFile('example\'+ trim(Get('@QteLanguage'))+ '\'+ trim(Get('@QteLanguage'))+'_Group_'+ trim(<Table."class">)+ '.rtf');

                               except
                                       GroupHeader17.Visible := FALSE;

                               end;
                       end
                       else
                       begin
                               GroupHeader17.Visible := False;
                       end;

                       CarGroupLoop := <table."Class">;

end;
</code>```

This Seem to have done the job and only bring back distinct rtf files.

```<code>procedure GroupHeader17OnBeforePrint(Sender: TfrxComponent );
var
       CarGroup: String     ;
       CarGroupLoop: String;
begin
                       CarGroup := Memo93.Value;
                       CarGroupLoop :=  <table."Class">;
                       if not(CarGroup = CarGroupLoop) then
                       begin
                               try
                                       GroupHeader17.Visible := TRUE;
                                       rich23.richedit.lines.LoadFromFile('example\'+ trim(Get('@QteLanguage'))+ '\'+ trim(Get('@QteLanguage'))+'_Group_'+ trim( <table."Class">)+ '.rtf');

                               except
                                       GroupHeader17.Visible := FALSE;

                               end;
                       end
                       else
                       begin
                               GroupHeader17.Visible := False;
                       end;

end;
</code>```

答:
Try to use CarGroup :=
; and move CarGroupLoop :=
; at the end of GroupHeader17OnBeforePrint event

```<code>    procedure GroupHeader17OnBeforePrint(Sender: TfrxComponent );
var
       CarGroup: String     ;
       CarGroupLoop: String;
begin
                       CarGroup :=  <table."Class">;
                       if not(CarGroup = CarGroupLoop) then
                       begin
                               try
                                       GroupHeader17.Visible := TRUE;
                                       rich23.richedit.lines.LoadFromFile('example\'+ trim(Get('@QteLanguage'))+ '\'+ trim(Get('@QteLanguage'))+'_Group_'+ trim(<Table."class">)+ '.rtf');

                               except
                                       GroupHeader17.Visible := FALSE;

                               end;
                       end
                       else
                       begin
                               GroupHeader17.Visible := False;
                       end;

                       CarGroupLoop := <table."Class">;

end;
</code>```

Title: Pascal Script Fast Reports

Body:
EDIT:

Im having to edit some old Pascal Script in Fast Reports and are having a tough time returning only distinct records. Any help would be appreciated.

So Basically, I am calling a stored proc to return data in a table. In one of these columns there sometimes are a 1 letter code (A,B,C) that defines which rtf file to go fetch for the report.

Currently It does go fetch all of the rtf files for the respective codes, but sometimes the code is repeated (A,A) and in that case I need it to return only the DISTINCT rtf files. So If A was pulled allready, Dont Pull again and carry on looking for other codes in that Column

My Code:
NOTE: In Memo93 I am just inserting (table."Class")

    procedure GroupHeader17OnBeforePrint(Sender: TfrxComponent );
var
       CarGroup: String     ;
       CarGroupLoop: String;
begin
                       CarGroup := Memo93.Value;
                       if not(CarGroup = CarGroupLoop) then
                       begin
                               try
                                       GroupHeader17.Visible := TRUE;
                                       rich23.richedit.lines.LoadFromFile('example\'+ trim(Get('@QteLanguage'))+ '\'+ trim(Get('@QteLanguage'))+'_Group_'+ trim(
)+ '.rtf');

                               except
                                       GroupHeader17.Visible := FALSE;

                               end;
                       end
                       else
                       begin
                               GroupHeader17.Visible := False;
                       end;

                       CarGroupLoop :=
;

end;

This Seem to have done the job and only bring back distinct rtf files.

procedure GroupHeader17OnBeforePrint(Sender: TfrxComponent );
var
       CarGroup: String     ;
       CarGroupLoop: String;
begin
                       CarGroup := Memo93.Value;
                       CarGroupLoop :=
;
                       if not(CarGroup = CarGroupLoop) then
                       begin
                               try
                                       GroupHeader17.Visible := TRUE;
                                       rich23.richedit.lines.LoadFromFile('example\'+ trim(Get('@QteLanguage'))+ '\'+ trim(Get('@QteLanguage'))+'_Group_'+ trim(
)+ '.rtf');

                               except
                                       GroupHeader17.Visible := FALSE;

                               end;
                       end
                       else
                       begin
                               GroupHeader17.Visible := False;
                       end;

end;

Body:
Try to use CarGroup :=  <table."Class">; and move CarGroupLoop :=  <table."Class">; at the end of GroupHeader17OnBeforePrint event

    procedure GroupHeader17OnBeforePrint(Sender: TfrxComponent );
var
       CarGroup: String     ;
       CarGroupLoop: String;
begin
                       CarGroup :=  <table."Class">;
                       if not(CarGroup = CarGroupLoop) then
                       begin
                               try
                                       GroupHeader17.Visible := TRUE;
                                       rich23.richedit.lines.LoadFromFile('example\'+ trim(Get('@QteLanguage'))+ '\'+ trim(Get('@QteLanguage'))+'_Group_'+ trim(<Table."class">)+ '.rtf');

                               except
                                       GroupHeader17.Visible := FALSE;

                               end;
                       end
                       else
                       begin
                               GroupHeader17.Visible := False;
                       end;

                       CarGroupLoop := <table."Class">;

end;


问:
maven2 war overlay and eclipse WTP
I have a maven war module which run eclipse WTP tomcat server like normal. Now i want to reuse that module artifact by using maven war overlay: i just create a new war project and include that module in project dependencies. The problem is now i cannot use eclipse "Run on server" anymore because i don't have any resource or config file (like web.xml) in the new project, everything is in the war dependencies but eclipse cannot resolve it.

Is there anyway to use a maven war overlay project run with eclipse ?

Thank you.

答:
If you're trying to have a war dependency on a war project, in other words doing a "war overlay", then it's not currently supported by m2eclipse
Jer developped a plugin to implement this feature, you can give it a try : http://code.google.com/p/m2eclipse-wtp-ext/</p>

Title: maven2 war overlay and eclipse WTP


问:
Laravel: Get variable name from route
How can I get the name of the get variable from a route url?

```<code>http://localhost:8000/api/system/123
</code>```

Basically I want to know what the GET variable is called that holds the value of 123. For example here it is called id

```<code>http://localhost:8000/api/system?id=123
</code>```

How can this be done?

```<code>Route::get('api/system/{id}', 'ApiController@User');
</code>```

答:
The route must be defined as:

```<code>Route::get('api/system', 'ApiController@user');
</code>```

And in your controller to get the value of any variable should be:

```<code>public function user(Request $request){
  dd($request->get('id'));
}
</code>```

Recommendations

If you are only going to receive an id use

Route::get('api/system/{id}, 'ApiController@user');

And the controller should be:

```<code>public function user($id){
  dd($id);
}
</code>```

The methods in the controller should be down cased. Ex: user instead of User

Read this laravel routes documenation

Title: Laravel: Get variable name from route

Body:
How can I get the name of the get variable from a route url?

http://localhost:8000/api/system/123

Basically I want to know what the GET variable is called that holds the value of 123. For example here it is called id

http://localhost:8000/api/system?id=123

How can this be done?

Route::get('api/system/{id}', 'ApiController@User');

Body:
The route must be defined as:

Route::get('api/system', 'ApiController@user');

And in your controller to get the value of any variable should be:

public function user(Request $request){
  dd($request->get('id'));
}

Recommendations

If you are only going to receive an id use

Route::get('api/system/{id}, 'ApiController@user');

And the controller should be:

public function user($id){
  dd($id);
}

The methods in the controller should be down cased. Ex: user instead of User

Read this laravel routes documenation


答:
Simply pass model to API as a parameter and use it in service...

code as below

Controller:

```<code>function MainCtrl($scope, consumeApi, $filter) {
 consumeApi.getFullByron($scope.dateLinea).success(function(data){
    console.log(data);
    $scope.dataFromFactory = data;
});
</code>```

In Service:

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

// Return the object
return {

    // Create simple method to get data from $http service
    getFullByron : function(dateLinea) {
        return $http({
            url: 'http://localhost/proveedores_api/core/api/proveedores/negocio_linea/negocio_linea_proveedor.php?api_key=ff19974921e713dd4ae3a6592532cd9d&function=negocio_linea_fecha&fecha=' + dateLinea,
            method: 'GET'
        })
    }
  }

}
</code>```

Title: passing ng-model input date to a service to make a api consult

Body:
Simply pass model to API as a parameter and use it in service...

code as below

Controller:

function MainCtrl($scope, consumeApi, $filter) {
 consumeApi.getFullByron($scope.dateLinea).success(function(data){
    console.log(data);
    $scope.dataFromFactory = data;
});

In Service:

function consumeApi($http) {

// Return the object
return {

    // Create simple method to get data from $http service
    getFullByron : function(dateLinea) {
        return $http({
            url: 'http://localhost/proveedores_api/core/api/proveedores/negocio_linea/negocio_linea_proveedor.php?api_key=ff19974921e713dd4ae3a6592532cd9d&function=negocio_linea_fecha&fecha=' + dateLinea,
            method: 'GET'
        })
    }
  }

}


问:
How to change swimlane orientation in Visio BPMN diagram using VBA
Visio 2013 contains a stencil for the BPMN diagram type. This stencil has a "Pool / Lane" master. When you drop it on a drawing, a new lane appears. Then you can go to the "Cross-functional Flowchart" ribbon and change its orientation with the "Orientation" option button, which offers a selection of vertical and horizontal orientations. How can I do the same manipulation in VBA?

I've tried to record the respective macro in Visio macro recorder. Surprisingly, the recorded macro contains no code for this manipulation.

答: i open shapesheet window, and change vertical/horizontal orientation. i find cells which changed with orientation


问:
Algorithm Analysis -- Big O Notation
What's a good strategy to determine the running time (Big O notation) of data structures and algorithms. I have the following to figure out the running times for and I'm having
trouble determining what it would be.

AINC is an array containing n integers arranged in increasing order.

AD is an array containing n integers arranged in decreasing order.

AR is an array containing n integers in random order.

Q is a queue implemented as a linked list and containing p elements.

LINK is a linked list containing n nodes.

CIRC is a circular linked list containing n elements, where C points to the last element.

T is a binary search tree containing n nodes.

a) Searching for an element in AINC using linear search.

b) Deleting the 10thnode of linked list LINK.

c) Calling a function which uses Q, and calls dequeue m times.

d) Inserting an element at the end of the list CIRC.

e) Deleting the last element of CIRC.

f) Finding the largest element of T.

g) Determining the height of T.

h) Making the call selectionsort (AINC, n).

i) Making two calls one after another. The first call is mergesort(AD,n), followed by the call insertionsort(AD,n).

j) Converting a decimal integer num into its binary equivalent.

***This is not hw. I am preparing for an exam.

答: If you are new to Big O analysis and have some time (2.5 hours), I would recommend watching the first two lectures of this algorithms class delivered by Leiserson himself.</p>

Title: Algorithm Analysis -- Big O Notation


问:
How to give an image a priority over a while loop drawing background
So basically for days, I have been trying to figure out key listener's in which I did to move my 'Superman' object with the arrow keys. This only works when I /* */ out my while loop of drawing the 'moving' road. Once it is uncommented and I run the program, the Superman does not move, and I assume that it is because the loop has priority over the image. I believe that I need help with threading the images priority. Help is much appreciated.</p>

```<code>// The "CPT" class.
import java.applet.*;
import java.awt.*;
import java.awt.Image;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Runnable;
import java.lang.Thread;

public class CPT extends Applet implements KeyListener
{
    // Place instance variables here
    Image myImage;
    int x = 100, y = 200;

    public void init ()
    {

        myImage = getImage (getCodeBase (), "SuperMan.png");
        System.out.println (getCodeBase ());
        addKeyListener (this);
        // Place the body of the initialization method here
    } // init method

    public void paint (Graphics g)
    {

       //Drawing sky
        g.setColor (new Color (150, 150, 254));
        g.fillRect (0, 0, 1000, 500);
        //Drawing floor
        g.setColor (Color.black);
        g.fillRect (0, 500, 1000, 150);
        //Drawing road lines

        //g.fillRect (
        //Drawing Sun
        g.setColor (Color.yellow);
        g.fillOval (800, 50, 75, 75);

        //Drawing Birds
        g.setColor (Color.black);
        g.drawArc (100, 75, 25, 25, 0, 180);
        g.drawArc (125, 75, 25, 25, 0, 180);

        g.drawArc (175, 85, 25, 25, 0, 180);
        g.drawArc (200, 85, 25, 25, 0, 180);

        g.drawArc (250, 65, 25, 25, 0, 180);
        g.drawArc (275, 65, 25, 25, 0, 180);

        //Drawing Smaller Birds

        g.drawArc (125, 55, 15, 15, 0, 180);
        g.drawArc (140, 55, 15, 15, 0, 180);
        while (true)
        {

            g.setColor (Color.black);
            g.fillRect (-30, 575, 80, 25);
            g.fillRect (120, 575, 80, 25);
            g.fillRect (270, 575, 80, 25);
            g.fillRect (420, 575, 80, 25);
            g.fillRect (570, 575, 80, 25);
            g.fillRect (720, 575, 80, 25);
            g.fillRect (870, 575, 80, 25);
            //first blocks
            g.setColor (Color.yellow);
            g.fillRect (50, 575, 80, 25);
            g.fillRect (200, 575, 80, 25);
            g.fillRect (350, 575, 80, 25);
            g.fillRect (500, 575, 80, 25);
            g.fillRect (650, 575, 80, 25);
            g.fillRect (800, 575, 80, 25);
            g.fillRect (950, 575, 80, 25);

            for (int k = 0 ; k < 100000000 ; k++)
                ;
            //second blocks

            g.setColor (Color.black);
            g.fillRect (50, 575, 80, 25);
            g.fillRect (200, 575, 80, 25);
            g.fillRect (350, 575, 80, 25);
            g.fillRect (500, 575, 80, 25);
            g.fillRect (650, 575, 80, 25);
            g.fillRect (800, 575, 80, 25);
            g.fillRect (950, 575, 80, 25);

            g.setColor (Color.orange);
            g.fillRect (10, 575, 80, 25);
            g.fillRect (160, 575, 80, 25);
            g.fillRect (310, 575, 80, 25);
            g.fillRect (460, 575, 80, 25);
            g.fillRect (610, 575, 80, 25);
            g.fillRect (760, 575, 80, 25);
            g.fillRect (910, 575, 80, 25);

            for (int z = 0 ; z < 100000000 ; z++)
                ;

            //third blocks

            g.setColor (Color.black);
            g.fillRect (10, 575, 80, 25);
            g.fillRect (160, 575, 80, 25);
            g.fillRect (310, 575, 80, 25);
            g.fillRect (460, 575, 80, 25);
            g.fillRect (610, 575, 80, 25);
            g.fillRect (760, 575, 80, 25);
            g.fillRect (910, 575, 80, 25);

            g.setColor (Color.yellow);
            g.fillRect (-30, 575, 80, 25);
            g.fillRect (120, 575, 80, 25);
            g.fillRect (270, 575, 80, 25);
            g.fillRect (420, 575, 80, 25);
            g.fillRect (570, 575, 80, 25);
            g.fillRect (720, 575, 80, 25);
            g.fillRect (870, 575, 80, 25);

            for (int t = 0 ; t < 100000000 ; t++)
                ;

            g.drawImage (myImage, x, y, 100, 40, this);

        }
    } // paint method

    public void keyReleased (KeyEvent e)
    {

    }

    public void keyPressed (KeyEvent e)
    {
        if (e.getKeyCode () == KeyEvent.VK_RIGHT)
        {
            // System.out.println ("Right Key Pressed");
            x += 10;
        }

        if (e.getKeyCode () == KeyEvent.VK_LEFT)
        {
            // System.out.println ("Left Key Pressed");
            x -= 10;
        }

        if (e.getKeyCode () == KeyEvent.VK_UP)
        {
        y -= 10;
        }

        if (e.getKeyCode () == KeyEvent.VK_DOWN)
        {
        y+=10;
        }
        repaint ();
    }

    public void keyTyped (KeyEvent e)
    {

    }
} // CPT class
</code>```

答:
That while loop freezes your whole application. It will keep on drawing stuff onto graphics but wont allow Swing event dispatch thread to be able to refresh the screen with your graphics.

Some suggestions:

1) Move the while loop outside of paint method and into a separate thread. Better yet read up on how to do proper animation in Java Swing.

2) Read up on how to properly override Swing component paint method.

3) Read up on what is Event Dispatch Thread and why you have to avoid blocking it.

Body:
So basically for days, I have been trying to figure out key listener's in which I did to move my 'Superman' object with the arrow keys. This only works when I /* */ out my while loop of drawing the 'moving' road. Once it is uncommented and I run the program, the Superman does not move, and I assume that it is because the loop has priority over the image. I believe that I need help with threading the images priority. Help is much appreciated.

// The "CPT" class.
import java.applet.*;
import java.awt.*;
import java.awt.Image;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Runnable;
import java.lang.Thread;

public class CPT extends Applet implements KeyListener
{
    // Place instance variables here
    Image myImage;
    int x = 100, y = 200;

    public void init ()
    {

        myImage = getImage (getCodeBase (), "SuperMan.png");
        System.out.println (getCodeBase ());
        addKeyListener (this);
        // Place the body of the initialization method here
    } // init method

    public void paint (Graphics g)
    {

       //Drawing sky
        g.setColor (new Color (150, 150, 254));
        g.fillRect (0, 0, 1000, 500);
        //Drawing floor
        g.setColor (Color.black);
        g.fillRect (0, 500, 1000, 150);
        //Drawing road lines

        //g.fillRect (
        //Drawing Sun
        g.setColor (Color.yellow);
        g.fillOval (800, 50, 75, 75);

        //Drawing Birds
        g.setColor (Color.black);
        g.drawArc (100, 75, 25, 25, 0, 180);
        g.drawArc (125, 75, 25, 25, 0, 180);

        g.drawArc (175, 85, 25, 25, 0, 180);
        g.drawArc (200, 85, 25, 25, 0, 180);

        g.drawArc (250, 65, 25, 25, 0, 180);
        g.drawArc (275, 65, 25, 25, 0, 180);

        //Drawing Smaller Birds

        g.drawArc (125, 55, 15, 15, 0, 180);
        g.drawArc (140, 55, 15, 15, 0, 180);
        while (true)
        {

            g.setColor (Color.black);
            g.fillRect (-30, 575, 80, 25);
            g.fillRect (120, 575, 80, 25);
            g.fillRect (270, 575, 80, 25);
            g.fillRect (420, 575, 80, 25);
            g.fillRect (570, 575, 80, 25);
            g.fillRect (720, 575, 80, 25);
            g.fillRect (870, 575, 80, 25);
            //first blocks
            g.setColor (Color.yellow);
            g.fillRect (50, 575, 80, 25);
            g.fillRect (200, 575, 80, 25);
            g.fillRect (350, 575, 80, 25);
            g.fillRect (500, 575, 80, 25);
            g.fillRect (650, 575, 80, 25);
            g.fillRect (800, 575, 80, 25);
            g.fillRect (950, 575, 80, 25);

            for (int k = 0 ; k < 100000000 ; k++)
                ;
            //second blocks

            g.setColor (Color.black);
            g.fillRect (50, 575, 80, 25);
            g.fillRect (200, 575, 80, 25);
            g.fillRect (350, 575, 80, 25);
            g.fillRect (500, 575, 80, 25);
            g.fillRect (650, 575, 80, 25);
            g.fillRect (800, 575, 80, 25);
            g.fillRect (950, 575, 80, 25);

            g.setColor (Color.orange);
            g.fillRect (10, 575, 80, 25);
            g.fillRect (160, 575, 80, 25);
            g.fillRect (310, 575, 80, 25);
            g.fillRect (460, 575, 80, 25);
            g.fillRect (610, 575, 80, 25);
            g.fillRect (760, 575, 80, 25);
            g.fillRect (910, 575, 80, 25);

            for (int z = 0 ; z < 100000000 ; z++)
                ;

            //third blocks

            g.setColor (Color.black);
            g.fillRect (10, 575, 80, 25);
            g.fillRect (160, 575, 80, 25);
            g.fillRect (310, 575, 80, 25);
            g.fillRect (460, 575, 80, 25);
            g.fillRect (610, 575, 80, 25);
            g.fillRect (760, 575, 80, 25);
            g.fillRect (910, 575, 80, 25);

            g.setColor (Color.yellow);
            g.fillRect (-30, 575, 80, 25);
            g.fillRect (120, 575, 80, 25);
            g.fillRect (270, 575, 80, 25);
            g.fillRect (420, 575, 80, 25);
            g.fillRect (570, 575, 80, 25);
            g.fillRect (720, 575, 80, 25);
            g.fillRect (870, 575, 80, 25);

            for (int t = 0 ; t < 100000000 ; t++)
                ;

            g.drawImage (myImage, x, y, 100, 40, this);

        }
    } // paint method

    public void keyReleased (KeyEvent e)
    {

    }

    public void keyPressed (KeyEvent e)
    {
        if (e.getKeyCode () == KeyEvent.VK_RIGHT)
        {
            // System.out.println ("Right Key Pressed");
            x += 10;
        }

        if (e.getKeyCode () == KeyEvent.VK_LEFT)
        {
            // System.out.println ("Left Key Pressed");
            x -= 10;
        }

        if (e.getKeyCode () == KeyEvent.VK_UP)
        {
        y -= 10;
        }

        if (e.getKeyCode () == KeyEvent.VK_DOWN)
        {
        y+=10;
        }
        repaint ();
    }

    public void keyTyped (KeyEvent e)
    {

    }
} // CPT class


问:
Keeping my JAVA (jar) program running on Heroku
I have made a bot in Java and it works great when I run the command:

```<code>heroku run nohup java -jar bot.jar
</code>```

However, after 24h Heroku closes it because of their Dyno policy. So, I thought of making a Procfile in order for it to execute the command above everytime it comes alive again.

I've tried placing the following commands inside the Procfile:

```<code>worker: java -jar bot.jar
worker: nohup java -jar bot.jar
</code>```

And I even made a run.sh file that contains:

```<code>#!/bin/bash
nohup java -jar bot.jar
</code>```

In order to make a Procfile that has:

```<code>worker: sh run.sh
</code>```

Sadly, none of this works, because everytime the Dyno executes the Procfile (right after I push a new version of it through git), the bot never comes alive. The logs show:

```<code>2017-06-07T13:17:33.651806+00:00 app[api]: Starting process with command `sh run.sh` by XXXX

2017-06-07T13:17:37.958327+00:00 heroku[run.2087]: State changed from starting to up

2017-06-07T13:17:37.948696+00:00 heroku[run.2087]: Awaiting client

2017-06-07T13:17:38.283581+00:00 heroku[run.2087]: Starting process with command `sh run.sh`

2017-06-07T13:17:52.807189+00:00 heroku[run.2087]: Client connection closed. Sending SIGHUP to all processes

2017-06-07T13:17:53.343009+00:00 heroku[run.2087]: Process exited with status 129

2017-06-07T13:17:53.359331+00:00 heroku[run.2087]: State changed from up to complete

2017-06-07T13:24:32.000000+00:00 app[api]: Build started by user XXXX

2017-06-07T13:24:43.090567+00:00 app[api]: Deploy YYYY by user XXXX

2017-06-07T13:24:43.090567+00:00 app[api]: Release v17 created by user XXXX

2017-06-07T13:24:32.000000+00:00 app[api]: Build succeeded
</code>```

I have no idea what to do in order for my bot to run from the Procfile.
Can you help me?

Thanks.

答:
Try running:

```<code>$ heroku ps:scale worker=1
</code>```

This will ensure that one worker process is always running.

Body:
I have made a bot in Java and it works great when I run the command:

heroku run nohup java -jar bot.jar

However, after 24h Heroku closes it because of their Dyno policy. So, I thought of making a Procfile in order for it to execute the command above everytime it comes alive again.

I've tried placing the following commands inside the Procfile:

worker: java -jar bot.jar
worker: nohup java -jar bot.jar

And I even made a run.sh file that contains:

#!/bin/bash
nohup java -jar bot.jar

In order to make a Procfile that has:

worker: sh run.sh

Sadly, none of this works, because everytime the Dyno executes the Procfile (right after I push a new version of it through git), the bot never comes alive. The logs show:

2017-06-07T13:17:33.651806+00:00 app[api]: Starting process with command `sh run.sh` by XXXX

2017-06-07T13:17:37.958327+00:00 heroku[run.2087]: State changed from starting to up

2017-06-07T13:17:37.948696+00:00 heroku[run.2087]: Awaiting client

2017-06-07T13:17:38.283581+00:00 heroku[run.2087]: Starting process with command `sh run.sh`

2017-06-07T13:17:52.807189+00:00 heroku[run.2087]: Client connection closed. Sending SIGHUP to all processes

2017-06-07T13:17:53.343009+00:00 heroku[run.2087]: Process exited with status 129

2017-06-07T13:17:53.359331+00:00 heroku[run.2087]: State changed from up to complete

2017-06-07T13:24:32.000000+00:00 app[api]: Build started by user XXXX

2017-06-07T13:24:43.090567+00:00 app[api]: Deploy YYYY by user XXXX

2017-06-07T13:24:43.090567+00:00 app[api]: Release v17 created by user XXXX

2017-06-07T13:24:32.000000+00:00 app[api]: Build succeeded

I have no idea what to do in order for my bot to run from the Procfile.
Can you help me?

Thanks.

Body:
Try running:

$ heroku ps:scale worker=1

This will ensure that one worker process is always running.


问:
In javascript, how to get timezone value in UTC format for new Date(2017,05,31).toISOString()?
How to get timezone value for new Date(2017,05,31).toISOString()? It always comes as 000Z for any Date when the date is passed to the Date constructor. But for new Date().toISOString(), it gives the the timezone value.

```<code>new Date(2017,05,31).toISOString() gives "2017-05-30T18:30:00.000Z"
</code>```

and new Date().toISOString() gives "2017-06-07T15:29:23.692Z". How to get timezone in UTC format for the past dates?

答:
If you want the time to default to midnight in UTC, you can use Date.UTC(year, month, ...) to first create a timestamp based in UTC.

```<code>var utcMay31 = Date.UTC(2017, 4, 31); // note: 4 = May (0 = January)
</code>```

Then, create the Date from that timestamp.

```<code>new Date(utcMay31).toUTCString(); // "Wed, 31 May 2017 00:00:00 GMT"
</code>```

However, if you're wanting to know the timezone stored in the Date object, it doesn't actually have that. Dates represent an "instant" in time as the total number of milliseconds that have passed since Jan 1, 1970 00:00:00.000 UTC.

```<code>new Date().getTime(); // 1496851...
</code>```

A Date can tell you the user's local offset from UTC in minutes at that instant.

```<code>new Date().getTimezoneOffset(); // e.g. 0, -480, 300
</code>```

Otherwise, the timezone is limited to two choices when creating date strings, and the choice is based on the method used – user's local timezone or UTC.

```<code>new Date().toString();    // "now" in user's local time
new Date().toUTCString(); // "now" in UTC time
new Date().toISOString(); // "now" also in UTC time, alternate format
// etc.
</code>```

Body:
How to get timezone value for new Date(2017,05,31).toISOString()? It always comes as 000Z for any Date when the date is passed to the Date constructor. But for new Date().toISOString(), it gives the the timezone value.

new Date(2017,05,31).toISOString() gives "2017-05-30T18:30:00.000Z"

and new Date().toISOString() gives "2017-06-07T15:29:23.692Z". How to get timezone in UTC format for the past dates?

Body:
If you want the time to default to midnight in UTC, you can use Date.UTC(year, month, ...) to first create a timestamp based in UTC.

var utcMay31 = Date.UTC(2017, 4, 31); // note: 4 = May (0 = January)

Then, create the Date from that timestamp.

new Date(utcMay31).toUTCString(); // "Wed, 31 May 2017 00:00:00 GMT"

However, if you're wanting to know the timezone stored in the Date object, it doesn't actually have that. Dates represent an "instant" in time as the total number of milliseconds that have passed since Jan 1, 1970 00:00:00.000 UTC.

new Date().getTime(); // 1496851...

A Date can tell you the user's local offset from UTC in minutes at that instant.

new Date().getTimezoneOffset(); // e.g. 0, -480, 300

Otherwise, the timezone is limited to two choices when creating date strings, and the choice is based on the method used – user's local timezone or UTC.

new Date().toString();    // "now" in user's local time
new Date().toUTCString(); // "now" in UTC time
new Date().toISOString(); // "now" also in UTC time, alternate format
// etc.


问:
How to debug ansible for general YAML syntax error without details to file and most likely unrelated to playbook itself?
I have refactored a huge playbook that includes other. I only changed the integration of files/* that get copied to the remote machines, i.e. changing from symlinks to real files etc. After that the playbook is not running anymore with no details for the error, only

$ ansible-playbook site.yml -i production.inv --limit build.local --ask-vault-pass --check -vvvvv
Using /home/XY/.ansible.cfg as config file
Vault password:
ERROR! Syntax Error while loading YAML.

Before the refactoring I see statically included: common/tasks/ubuntu-fix.yml output lines and if I manually add an error there, I get details like The error appears to have been in 'common/tasks/install.yml': line 3, column 9, but may also after the first file is included successfully. I conclude that the error happens before the first include, however the playbook itself is not changed and works in another folder with the old way of including files via symlink.

How can I debug in which file ansible fails?

答:
I found the problem. It was also a symlink, but to a yaml file in this case. In the other folder this symlink was correct. In the new version the symlink was broken and read in as physical binary file with the content

!<symlink>�workspace/dev.yml%

Why can't ansible help with showing that the inclusion of this file didn't work, i.e. to keep the general part of the question open how to debug such issues?


问:
Why does the function take an int, but does nothing when a variable is passed through?
```<code>  $array = $product->get_trims2($year);
  for($i = 0; $i < sizeof($array); ++$i) {
    var_dump((int)$array[$i]["car_trim"]);
    $item = $product->get_trim_by_id((int)$array[$i]["car_trim"]); //line of code in question
    var_dump($item);
  }
</code>```

will output:

int(29)
array(0) {
}

```<code>  $array = $product->get_trims2($year);
  for($i = 0; $i < sizeof($array); ++$i) {
    var_dump((int)$array[$i]["car_trim"]);
    $item = $product->get_trim_by_id(29); //line of code in question
    var_dump($item);
  }
</code>```

Will output:

int(29)
array(1) {
  [0]=>
  array(10) {
    ["id"]=>
    string(2) "29"
    [0]=>
    string(2) "29"
    ["year"]=>
    string(4) "2016"
    [1]=>
    string(4) "2016"
    ["make"]=>
    string(3) "bmw"
    [2]=>
    string(3) "bmw"
    ["model"]=>
    string(1) "3"
    [3]=>
    string(1) "3"
    ["trim"]=>
    string(22) "With OEM HID Headlamps"
    [4]=>
    string(22) "With OEM HID Headlamps"
  }
}

used function:

```<code>public function get_trim_by_id($id)
{
    $query = $this->pdo->prepare("SELECT * FROM `custom_trims` WHERE `id` = ?");
    $query->bindValue(1, $id);
    $query->execute();
    return $query->fetchAll();
}
</code>```

答:
Instead of bindValue(1, $id) use bindParam(1, $id) to pass a variable value. It looks like a matter of execution time and the value assigned by bind value.

You could read more here:

http://php.net/manual/es/pdostatement.bindvalue.php

Body:
  $array = $product->get_trims2($year);
  for($i = 0; $i < sizeof($array); ++$i) {
    var_dump((int)$array[$i]["car_trim"]);
    $item = $product->get_trim_by_id((int)$array[$i]["car_trim"]); //line of code in question
    var_dump($item);
  }

will output:

int(29)
array(0) {
}

  $array = $product->get_trims2($year);
  for($i = 0; $i < sizeof($array); ++$i) {
    var_dump((int)$array[$i]["car_trim"]);
    $item = $product->get_trim_by_id(29); //line of code in question
    var_dump($item);
  }

Will output:

int(29)
array(1) {
  [0]=>
  array(10) {
    ["id"]=>
    string(2) "29"
    [0]=>
    string(2) "29"
    ["year"]=>
    string(4) "2016"
    [1]=>
    string(4) "2016"
    ["make"]=>
    string(3) "bmw"
    [2]=>
    string(3) "bmw"
    ["model"]=>
    string(1) "3"
    [3]=>
    string(1) "3"
    ["trim"]=>
    string(22) "With OEM HID Headlamps"
    [4]=>
    string(22) "With OEM HID Headlamps"
  }
}

used function:

public function get_trim_by_id($id)
{
    $query = $this->pdo->prepare("SELECT * FROM `custom_trims` WHERE `id` = ?");
    $query->bindValue(1, $id);
    $query->execute();
    return $query->fetchAll();
}


问:
This program works fine on my pc but when I submit it to a coding site, it says there is a segmentation fault. Please point out the error someone
```<code>int main() {

  int n, found, query_no = 0;
  unsigned long int *phone;

  char **str, query[30], c;

  scanf("%d", &n);

  str = (char**) malloc(sizeof(char*) * n); //creating a pointer array of strings

  phone = (unsigned long int*) malloc(sizeof(unsigned long int) * n);
  for (int i = 0; i < n; i++) {
    str[i] = (char*) malloc(sizeof(char) * 30); //iitializing each pointer in arry
  }
  for (int i = 0; i < n; i++) {
    scanf("%s", *(str + i));
    scanf("%u", phone + i);
  }

  gets(query);
  char *p;
  p = query;

  while (*(p = gets(query)) != '\0')  //checks if blank line is entered
  {
    found = 0;
    for (int j = 0; j < n; j++) {
      /*two pointers are being passed here,*/
      /* one to the line entered and       */
      /* other to each character array pointed to by the pointer array*/
      if (strcmp(p, *(str + j)) == 0) {
        printf("%s", *(str + j));
        printf("=");
        printf("%u", *(phone + j));
        found = 1;
        break;
      }
    }
    if (found == 0) //if record not found, print so
      printf("Not found");
    printf("\n");
  }
</code>```

The code inputs a phone book from user by first inputting the number of records to be inserted then in each new line a record is entered in the form of name number.  Then the user searches for an unknown number records and we print the name and number if the records is found otherwise we print not found.

Source : Hackerrank 30 days of code Day 8
(I hope I am not violating any rules here, please tell me if I am)

答:
the following proposed code:

cleanly compiles

performs the desired function

avoids any use of the heap allocation functions, like malloc()

allows easy modification to the actual MAX value for 'n' via a #define statement.

allows easy modification to the max name length via a #define statement.

consolidates the data representation into a simple struct.

avoids calling functions (I.E. gets()) that has been removed from the C standard.

because it is a 'Hackerrank' item, does not perform error checking.

stops when a blank line is read for a 'query'

note the use of size_t rather than int as the values are never <0

And now the proposed code:

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

#define MAX_NAMES 500
#define MAX_NAME_LEN 30

struct phoneBook
{
    char name[ MAX_NAME_LEN + 1]; // +1 to allow for NUL terminator
    unsigned long phone;
};

struct phoneBook myPhoneBook[ MAX_NAMES ];

int main( void )
{
    size_t n;

    scanf("%lu", &n);

    for (size_t i = 0; i < n; i++)
    {
        scanf( "%29s", myPhoneBook[i].name );
        char *newline;
        if( NULL != (newline = strchr( myPhoneBook[i].name, '\n' ) ) )
        {
            *newline = '\0';
        }
        scanf( "%lu",  &myPhoneBook[i].phone );
    }

    char query[MAX_NAME_LEN+2]; // +2 to allow for NUL byte and newline

    while ( fgets( query, sizeof(query), stdin ) )
    {
        if( query[0] == '\n' )
            break;

        char *newline;
        if( NULL != (newline = strchr( query, '\n' ) ) )
        {
            *newline = '\0';
        }

        size_t found = 0;

        for ( size_t j = 0; j < n; j++)
        {
            /*two pointers are being passed here,*/
            /* one to the line entered and       */
            /* other to each character array pointed to by the pointer array*/
            if (strcmp( query, myPhoneBook[j].name ) == 0)
            {
                printf( "%s", myPhoneBook[j].name );
                printf( "=" );
                printf( "%lu", myPhoneBook[j].phone );
                found = 1;
                break;
            }
        }

        if ( !found ) //if record not found, print so
            printf("Not found");
        printf("\n");
    }

    return 0;
}
</code>```

Note:  printf() and scanf() are SLOW.  Suggest modifying the proposed code to use the following two functions, so never call printf() nor scanf():

```<code>void fastRead( size_t *a );
void fastWrite( size_t a );

inline void fastRead(size_t *a)
{
    int c=0;
    // note: 32 is space character
    // consume leading trash
    while (c<33) c=getchar_unlocked();

    // initialize result value
    *a=0;

    // punctuation parens, etc are show stoppers
    while (c>47 && c <58)
    { // then in range 0...9
        *a = (*a)*10 + (size_t)(c-48);
        c=getchar_unlocked();
    }
    //printf( "%s, value: %lu\n", __func__, *a );
} // end function: fastRead

inline void fastWrite(size_t a)
{
    char snum[20];
    //printf( "%s, %lu\n", __func__, a );

    int i=0;
    // decompose 'a' into char array
    do
    {
        // 48 is numeric character 0
        snum[i++] = (char)((a%10)+(size_t)48);
        a=a/10;
    }while(a>0);

    i=i-1; // correction for overincrement from prior 'while' loop

    while(i>=0)
    {
        putchar_unlocked(snum[i--]);
    }
    putchar_unlocked('\n');
} // end function: fastWrite
</code>```

Body:
int main() {

  int n, found, query_no = 0;
  unsigned long int *phone;

  char **str, query[30], c;

  scanf("%d", &n);

  str = (char**) malloc(sizeof(char*) * n); //creating a pointer array of strings

  phone = (unsigned long int*) malloc(sizeof(unsigned long int) * n);
  for (int i = 0; i < n; i++) {
    str[i] = (char*) malloc(sizeof(char) * 30); //iitializing each pointer in arry
  }
  for (int i = 0; i < n; i++) {
    scanf("%s", *(str + i));
    scanf("%u", phone + i);
  }

  gets(query);
  char *p;
  p = query;

  while (*(p = gets(query)) != '\0')  //checks if blank line is entered
  {
    found = 0;
    for (int j = 0; j < n; j++) {
      /*two pointers are being passed here,*/
      /* one to the line entered and       */
      /* other to each character array pointed to by the pointer array*/
      if (strcmp(p, *(str + j)) == 0) {
        printf("%s", *(str + j));
        printf("=");
        printf("%u", *(phone + j));
        found = 1;
        break;
      }
    }
    if (found == 0) //if record not found, print so
      printf("Not found");
    printf("\n");
  }

The code inputs a phone book from user by first inputting the number of records to be inserted then in each new line a record is entered in the form of name number.  Then the user searches for an unknown number records and we print the name and number if the records is found otherwise we print not found.

Source : Hackerrank 30 days of code Day 8
(I hope I am not violating any rules here, please tell me if I am)

Body:
the following proposed code:

cleanly compiles

performs the desired function

avoids any use of the heap allocation functions, like malloc()

allows easy modification to the actual MAX value for 'n' via a #define statement.

allows easy modification to the max name length via a #define statement.

consolidates the data representation into a simple struct.

avoids calling functions (I.E. gets()) that has been removed from the C standard.

because it is a 'Hackerrank' item, does not perform error checking.

stops when a blank line is read for a 'query'

note the use of size_t rather than int as the values are never <0

And now the proposed code:

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

#define MAX_NAMES 500
#define MAX_NAME_LEN 30

struct phoneBook
{
    char name[ MAX_NAME_LEN + 1]; // +1 to allow for NUL terminator
    unsigned long phone;
};

struct phoneBook myPhoneBook[ MAX_NAMES ];

int main( void )
{
    size_t n;

    scanf("%lu", &n);

    for (size_t i = 0; i < n; i++)
    {
        scanf( "%29s", myPhoneBook[i].name );
        char *newline;
        if( NULL != (newline = strchr( myPhoneBook[i].name, '\n' ) ) )
        {
            *newline = '\0';
        }
        scanf( "%lu",  &myPhoneBook[i].phone );
    }

    char query[MAX_NAME_LEN+2]; // +2 to allow for NUL byte and newline

    while ( fgets( query, sizeof(query), stdin ) )
    {
        if( query[0] == '\n' )
            break;

        char *newline;
        if( NULL != (newline = strchr( query, '\n' ) ) )
        {
            *newline = '\0';
        }

        size_t found = 0;

        for ( size_t j = 0; j < n; j++)
        {
            /*two pointers are being passed here,*/
            /* one to the line entered and       */
            /* other to each character array pointed to by the pointer array*/
            if (strcmp( query, myPhoneBook[j].name ) == 0)
            {
                printf( "%s", myPhoneBook[j].name );
                printf( "=" );
                printf( "%lu", myPhoneBook[j].phone );
                found = 1;
                break;
            }
        }

        if ( !found ) //if record not found, print so
            printf("Not found");
        printf("\n");
    }

    return 0;
}

Note:  printf() and scanf() are SLOW.  Suggest modifying the proposed code to use the following two functions, so never call printf() nor scanf():

void fastRead( size_t *a );
void fastWrite( size_t a );

inline void fastRead(size_t *a)
{
    int c=0;
    // note: 32 is space character
    // consume leading trash
    while (c<33) c=getchar_unlocked();

    // initialize result value
    *a=0;

    // punctuation parens, etc are show stoppers
    while (c>47 && c <58)
    { // then in range 0...9
        *a = (*a)*10 + (size_t)(c-48);
        c=getchar_unlocked();
    }
    //printf( "%s, value: %lu\n", __func__, *a );
} // end function: fastRead

inline void fastWrite(size_t a)
{
    char snum[20];
    //printf( "%s, %lu\n", __func__, a );

    int i=0;
    // decompose 'a' into char array
    do
    {
        // 48 is numeric character 0
        snum[i++] = (char)((a%10)+(size_t)48);
        a=a/10;
    }while(a>0);

    i=i-1; // correction for overincrement from prior 'while' loop

    while(i>=0)
    {
        putchar_unlocked(snum[i--]);
    }
    putchar_unlocked('\n');
} // end function: fastWrite


问:
Pandas date_range with specific time ranges
I am trying to use pd.date_range() to create a DatetimeIndex that spans over multiple days with a frequency in seconds. However, the time range for each day should be restricted between 05:00:00 and 22:00:00

Something along the lines of (doesn't work of course):

```<code>times_c = pd.date_range(start="2015-01-01",end="2015-01-10",freq="S")
mask_c = ((times_c.time < dt.datetime.strptime("22:00:00", "%H:%M:%S")) | (times_c.time > dt.datetime.strptime("05:00:00","%H:%M:%S")))
times_c = times_c[mask_c]
</code>```

答:
Use indexer_between_time:

```<code>times_c[times_c.indexer_between_time('05:00:00', '22:00:00')]
</code>```

Body:
I am trying to use pd.date_range() to create a DatetimeIndex that spans over multiple days with a frequency in seconds. However, the time range for each day should be restricted between 05:00:00 and 22:00:00

Something along the lines of (doesn't work of course):

times_c = pd.date_range(start="2015-01-01",end="2015-01-10",freq="S")
mask_c = ((times_c.time
 dt.datetime.strptime("05:00:00","%H:%M:%S")))
times_c = times_c[mask_c]

Body:
Use indexer_between_time:

times_c[times_c.indexer_between_time('05:00:00', '22:00:00')]


问:
Using webpack HMR (Hot Module replacement) without the webpack-dev-server
I implemented the HMR with webpack and it works ok. When I change something I see in the console that it has updated but since I am using it for the server bundle I was wondering hot to send signal to browser to reload after HMR finishes, or better yet, how to do hot swap without refreshing the browser?

It works normally on client side where I use webpack-dev-server but on the server side where I use webpack/hot/poll I need to manually refresh after every change to see it in the browser?

webpack.config.server.js

```<code>module.exports = {
  ...
  watch: true,
  target: 'node',
  node: {
    __dirname: true,
    __filename: true
  },
  entry: {
    bundle: [
      'webpack/hot/poll?1000',
      './src/server/devServer'
    ]
  },
  output: {
    path: path.join(__dirname, 'src', 'build'),
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      CountdownForm: path.resolve(__dirname, 'src/client/scenes/countdown/components/CountdownForm.jsx'),
     ...
    }
  },
  externals: [nodeExternals({
    whitelist: ['webpack/hot/poll?1000']
  })],
 ...
  plugins: [
    new StartServerPlugin('bundle.js'),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new HtmlWebpackPlugin({
      title: 'React Timer',
      template: 'ejs-loader!./src/server/views/index.ejs'
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development')
      }
    })
  ]
}
</code>```

devServer

```<code>const server = http.createServer(app)
let currentApp = app

server.listen(PORT, () => {
  console.log(`
  Express server is up on port ${PORT}
  Development environment - Webpack HMR active
  `)
})

if (module.hot) {
  module.hot.accept('./index', () => {
    server.removeListener('request', currentApp)
    currentApp = app
    server.on('request', app)
  })
}
</code>```

答:
webpack-dev-server sets up a server that will transmit changes to any listening client. If you're writing your own server application, it won't be a client of the webpack server. Instead, you'll want to add webpack to the server so your client can connect to it and get updates. You'll need two things for this:

https://github.com/webpack/webpack-dev-middleware

https://github.com/glenjamin/webpack-hot-middleware

The first allows webpack to bundle your code and serve it up from your server app. The second allows it to transmit HMR updates to the client.

Note: webpack-dev-server actually uses webpack-dev-middleware internally. It's basically just a pre-configured version of the middleware.

Body:
I implemented the HMR with webpack and it works ok. When I change something I see in the console that it has updated but since I am using it for the server bundle I was wondering hot to send signal to browser to reload after HMR finishes, or better yet, how to do hot swap without refreshing the browser?

It works normally on client side where I use webpack-dev-server but on the server side where I use webpack/hot/poll I need to manually refresh after every change to see it in the browser?

webpack.config.server.js

module.exports = {
  ...
  watch: true,
  target: 'node',
  node: {
    __dirname: true,
    __filename: true
  },
  entry: {
    bundle: [
      'webpack/hot/poll?1000',
      './src/server/devServer'
    ]
  },
  output: {
    path: path.join(__dirname, 'src', 'build'),
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      CountdownForm: path.resolve(__dirname, 'src/client/scenes/countdown/components/CountdownForm.jsx'),
     ...
    }
  },
  externals: [nodeExternals({
    whitelist: ['webpack/hot/poll?1000']
  })],
 ...
  plugins: [
    new StartServerPlugin('bundle.js'),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new HtmlWebpackPlugin({
      title: 'React Timer',
      template: 'ejs-loader!./src/server/views/index.ejs'
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development')
      }
    })
  ]
}

devServer

const server = http.createServer(app)
let currentApp = app

server.listen(PORT, () => {
  console.log(`
  Express server is up on port ${PORT}
  Development environment - Webpack HMR active
  `)
})

if (module.hot) {
  module.hot.accept('./index', () => {
    server.removeListener('request', currentApp)
    currentApp = app
    server.on('request', app)
  })
}


问:
Use KONG as API Gateway to GraphQL/REST services
I'm trying to understand if it's possible to use KONG as API Gateway to microservices implementing REST and/or GraphQL interfaces

As API Gateway will expose a GraphQL API and will request to our microservices currently implemented in REST/GraphQL and grpc coming soon.

答: Kong can front any RESTful API and through a transformation plugin you should be able to deal with GraphQL API as well.</p>


问:
I need a way to see which of my db tables are not empty, but I am strugling with the syntax a bit
I use a reference table that references schemas (table names) by schemaid.
I need to run a SELECT count() from T(table) where count() > 0
But only for those tables with CORE:Table in the name. The substitution for the (table) I thought I could do by DECLARING @schemaset and then use the while loop to process it. I am more used to FOR loop, but MSSQL does not seem to have that.

```<code>DECLARE @schemaset VARCHAR

WHILE @schemaset in (select schemaId from arschema where name like 'CORE:Table%')

BEGIN
  select COUNT(*) from T(@schemaset)where FIELD1 IS NOT NULL
END
</code>```

Query runs, but it says it completed successfully. I tried PRINT to see the results, but that complained with an error.

So, how do I get a full/empty check on a set of specific tables?

答:
Here's an example of SQL that will return all empty tables:

```<code>-- All Empty Tables
CREATE TABLE #counts (table_name sysname,row_count int)

EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'
SELECT table_name AS EmptyTables, row_count
FROM #counts
WHERE row_count = 0
ORDER BY table_name
DROP TABLE #counts
GO
</code>```

A different strategy that doesn't rely on the undocumented "sp_MSForEachTable" stored procedure, and which lets you filter which tables you want to examine, looks something like this:

```<code>DECLARE @sql nvarchar(max);
CREATE TABLE #Counts (Table_Name sysname, Row_Count int);
SET @sql = N'';
SELECT @sql += N'INSERT INTO #Counts (Table_Name, Row_Count) SELECT ''' + TABLE_NAME +
               N''', COUNT(1) FROM ' + QUOTENAME(TABLE_NAME) + N'; '
  FROM INFORMATION_SCHEMA.TABLES
 WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'dbo' AND TABLE_NAME LIKE N'A%'
PRINT @sql;
EXEC(@sql);
SELECT * FROM #Counts
DROP TABLE #Counts
</code>```

The SELECT statement filters the list of tables to only those in the 'dbo' schema, and only those that start with the letter 'A'.  You can alter this to fit your needs, filtering for any tables you wish.

Basically what this code is doing is building up a series of INSERT statements for each table, inserting the COUNT and the table name into the temporary table. You can massage this to do any sort of thing you wish... this is purely an example.

Body:
I use a reference table that references schemas (table names) by schemaid.
I need to run a SELECT count() from T(table) where count() > 0
But only for those tables with CORE:Table in the name. The substitution for the (table) I thought I could do by DECLARING @schemaset and then use the while loop to process it. I am more used to FOR loop, but MSSQL does not seem to have that.

DECLARE @schemaset VARCHAR

WHILE @schemaset in (select schemaId from arschema where name like 'CORE:Table%')

BEGIN
  select COUNT(*) from T(@schemaset)where FIELD1 IS NOT NULL
END

Query runs, but it says it completed successfully. I tried PRINT to see the results, but that complained with an error.

So, how do I get a full/empty check on a set of specific tables?

Body:
Here's an example of SQL that will return all empty tables:

-- All Empty Tables
CREATE TABLE #counts (table_name sysname,row_count int)

EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'
SELECT table_name AS EmptyTables, row_count
FROM #counts
WHERE row_count = 0
ORDER BY table_name
DROP TABLE #counts
GO

A different strategy that doesn't rely on the undocumented "sp_MSForEachTable" stored procedure, and which lets you filter which tables you want to examine, looks something like this:

DECLARE @sql nvarchar(max);
CREATE TABLE #Counts (Table_Name sysname, Row_Count int);
SET @sql = N'';
SELECT @sql += N'INSERT INTO #Counts (Table_Name, Row_Count) SELECT ''' + TABLE_NAME +
               N''', COUNT(1) FROM ' + QUOTENAME(TABLE_NAME) + N'; '
  FROM INFORMATION_SCHEMA.TABLES
 WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA = 'dbo' AND TABLE_NAME LIKE N'A%'
PRINT @sql;
EXEC(@sql);
SELECT * FROM #Counts
DROP TABLE #Counts

The SELECT statement filters the list of tables to only those in the 'dbo' schema, and only those that start with the letter 'A'.  You can alter this to fit your needs, filtering for any tables you wish.

Basically what this code is doing is building up a series of INSERT statements for each table, inserting the COUNT and the table name into the temporary table. You can massage this to do any sort of thing you wish... this is purely an example.