问:
How to avoid code repetition using a 3rd party web service - without using dynamic?
I'm using a 3rd party web service where all it's methods have the following signature:

```<code>SomeResponseClass SomeMethod(SomeRequestClass request)
</code>```

Every method has it's own request class and it's own response class, However there are a few things that all requests have in common, and all responses have in common.

Every request class has a couple of properties for identification: username and token, and every response class have a couple of properties to indicate if there was an error: status and error.

I'm looking for an elegant way to create a method that will instantiate my requests - so that I will not have to repeat myself in every method calling the service. Since I can't change the classes, and there is no common interface or base class to all of them, the only solution I found was to use dynamic:

```<code>private T CreateRequest<T>() where T : new()
{
    if(string.IsNullOrEmpty(_Token))
    {
        Login();
    }
    // this has to be dynamic for the next 2 rows to pass compilation.
    dynamic request = new T();
    request.username = _UserName;
    request.token = _Token;
    return (T)request;
}
</code>```

And something similar to populate my own entities from the service responses:

```<code>// response have to be dynamic for getting the error and status properties
private static T CreateServiceResponse<T>(dynamic response) where T : ServiceResponse, new()
{
    T result = new T();
    result.Error = (response == null) ? "Service response is null" : response.error;
    result.Status = (response == null) ? -1 : response.status;
    return result;
}
</code>```

(This method is used inside every method that I use to populate my entities (all derived from ServiceResponse) with the data from the service response.)

Is there any way to do something like this without using dynamic?
To me, it kinda feels like using a dirty hack...

If I could somehow "inject" a common interface for all requests to implement and a common interface for all responses to implement I could use simple Generics, but I guess that's impossible, or is it?

答:
When you are using service references created by visual studio, all generated classes are marked as partial. That means you can extend them with your own code. In your case that would be an interface that provides the repetitive properties. You can use that interface as a generic constraint.

You first create the common interface. To make things easy, you use the same name and type for your common properties as defined in the service reference:

```<code>interface IRequest {
    string username { get; set; }
    string token { get; set; }
}
</code>```

You then create a code file and in the same namespace as the service reference you define a partial class for each service request class (with the same name). Each of these classes implements your interface:

```<code>partial class SomeRequestClass : IRequest {}
</code>```

Having chosen the same property names and types, you don‘t have to specifically implement the interface.

Finally you use generic constraints:

```<code>private T CreateRequest<T>() where T : IRequest, new()
{
    if(string.IsNullOrEmpty(_Token))
    {
        Login();
    }
    T request = new T();
    request.username = _UserName;
    request.token = _Token;
    return request;
}
</code>```

Body:
I'm using a 3rd party web service where all it's methods have the following signature:

SomeResponseClass SomeMethod(SomeRequestClass request)

Every method has it's own request class and it's own response class, However there are a few things that all requests have in common, and all responses have in common.

Every request class has a couple of properties for identification: username and token, and every response class have a couple of properties to indicate if there was an error: status and error.

I'm looking for an elegant way to create a method that will instantiate my requests - so that I will not have to repeat myself in every method calling the service. Since I can't change the classes, and there is no common interface or base class to all of them, the only solution I found was to use dynamic:

private T CreateRequest<T>() where T : new()
{
    if(string.IsNullOrEmpty(_Token))
    {
        Login();
    }
    // this has to be dynamic for the next 2 rows to pass compilation.
    dynamic request = new T();
    request.username = _UserName;
    request.token = _Token;
    return (T)request;
}

And something similar to populate my own entities from the service responses:

// response have to be dynamic for getting the error and status properties
private static T CreateServiceResponse<T>(dynamic response) where T : ServiceResponse, new()
{
    T result = new T();
    result.Error = (response == null) ? "Service response is null" : response.error;
    result.Status = (response == null) ? -1 : response.status;
    return result;
}

(This method is used inside every method that I use to populate my entities (all derived from ServiceResponse) with the data from the service response.)

Is there any way to do something like this without using dynamic?
To me, it kinda feels like using a dirty hack...

If I could somehow "inject" a common interface for all requests to implement and a common interface for all responses to implement I could use simple Generics, but I guess that's impossible, or is it?

Body:
When you are using service references created by visual studio, all generated classes are marked as partial. That means you can extend them with your own code. In your case that would be an interface that provides the repetitive properties. You can use that interface as a generic constraint.

You first create the common interface. To make things easy, you use the same name and type for your common properties as defined in the service reference:

interface IRequest {
    string username { get; set; }
    string token { get; set; }
}

You then create a code file and in the same namespace as the service reference you define a partial class for each service request class (with the same name). Each of these classes implements your interface:

partial class SomeRequestClass : IRequest {}

Having chosen the same property names and types, you don‘t have to specifically implement the interface.

Finally you use generic constraints:

private T CreateRequest<T>() where T : IRequest, new()
{
    if(string.IsNullOrEmpty(_Token))
    {
        Login();
    }
    T request = new T();
    request.username = _UserName;
    request.token = _Token;
    return request;
}


来源: stackexchange

问:
Laravel File Uploads Error: Missing a temporary folder
I'm running a server with Ubuntu 16.04, ISPConfig and Laravel. For tests I got a local Testserver with basically the same settings. Testserver has another domain and no https. I've integrated File Uploads for Laravel on my Testserver. I use http://image.intervention.io/ and it works fine on my Testserver.

The Liveserver fails with it. Can't pass "hasFile" function.

Form:

```<code><div class="form-group">
  <div class="row">
    <div class="col-md-10 col-md-offset-1">
      <img src="/uploads/avatars/{{$user->avatar}}" style="width:150px;
       height:150px; float:left; border-radius:50%; margin-
       right:25px;">
      <form enctype="multipart/form-data"
       action="/account/edit/upload_avatar" method="post">
        <input type="file" name="avatar">
        {{ csrf_field() }}
        <input type="submit" class="pull-right btn btn-sm btn-primary">
      </form>
    </div>
  </div>
</div>
</code>```

Controller:

```<code> public function upload_avatar(Request $request)
 {
    dd($request);

    if($request->hasFile('avatar')) {
      $avatar = $request->file('avatar');
      $filename = time() . '.' . $avatar->getClientOriginalExtension();
      Image::make($avatar)->resize(300, 300)->save(
      public_path('uploads/avatars/' . $filename));

      $user = Sentinel::getUser();
      $user->avatar = $filename;
      $user->save();

      return back();
    }
  }
</code>```

Request:

```<code>Request {#39 ▼
#json: null
#convertedFiles: null
#userResolver: Closure {#330 ▶}
#routeResolver: Closure {#322 ▶}
+attributes: ParameterBag {#41 ▶}
+request: ParameterBag {#40 ▶}
+query: ParameterBag {#47 ▶}
+server: ServerBag {#44 ▶}
+files: FileBag {#43 ▼
#parameters: array:1 [▼
  "avatar" => UploadedFile {#28 ▼
    -test: false
    -originalName: "2.jpg"
    -mimeType: "application/octet-stream"
    -size: 0
    -error: 6
    path: ""
    filename: ""
    basename: ""
    pathname: ""
    extension: ""
    realPath: "/var/www/clients/client1/web1/web/public"
    aTime: 1970-01-01 00:00:00
    mTime: 1970-01-01 00:00:00
    cTime: 1970-01-01 00:00:00
    inode: false
    size: false
    perms: 00
    owner: false
    group: false
    type: false
    writable: false
    readable: false
    executable: false
    file: false
    dir: false
    link: false
      }
    ]
  }
  +cookies: ParameterBag {#42 ▶}
  +headers: HeaderBag {#45 ▶}
  #content: null
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: "/account/edit/upload_avatar"
  #requestUri: "/account/edit/upload_avatar"
  #baseUrl: ""
  #basePath: null
  #method: "POST"
  #format: null
  #session: Store {#375 ▶}
  #locale: null
  #defaultLocale: "en"
  -isHostValid: true
  -isClientIpsValid: true
  -isForwardedValid: true
  basePath: ""
  format: "html"
  }
</code>```

error:6
UPLOAD_ERR_NO_TMP_DIR

Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP

Php.ini has the same settings for file uploads as the Testserver.
This is from my php.ini:

```<code>    ;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default
 if not
; specified).
; http://php.net/upload-tmp-dir
;upload_tmp_dir =

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20
</code>```

Without the if(hasFile) iIget the following:

```<code>NotReadableException
Unsupported image type. GD driver is only able to decode JPG, PNG, GIF
or WebP files.
</code>```

I've already checked the file permissions for the whole project and even tried it with 777 on the file destination.

答: I know, thanks! Solved it now. Tmp folder Hand wrong permissions.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm running a server with Ubuntu 16.04, ISPConfig and Laravel. For tests I got a local Testserver with basically the same settings. Testserver has another domain and no https. I've integrated File Uploads for Laravel on my Testserver. I use http://image.intervention.io/ and it works fine on my Testserver.

The Liveserver fails with it. Can't pass "hasFile" function.

Form:

      avatar}}" style="width:150px;
       height:150px; float:left; border-radius:50%; margin-
       right:25px;">
      <form enctype="multipart/form-data"
       action="/account/edit/upload_avatar" method="post">
        <input type="file" name="avatar">
        {{ csrf_field() }}
        <input type="submit" class="pull-right btn btn-sm btn-primary">
      </form>

Controller:

 public function upload_avatar(Request $request)
 {
    dd($request);

    if($request->hasFile('avatar')) {
      $avatar = $request->file('avatar');
      $filename = time() . '.' . $avatar->getClientOriginalExtension();
      Image::make($avatar)->resize(300, 300)->save(
      public_path('uploads/avatars/' . $filename));

      $user = Sentinel::getUser();
      $user->avatar = $filename;
      $user->save();

      return back();
    }
  }

Request:

Request {#39 ▼
#json: null
#convertedFiles: null
#userResolver: Closure {#330 ▶}
#routeResolver: Closure {#322 ▶}
+attributes: ParameterBag {#41 ▶}
+request: ParameterBag {#40 ▶}
+query: ParameterBag {#47 ▶}
+server: ServerBag {#44 ▶}
+files: FileBag {#43 ▼
#parameters: array:1 [▼
  "avatar" => UploadedFile {#28 ▼
    -test: false
    -originalName: "2.jpg"
    -mimeType: "application/octet-stream"
    -size: 0
    -error: 6
    path: ""
    filename: ""
    basename: ""
    pathname: ""
    extension: ""
    realPath: "/var/www/clients/client1/web1/web/public"
    aTime: 1970-01-01 00:00:00
    mTime: 1970-01-01 00:00:00
    cTime: 1970-01-01 00:00:00
    inode: false
    size: false
    perms: 00
    owner: false
    group: false
    type: false
    writable: false
    readable: false
    executable: false
    file: false
    dir: false
    link: false
      }
    ]
  }
  +cookies: ParameterBag {#42 ▶}
  +headers: HeaderBag {#45 ▶}
  #content: null
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: "/account/edit/upload_avatar"
  #requestUri: "/account/edit/upload_avatar"
  #baseUrl: ""
  #basePath: null
  #method: "POST"
  #format: null
  #session: Store {#375 ▶}
  #locale: null
  #defaultLocale: "en"
  -isHostValid: true
  -isClientIpsValid: true
  -isForwardedValid: true
  basePath: ""
  format: "html"
  }

error:6
UPLOAD_ERR_NO_TMP_DIR

Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP

Php.ini has the same settings for file uploads as the Testserver.
This is from my php.ini:

    ;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default
 if not
; specified).
; http://php.net/upload-tmp-dir
;upload_tmp_dir =

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20

Without the if(hasFile) iIget the following:

NotReadableException
Unsupported image type. GD driver is only able to decode JPG, PNG, GIF
or WebP files.

I've already checked the file permissions for the whole project and even tried it with 777 on the file destination.

ContentLicense: CC BY-SA 3.0


问:
PHP - Create a folder and put a file in it
I need to put a file in a folder named after the current date (Ex : folderbefore/2017-11-15/mynewfile.sql).

I tried :

change folderbefore to 777 in the server (I know it's not good, but I tried it and anyway it doesn't work)

add www-data to the owner group of folderbefore

set the umask to 0 before creating the folder :

```<code>$old = umask(0);
$directory_was_created = mkdir($path, 0777);
umask($old);
</code>```

I tried adding chmod after to change the permission

```<code>$old = umask(0);
$directory_was_created = mkdir($path, 0777);
chmod($path, 0777);
umask($old);
</code>```

I'm always getting a folder with 775 permissions and no right to write in this newly created folder (tried with file_put_content who gives me FALSE and fopen who's throwing an error).

What am I missing ?

答:
Ok I found the problem right after I posted the question.

I'm working on a test server on a vagrant machine. In order to give my computer access to folderbefore, I needed to add this in my Vagrantfile and restart the machine :

```<code>config.vm.synced_folder "path/to/folderbefore", "path/to/folderbefore/on/my/computer", id: "unique-id-for-this-folder",
owner: "vagrant",
group: "vagrant",
mount_options: ["dmode=777,fmode=777"]
</code>```

Body:
I need to put a file in a folder named after the current date (Ex : folderbefore/2017-11-15/mynewfile.sql).

I tried :

change folderbefore to 777 in the server (I know it's not good, but I tried it and anyway it doesn't work)

add www-data to the owner group of folderbefore

set the umask to 0 before creating the folder :

$old = umask(0);
$directory_was_created = mkdir($path, 0777);
umask($old);

I tried adding chmod after to change the permission

$old = umask(0);
$directory_was_created = mkdir($path, 0777);
chmod($path, 0777);
umask($old);

I'm always getting a folder with 775 permissions and no right to write in this newly created folder (tried with file_put_content who gives me FALSE and fopen who's throwing an error).

What am I missing ?

Body:
Ok I found the problem right after I posted the question.

I'm working on a test server on a vagrant machine. In order to give my computer access to folderbefore, I needed to add this in my Vagrantfile and restart the machine :

config.vm.synced_folder "path/to/folderbefore", "path/to/folderbefore/on/my/computer", id: "unique-id-for-this-folder",
owner: "vagrant",
group: "vagrant",
mount_options: ["dmode=777,fmode=777"]


问:
POST versus Ajax call
Now that most modern browsers support AJAX and client-side requests without performing a POST, what is the role of POST (form post)?

Are there situations or general rules when a POST will always be preferred to a XmlHttpRequest?

All that POST is doing is placing variable key value pairs inside the server head. The advantages of POST I can think of are large amounts of data and mobile browsers. Are there many others I'm missing?

N.B. I know you can perform POSTs with AJAX calls, I'm talking primarily about with a <form> tag

答:
If theory, an HTTP GET should be an idempotent request for information: Two identical GETs should return the exact same information.

HTTP POSTs, on the other hand, are intended to hold state and perform actions: Two identical POSTs maybe perform different action depending on who doing it, what was done before, and when it is being done.

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Title: POST versus Ajax call

OwnerDisplayName: James Curran


问:
Build a UIView in Interface Builder
There are similar posts about this topic, but my situation seems to be a little different. With that said, it also feels like it should be a common problem to overcome.

I have a view controller (StatsViewController) that has a blank UIScrollView at the moment. What I'd like to do is create a custom UIView class, and lay it out using Interface Builder and then have the StatsViewController use this view multiple times. But it's an unknown number of times currently. Basically, the StatsViewController will be pulling in some JSON from a web service, looping through the service, and for each "loop" I'd like to instantiate a new view using my custom UIView and add it to the UIScrollView within the StatsViewController.

My problem is when I create the UIView in interface builder, I can't figure out how to instantiate it using the nib through the loop. I read that you load view controllers using a nib, and not plain UIView's... but at the same time, I read that you can't (or shouldn't) have nested UIViewControllers, so I'm at a loss.

If I create a custom view in Interface Builder, how can I instantiate it multiple times on the same view controller?

答:
A simple trick to get what you want is the same way you'd implement a UITableViewCell in Interface Builder.

In Interface Builder, set the file owner to UIViewController, load your nib, and then grab that view controller's view. You can then (so long as you retain the view), get rid of the VC.

So what I suggest you do, is watch the first 2/3 of the WWDC10 session 104, to get an idea how to implement cell reuse. Then if you want to implement your cells in IB, use the above method (there are other ways to do it too, but they're all hackish), you can do that.

Title: Build a UIView in Interface Builder


问:
fade in/out highlight to zebra striped table
I have a table with a number of data rows, which is zebra striped using the following CSS:

```<code>#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}
</code>```

The data in the table is continually updated via ajax calls, and I want to add a temporary highlight to particular rows where data has changed.

I want this new colour (red if the data value has decreased, green if the data value has increased), to nicely fade in, stay for a second or two, then fade back out to the original row colour again.

I have this working just now using jQuery and CSS;

```<code>$('#row_id').addClass("temphighlight");
setTimeout(clearHighlighting, 3000);

function clearHighlighting(){
$("#row_id").removeClass("temphighlight");
}

#datatable tr.temphighlight {
background-color: #c6efce;
transition: background 1.0s ease;
}
</code>```

This works for the fade in, but after the delay, the CSS class is removed immediately and there is no fade out.

How can I get this highlighting to have a better effect, where it fades in and also fades out?

I have checked several similar SO questions, but the answers either don't work or don't apply - such as suggestions that you animate a fade to white, which doesn't work for me because my rows are alternatively coloured differently due to the row striping.

答:
Something like this?

.table{
  border: 1px solid #eee;
}

.table .row{
  padding: 10px;
  box-sizing: border-box;
}

.table .row:nth-child(odd) {
background-color: #fff;
}

.table .row:nth-child(even) {
background-color: #fafafa;
}

.table .row.increased{
  animation: 1s increased;
}

.table .row.decreased{
  animation: 1s decreased;
}

@keyframes increased{
  0%{
    background: initial;
  }
  50%{
    background: #a2ffa9;
  }
  100%{
    background: initial;
  }
}

@keyframes decreased{
  0%{
    background: initial;
  }
  50%{
    background: #ff6f6f;
  }
  100%{
    background: initial;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table">
  <div class="row increased">
  row
  </div>
  <div class="row">
  row
  </div>
  <div class="row">
  row
  </div>
  <div class="row decreased">
  row
  </div>
</div></code>```

Body:
I have a table with a number of data rows, which is zebra striped using the following CSS:

#datatable tr:nth-child(odd) {
background-color: #fff;
}

#datatable tr:nth-child(even) {
background-color: #fafafa;
}

The data in the table is continually updated via ajax calls, and I want to add a temporary highlight to particular rows where data has changed.

I want this new colour (red if the data value has decreased, green if the data value has increased), to nicely fade in, stay for a second or two, then fade back out to the original row colour again.

I have this working just now using jQuery and CSS;

$('#row_id').addClass("temphighlight");
setTimeout(clearHighlighting, 3000);

function clearHighlighting(){
$("#row_id").removeClass("temphighlight");
}

#datatable tr.temphighlight {
background-color: #c6efce;
transition: background 1.0s ease;
}

This works for the fade in, but after the delay, the CSS class is removed immediately and there is no fade out.

How can I get this highlighting to have a better effect, where it fades in and also fades out?

I have checked several similar SO questions, but the answers either don't work or don't apply - such as suggestions that you animate a fade to white, which doesn't work for me because my rows are alternatively coloured differently due to the row striping.

Body:
Something like this?

.table{
  border: 1px solid #eee;
}

.table .row{
  padding: 10px;
  box-sizing: border-box;
}

.table .row:nth-child(odd) {
background-color: #fff;
}

.table .row:nth-child(even) {
background-color: #fafafa;
}

.table .row.increased{
  animation: 1s increased;
}

.table .row.decreased{
  animation: 1s decreased;
}

@keyframes increased{
  0%{
    background: initial;
  }
  50%{
    background: #a2ffa9;
  }
  100%{
    background: initial;
  }
}

@keyframes decreased{
  0%{
    background: initial;
  }
  50%{
    background: #ff6f6f;
  }
  100%{
    background: initial;
  }
}

<div class="table">
  <div class="row increased">
  row
  </div>
  <div class="row">
  row
  </div>
  <div class="row">
  row
  </div>
  <div class="row decreased">
  row
  </div>
</div>


问:
TFS 2017 - NuGet Publisher step during a build fails with 401 Unauthorized
I have a build definition that includes steps to package and publish a NuGet package to an internal feed. That internal feed resides on the same TFS server.

This is on prem

TFS 2017 15.105.25910.0

Permissions for the feed are:

OWNERS:

[My account]

[Collection]\Project Collection Administrators

Contributors

Project Collection Build Service(TEAM FOUNDATION)

Readers

[Collection]\Project Collection Valid Users

The NuGet package step works fine, but the NuGet publish step fails with the following error:

```<code>Unable to load the service index for source https://[server]/[collection]/_packaging/Feed/nuget/v3/index.json.
Response status code does not indicate success: 401 (Unauthorized).
</code>```

I put in a Powershell script early in the build definition to determine the exact account being used during the build process, and it indicated Project Collection Build Service (TEAM FOUNDATION), which has permission to contribute to the feed.

Here are the contents of the Nuget.Config file at C:\Windows\ServiceProfiles\NetworkService\AppData\Roaming\NuGet>

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <disabledPackageSources>
    <add key="Microsoft Visual Studio Offline Packages" value="true" />
  </disabledPackageSources>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>
</code>```

What other information would be useful to help me diagnose with issue?

答:
Do you have Basic Authentication enabled in IIS for the tfs website? This was the cause of the problem for my TFS 2017.2 instance. Once I disabled it, the build went through successfully.

"TFS expects IIS level basic auth setting to be Off."

https://developercommunity.visualstudio.com/content/problem/110312/tfs2017-build-nuget-unable-to-restore-package-from.html

Body:
I have a build definition that includes steps to package and publish a NuGet package to an internal feed. That internal feed resides on the same TFS server.

This is on prem

TFS 2017 15.105.25910.0

Permissions for the feed are:

OWNERS:

[My account]

[Collection]\Project Collection Administrators

Contributors

Project Collection Build Service(TEAM FOUNDATION)

Readers

[Collection]\Project Collection Valid Users

The NuGet package step works fine, but the NuGet publish step fails with the following error:

Unable to load the service index for source https://[server]/[collection]/_packaging/Feed/nuget/v3/index.json.
Response status code does not indicate success: 401 (Unauthorized).

I put in a Powershell script early in the build definition to determine the exact account being used during the build process, and it indicated Project Collection Build Service (TEAM FOUNDATION), which has permission to contribute to the feed.

Here are the contents of the Nuget.Config file at C:\Windows\ServiceProfiles\NetworkService\AppData\Roaming\NuGet>

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <disabledPackageSources>
    <add key="Microsoft Visual Studio Offline Packages" value="true" />
  </disabledPackageSources>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</configuration>

What other information would be useful to help me diagnose with issue?


问:
calculate average using onchange event handler
I need to calculate the average of 5 numbers using onchange event handler. I'm new to coding and don't fully understand how onchange works. I also am confused on how to have the return # for my calcAvg function displayin my in 'result' box</p>

```<code><! doctype html >

<html lang = "en">
<head>
<title> Calculate Average </title>
</head>

<body>
    Number 1:<input type="number" id="number 1" Value="0"
onchange="calcAvg()"> </br> //do I put anything in between the ()of
onchange?
    Number 2:<input type="number" id="number 2" Value="0"
onchange="calcAvg()"> </br>
    Number 3:<input type="number" id="number 3" Value="0"
onchange="calcAvg()"> </br>
    Number 4:<input type="number" id="number 4" Value="0"
onchange="calcAvg()"> </br>
    Number 5:<input type="number" id="number 5" Value="0"
onchange="calcAvg()"> </br>
    Result :<input type=" number" id="result"> </br>
    <input type= 'button' value='calculate' id= 'calculate'>
    <div id= "result"> </div>//

    <script>
        function calcAvg ( number 1, number 2 ,number 3, number 4, number 5)
{
        return ((number 1 + number 2 +number 3+ number 4+ number 5)/5)
        }
    </script>

</body>
</html>
</code>```

答:
```<code><html lang = "en">
<head>
<title> Calculate Average </title>
</head>

<body>
   Number 1:<input type="number" id="number1" Value="0"
   onchange="calcAvg()"> </br>
   Number 2:<input type="number" id="number2" Value="0"
   onchange="calcAvg()"> </br>
   Number 3:<input type="number" id="number3" Value="0"
   onchange="calcAvg()"> </br>
   Number 4:<input type="number" id="number4" Value="0"
   onchange="calcAvg()"> </br>
   Number 5:<input type="number" id="number5" Value="0"
   onchange="calcAvg()"> </br>
   Result :<input type=" number" id="result"> </br>
<input type= 'button' onClick="calcAvg()" id= 'calculate'>
<div id="result"> </div>//

 <script>
    function calcAvg () {
     var num1 = document.getElementById("number1").val() || 0;
     var num2 = document.getElementById("number2").val() || 0;
     var num3 = document.getElementById("number3").val() || 0;
     var num4 = document.getElementById("number4").val() || 0;
     var num5 = document.getElementById("number5").val() || 0;

     document.getElementById("result").value=((num1 + num2 +num3+ num4+
     num5)/5);
    }
</script>
</code>```

grab the values from the inputs by their id's and average those values. call the function from the on change attribute. you can call the same function from onclick for the button. set the value by grabbing results ID and adding value to it.

Body:
I need to calculate the average of 5 numbers using onchange event handler. I'm new to coding and don't fully understand how onchange works. I also am confused on how to have the return # for my calcAvg function displayin my in 'result' box

<! doctype html >

<title> Calculate Average </title>

    Number 1:<input type="number" id="number 1" Value="0"
onchange="calcAvg()">
 //do I put anything in between the ()of
onchange?
    Number 2:<input type="number" id="number 2" Value="0"
onchange="calcAvg()">

    Number 3:<input type="number" id="number 3" Value="0"
onchange="calcAvg()">

    Number 4:<input type="number" id="number 4" Value="0"
onchange="calcAvg()">

    Number 5:<input type="number" id="number 5" Value="0"
onchange="calcAvg()">

    Result :<input type=" number" id="result">

    <input type= 'button' value='calculate' id= 'calculate'>

//

Body:
<html lang = "en">
<head>
<title> Calculate Average </title>
</head>

<body>
   Number 1:<input type="number" id="number1" Value="0"
   onchange="calcAvg()"> </br>
   Number 2:<input type="number" id="number2" Value="0"
   onchange="calcAvg()"> </br>
   Number 3:<input type="number" id="number3" Value="0"
   onchange="calcAvg()"> </br>
   Number 4:<input type="number" id="number4" Value="0"
   onchange="calcAvg()"> </br>
   Number 5:<input type="number" id="number5" Value="0"
   onchange="calcAvg()"> </br>
   Result :<input type=" number" id="result"> </br>
<input type= 'button' onClick="calcAvg()" id= 'calculate'>
<div id="result"> </div>//

 <script>
    function calcAvg () {
     var num1 = document.getElementById("number1").val() || 0;
     var num2 = document.getElementById("number2").val() || 0;
     var num3 = document.getElementById("number3").val() || 0;
     var num4 = document.getElementById("number4").val() || 0;
     var num5 = document.getElementById("number5").val() || 0;

     document.getElementById("result").value=((num1 + num2 +num3+ num4+
     num5)/5);
    }
</script>

grab the values from the inputs by their id's and average those values. call the function from the on change attribute. you can call the same function from onclick for the button. set the value by grabbing results ID and adding value to it.


问:
How can I schedule an email to be sent at some point in the future in django?
I want to schedule an email to be sent to a user upon a specific action.
However, if the user takes another action I want to cancel that email and have it not send.

How would I do that in django or python?

答: Are your using celery ? If true, see http://ask.github.com/celery/userguide/executing.html#eta-and-countdown</p>


问:
Jupyter: Programmatically Clear Output from all Cells when Kernel is Ready
I have a question on how to programmatically  clear\clean the output from all the Cells in my Jupyter notebook after notebook is done loading (when Kernel is ready), and prior to the user, myself, manually executing code. Basically, I would like the notebook to look clean when it is done loading, and I would like to do it automatically.

How can I impose a command like clear_output() from a single initialization cell on to all other cells in the notebook?

Thank you.

答:
For a trusted notebook (see http://jupyter-notebook.readthedocs.io/en/stable/security.html#Our-security-model for details on trusted/untrusted notebooks, but in brief, for this purpose, the relevant bit is that anything you have created on your machine should be trusted already), you could use a javascript cell at the beginning with something like:

require(['base/js/namespace', 'base/js/events'],
function (Jupyter, events) {
    // save a reference to the cell we're currently executing inside of,
    // to avoid clearing it later (which would remove this js)
    var this_cell = $(element).closest('.cell').data('cell');
    function clear_other_cells () {
        Jupyter.notebook.get_cells().forEach(function (cell) {
            if (cell.cell_type === 'code' && cell !== this_cell) {
                cell.clear_output();
            }
            Jupyter.notebook.set_dirty(true);
        });
    }

    if (Jupyter.notebook._fully_loaded) {
        // notebook has already been fully loaded, so clear now
        clear_other_cells();
    }
    // Also clear on any future load
    // (e.g. when notebook finishes loading, or when a checkpoint is reloaded)
    events.on('notebook_loaded.Notebook', clear_other_cells);
});
```

This won't function in a non-trusted notebook, for which javascript outputs are sanitized, but if you're creating the notebook, it should function ok. You could even wrap the whole thing up into an nbextension if you'd rather not have the cell in every notebook.

<shameless plug>
See https://github.com/ipython-contrib/jupyter_contrib_nbextensions for examples of nbextensions, or file an issue there to suggest adding something like this
</shameless plug>

Body:
For a trusted notebook (see http://jupyter-notebook.readthedocs.io/en/stable/security.html#Our-security-model for details on trusted/untrusted notebooks, but in brief, for this purpose, the relevant bit is that anything you have created on your machine should be trusted already), you could use a javascript cell at the beginning with something like:

require(['base/js/namespace', 'base/js/events'],
function (Jupyter, events) {
    // save a reference to the cell we're currently executing inside of,
    // to avoid clearing it later (which would remove this js)
    var this_cell = $(element).closest('.cell').data('cell');
    function clear_other_cells () {
        Jupyter.notebook.get_cells().forEach(function (cell) {
            if (cell.cell_type === 'code' && cell !== this_cell) {
                cell.clear_output();
            }
            Jupyter.notebook.set_dirty(true);
        });
    }

    if (Jupyter.notebook._fully_loaded) {
        // notebook has already been fully loaded, so clear now
        clear_other_cells();
    }
    // Also clear on any future load
    // (e.g. when notebook finishes loading, or when a checkpoint is reloaded)
    events.on('notebook_loaded.Notebook', clear_other_cells);
});

This won't function in a non-trusted notebook, for which javascript outputs are sanitized, but if you're creating the notebook, it should function ok. You could even wrap the whole thing up into an nbextension if you'd rather not have the cell in every notebook.

<shameless plug>
See https://github.com/ipython-contrib/jupyter_contrib_nbextensions for examples of nbextensions, or file an issue there to suggest adding something like this
</shameless plug>


问:
PowerShell 5 Copy-Item not working
I am trying to copy all .pdf files from all folders and sub folder (dirs. and subdirs).

```<code>Folder1
  1.pdf
  2.pdf
Folder1\Foder2\3.pdf
Folder1\Folder2\4.pdf
Folder1\Foder2\Folder3\5.pdf
Folder1\Folder2\Folder3\6.pdf
</code>```

First I used

```<code> $source = "c:\Folder1\"
 $desti = "D:\foderA\"
 PS> Get-ChildItem -recurse $source -Filter "*.pdf"
</code>```

It displays all the files in dir and sub dir but when I try to use copy-Item I get the error.

```<code> PS> Get-ChildItem -recurse $source -Filter "*.pdf" | % {Copy-Item $_    -destination $desti}
</code>```

Error: Copy-Item : Cannot find path 'C:\Folder1\Folder2.... because it does not exist. Error points to source being non-existent.
What am I doing wrong?
Is it because I have read only on the source drive\Folder?

Thanks

答:
You can pipe the output objects from Get-ChildItem directly to Copy-Item (i.e., you don't need % [which is an alias for ForEach-Object]); e.g.:

```<code>Get-ChildItem -Recurse $source -Filter "*.pdf" -File | Copy-Item -Destination $desti
</code>```

The -File parameter restricts the search only to files.

Title: PowerShell 5 Copy-Item not working

Body:
I am trying to copy all .pdf files from all folders and sub folder (dirs. and subdirs).

Folder1
  1.pdf
  2.pdf
Folder1\Foder2\3.pdf
Folder1\Folder2\4.pdf
Folder1\Foder2\Folder3\5.pdf
Folder1\Folder2\Folder3\6.pdf

First I used

 $source = "c:\Folder1\"
 $desti = "D:\foderA\"
 PS> Get-ChildItem -recurse $source -Filter "*.pdf"

It displays all the files in dir and sub dir but when I try to use copy-Item I get the error.

 PS> Get-ChildItem -recurse $source -Filter "*.pdf" | % {Copy-Item $_    -destination $desti}

Error: Copy-Item : Cannot find path 'C:\Folder1\Folder2.... because it does not exist. Error points to source being non-existent.
What am I doing wrong?
Is it because I have read only on the source drive\Folder?

Thanks

Body:
You can pipe the output objects from Get-ChildItem directly to Copy-Item (i.e., you don't need % [which is an alias for ForEach-Object]); e.g.:

Get-ChildItem -Recurse $source -Filter "*.pdf" -File | Copy-Item -Destination $desti

The -File parameter restricts the search only to files.


问:
Playframework: how can I initialize an input box in a form?
Inside a web form I have input boxes like these:

```<code><input type="datetime-local" id="dt" name="dt" value=@form("dt")><br />
<input type="text" id="f0" name="f0" size="12" list=lst>
</code>```

I am mapping the fields to a class:

```<code>case class Data(dt: Date, f0: String...)
</code>```

When I submit the form I am able to fetch the values inserted in the boxes. However, I wanted to initialize the first input box with the current date. I tried, like it was documented, by returning the following from the main action:

```<code>Ok(views.html.index(form.fill(new Data(new Date(), ""))))
</code>```

But it did not work out.

How can I achieve that?

Thanks!

答:
First define a custom Formatter that has the date pattern needed by the datetime-local input type using Java's date format pattern:

```<code>import play.api.data.format._

val dateTimeLocal: Formatter[Date] = Formats.dateFormat("yyyy-MM-dd'T'HH:mm")
</code>```

Then define to/from a Form using mapping and of.

```<code>val dataForm = Form(
  mapping(
    "dt" -> of(dateTimeLocal),
    "f0" -> text
  )(Data.apply)(Data.unapply)
)
</code>```

Now you can use a form helper to display an <input type="datetime-local">:

```<code>@helper.inputText(dataForm("dt"), 'type -> "datetime-local")
</code>```

This produces the following HTML snippet, with the correct input type and date pattern:

```<code><input type="datetime-local" id="dt" name="dt" value="2017-11-16T08:19" />
</code>```

You'll get a date/time picker when you view this in Chrome, but not currently in browsers like Firefox (as of November 2017). You may wish to consider this note on MDN:

Because of the limited browser support for datetime-local, and the variations in how the inputs work, it may currently still be best to use a framework or library to present these, or to use a custom input of your own. Another option is to use separate date and time inputs, each of which is more widely supported than datetime-local.

Body:
Inside a web form I have input boxes like these:

<input type="datetime-local" id="dt" name="dt" value=@form("dt")>

<input type="text" id="f0" name="f0" size="12" list=lst>

I am mapping the fields to a class:

case class Data(dt: Date, f0: String...)

When I submit the form I am able to fetch the values inserted in the boxes. However, I wanted to initialize the first input box with the current date. I tried, like it was documented, by returning the following from the main action:

Ok(views.html.index(form.fill(new Data(new Date(), ""))))

But it did not work out.

How can I achieve that?

Thanks!

Body:
First define a custom Formatter that has the date pattern needed by the datetime-local input type using Java's date format pattern:

import play.api.data.format._

val dateTimeLocal: Formatter[Date] = Formats.dateFormat("yyyy-MM-dd'T'HH:mm")

Then define to/from a Form using mapping and of.

val dataForm = Form(
  mapping(
    "dt" -> of(dateTimeLocal),
    "f0" -> text
  )(Data.apply)(Data.unapply)
)

Now you can use a form helper to display an <input type="datetime-local">:

@helper.inputText(dataForm("dt"), 'type -> "datetime-local")

This produces the following HTML snippet, with the correct input type and date pattern:

<input type="datetime-local" id="dt" name="dt" value="2017-11-16T08:19" />

You'll get a date/time picker when you view this in Chrome, but not currently in browsers like Firefox (as of November 2017). You may wish to consider this note on MDN:

Because of the limited browser support for datetime-local, and the variations in how the inputs work, it may currently still be best to use a framework or library to present these, or to use a custom input of your own. Another option is to use separate date and time inputs, each of which is more widely supported than datetime-local.


问:
Trying to use controllers in AngularJS
I have implemented auto-complete feature, now I am trying to integrate into my main application. This is the controller function which I designed.

```<code>(function() {
      'use strict';
      angular
        .module('MyApp')
        .controller('DemoCtrl', DemoCtrl);

      function DemoCtrl($http) {
        this.querySearch = function (query) {
           return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
              return result.data;
            });
        }
      }
    })();
</code>```

This is my HTML for the first scenario:

```<code><div class="autocompletedemoFloatingLabel" ng-controller="DemoCtrl as ctrl" ng-app="MyApp" layout="column" ng-cloak="">
      <md-content class="md-padding">
        <form name="searchForm" ng-submit="$event.preventDefault()">
            <div layout-gt-sm="row">
            <md-input-container flex="">
            </md-input-container>

            <md-autocomplete md-floating-label=""
                            flex=""
                            md-item-text="item.Symbol"
                            md-items="item in ctrl.querySearch(ctrl.searchText)"
                            md-search-text="ctrl.searchText"
                            md-selected-item="ctrl.selectedItem"
                            md-no-cache="ctrl.noCache"
                            md-input-name="autocompleteField"
                            required="">
              <input>
              <md-item-template>
                <span md-highlight-text="ctrl.searchText">{{item.Symbol+" - "+item.Name+" ("+item.Exchange+")"}}</span>
              </md-item-template>
              <div ng-messages="searchForm.autocompleteField.$error" ng-if="searchForm.autocompleteField.$touched">
                <div ng-message="required">You <b>must</b> have a favorite movie.</div>
                <div ng-message="minlength">Your entry is not long enough.</div>
                <div ng-message="maxlength">Your entry is too long.</div>
              </div>
            </md-autocomplete>
          </input>
          </div>
    </form>
  </md-content>
</div>
</code>```

Now the application currently contains controller in this format:

```<code>var app = angular.module("assign8", ["ngAnimate"]);
app.controller("MyCtrl", function ($scope) {
$scope.myValue=false;
$scope.myValue_sec = false;
});
</code>```

I am very new to angular, I am unable to map the first format to the second one. Kindly let me know how can I map first to second. TIA.

答:
I'm not sure where the confusion lies. The two scenarios are very similar. </p>

```<code>app.controller("MyCtrl", function ($scope) {
    this.querySearch = function (query) { ... }
});
</code>```

Title: Trying to use controllers in AngularJS

Body:
I have implemented auto-complete feature, now I am trying to integrate into my main application. This is the controller function which I designed.

(function() {
      'use strict';
      angular
        .module('MyApp')
        .controller('DemoCtrl', DemoCtrl);

      function DemoCtrl($http) {
        this.querySearch = function (query) {
           return $http.get('http://127.0.0.1:8888/autocomplete/' + escape(query)).then(function(result) {
              return result.data;
            });
        }
      }
    })();

This is my HTML for the first scenario:

      <md-content class="md-padding">
        <form name="searchForm" ng-submit="$event.preventDefault()">

            <md-input-container flex="">
            </md-input-container>

            <md-autocomplete md-floating-label=""
                            flex=""
                            md-item-text="item.Symbol"
                            md-items="item in ctrl.querySearch(ctrl.searchText)"
                            md-search-text="ctrl.searchText"
                            md-selected-item="ctrl.selectedItem"
                            md-no-cache="ctrl.noCache"
                            md-input-name="autocompleteField"
                            required="">
              <input>
              <md-item-template>
                {{item.Symbol+" - "+item.Name+" ("+item.Exchange+")"}}
              </md-item-template>

You must have a favorite movie.

Your entry is not long enough.

Your entry is too long.

            </md-autocomplete>
          </input>

    </form>
  </md-content>

Now the application currently contains controller in this format:

var app = angular.module("assign8", ["ngAnimate"]);
app.controller("MyCtrl", function ($scope) {
$scope.myValue=false;
$scope.myValue_sec = false;
});

I am very new to angular, I am unable to map the first format to the second one. Kindly let me know how can I map first to second. TIA.

Body:
I'm not sure where the confusion lies. The two scenarios are very similar.

app.controller("MyCtrl", function ($scope) {
    this.querySearch = function (query) { ... }
});


问:
SAS - Built a new table by calling a macro with a variable of another table passed as parameter
I have written this code to do this :

read records in the table "not_identified" one by one

for one record pass the "name_firstname" variable to a macro named "mCalcul_lev_D33",

then, the macro calculates the Levenstein between the variable passed as parameter and all the values of the variable "name_firstname_in_D33" in "data_all" table,

if the Levenstein returns a value less or equal to "3", then the record of "data_all" is copied to "lev_D33" table.

```<code>rsubmit;
%macro mCalcul_lev_D33(theName);
  data result.lev_D33;
   set result.data_all;
   name_LEV=complev(&theName, name_firstname_in_D33);
   if name_LEV<=3 then output;
  run;
%mend mCalcul_lev_D33;
endrsubmit;

rsubmit;
data _null_;
  set result.not_identified;
  call execute ('%mCalcul_lev_D33('||name_firstname||')');
;
run;
endrsubmit;
</code>```

There is 53700000 records in "data_all". The code is running since yesterday. Because I cannot see the result, I am asking :

Is the code doing what I want?

How coding if I want to write "name_firstname" (the variable passed like parameter) in the beginning of each record of "lev_D33"?

Thank you!

答:
Thanks to @Richard. I have used your second example to write this code :

```<code>rsubmit;
  data result.lev_D33;
    set result.not_identified (firstobs=1 obs=10);
    do check_row = 1 to 1000000;
      set &lib..data_all (firstobs=1 obs=1000000) point=check_row;
      name_lev = complev (name_firstname, name_firstname_D3);
      if name_lev <= 3 then output;
    end;
  run;
endrsubmit ;
</code>```

And it worked like I wanted.

In this example, I compare name_firstname in not_identified table to all name_firstname_D3 in data_all. If the COMPLEV is less or equal to 3, then the merge of the 2 records are in the result table "lev_D33" (one record from not_identified is merged to one record from data_all).

To do a test, I taked 10 records from not_identified and tried to find a concordance of the names and the firstnames in 1000000 data_all only.

Body:
I have written this code to do this :

read records in the table "not_identified" one by one

for one record pass the "name_firstname" variable to a macro named "mCalcul_lev_D33",

then, the macro calculates the Levenstein between the variable passed as parameter and all the values of the variable "name_firstname_in_D33" in "data_all" table,

if the Levenstein returns a value less or equal to "3", then the record of "data_all" is copied to "lev_D33" table.

rsubmit;
%macro mCalcul_lev_D33(theName);
  data result.lev_D33;
   set result.data_all;
   name_LEV=complev(&theName, name_firstname_in_D33);
   if name_LEV<=3 then output;
  run;
%mend mCalcul_lev_D33;
endrsubmit;

rsubmit;
data _null_;
  set result.not_identified;
  call execute ('%mCalcul_lev_D33('||name_firstname||')');
;
run;
endrsubmit;

There is 53700000 records in "data_all". The code is running since yesterday. Because I cannot see the result, I am asking :

Is the code doing what I want?

How coding if I want to write "name_firstname" (the variable passed like parameter) in the beginning of each record of "lev_D33"?

Thank you!

Body:
Thanks to @Richard. I have used your second example to write this code :

rsubmit;
  data result.lev_D33;
    set result.not_identified (firstobs=1 obs=10);
    do check_row = 1 to 1000000;
      set &lib..data_all (firstobs=1 obs=1000000) point=check_row;
      name_lev = complev (name_firstname, name_firstname_D3);
      if name_lev <= 3 then output;
    end;
  run;
endrsubmit ;

And it worked like I wanted.

In this example, I compare name_firstname in not_identified table to all name_firstname_D3 in data_all. If the COMPLEV is less or equal to 3, then the merge of the 2 records are in the result table "lev_D33" (one record from not_identified is merged to one record from data_all).

To do a test, I taked 10 records from not_identified and tried to find a concordance of the names and the firstnames in 1000000 data_all only.


问:
How to map + filter in single loop
I have asked this question on SO before but I cannot find the question/answers!

Basically I want to create this:

```<code>Array.prototype.filterAndMap = function(){};
</code>```

where I can use it like so:

```<code>[1,2,3,4,5].filterAndMap(function(){
     if(i % 2 === 0){
        return i*2;
     }
});
</code>```

the above would return:

```<code>  [4,8]
</code>```

I think the best way to implement this is using Array.prototype.reduce...but I am not sure.

What I am trying to avoid, is iterating through the list twice:

```<code>   [1,2,3,4,5].filter(function(){
         return i % 2 === 0;
    })
    .map(function(i){
         return i * 2;
    });
</code>```

答:
Your question has been answered in specific ways, according to your sample code.

If what you are trying to accomplish is a generic function to filter and map (although it is not a map, it is a reduce), this is what you are looking for:

```<code>var filterAndReduce = function(arr, filterFn, fn) {
  return arr.reduce(function(r, a) {
        return r.concat(filterFn(a) ? [] : fn(a));
  }, []);
};
</code>```

You would use it this way:

```<code>filterAndReduce([1,2,3,4,5], function(i) {
     return i % 2;
},
function(i) {
    return i * 2
});
</code>```

Title: How to map + filter in single loop

Body:
I have asked this question on SO before but I cannot find the question/answers!

Basically I want to create this:

Array.prototype.filterAndMap = function(){};

where I can use it like so:

[1,2,3,4,5].filterAndMap(function(){
     if(i % 2 === 0){
        return i*2;
     }
});

the above would return:

  [4,8]

I think the best way to implement this is using Array.prototype.reduce...but I am not sure.

What I am trying to avoid, is iterating through the list twice:

   [1,2,3,4,5].filter(function(){
         return i % 2 === 0;
    })
    .map(function(i){
         return i * 2;
    });

Body:
Your question has been answered in specific ways, according to your sample code.

If what you are trying to accomplish is a generic function to filter and map (although it is not a map, it is a reduce), this is what you are looking for:

var filterAndReduce = function(arr, filterFn, fn) {
  return arr.reduce(function(r, a) {
        return r.concat(filterFn(a) ? [] : fn(a));
  }, []);
};

You would use it this way:

filterAndReduce([1,2,3,4,5], function(i) {
     return i % 2;
},
function(i) {
    return i * 2
});


问:
change DD-MMM-YYYY to YYYYMMDD in oracle
i have a date 07-OCT-2017, I have to get it converted as 20171007 in oracle.</p>

```<code>Below code doesn't work for me
select To_date(to_char('07-OCT-2017','DD-MMM-YYYY'), 'yyyymmdd') from dual;
</code>```

答:
Too much sugar for your dime.

```<code>  select to_char( to_date( '07-JUL-2017',
                           'DD-MON-YYYY',
                           'NLS_DATE_LANGUAGE = American'),
                 'YYYYMMDD') from dual;
</code>```

Yields

```<code>TO_CHAR(
--------
20170707
</code>```

Fix the details. Please edit your question to match the data you present.
Still, hope this helps.

Body:
i have a date 07-OCT-2017, I have to get it converted as 20171007 in oracle.

Below code doesn't work for me
select To_date(to_char('07-OCT-2017','DD-MMM-YYYY'), 'yyyymmdd') from dual;

Body:
Too much sugar for your dime.

  select to_char( to_date( '07-JUL-2017',
                           'DD-MON-YYYY',
                           'NLS_DATE_LANGUAGE = American'),
                 'YYYYMMDD') from dual;

Yields

TO_CHAR(
--------
20170707

Fix the details. Please edit your question to match the data you present.
Still, hope this helps.


问:
Differentiating a component mounting or hydrating in React 16.1.1
I have a ScrollToTopOnMount as implemented here with

```<code>componentDidMount(prevProps) {
  window.scrollTo(0, 0)
}
</code>```

Which works great, except when I combine this with SSR and hydrating, my page snaps to the top when the hydration happens.

Other answers such as this one gave me hope that there may be some way to discriminate between whether a component is legitimately mounting, or just being hydrated. However, this does not seem to be the case as of react-dom 16.1.1, where both the server and the client appear to call componentWillMount.

Is there a way to have an lifecycle method determine whether it's being mounted where there is no DOM or hydrating an existing node?

答: ReactDOM.hydrate has a callback when it completes. One solution would be to set and un-set a global var window.hydrating = true and differentiate based on that when the component mounts.

Body:
I have a ScrollToTopOnMount as implemented here with

componentDidMount(prevProps) {
  window.scrollTo(0, 0)
}

Which works great, except when I combine this with SSR and hydrating, my page snaps to the top when the hydration happens.

Other answers such as this one gave me hope that there may be some way to discriminate between whether a component is legitimately mounting, or just being hydrated. However, this does not seem to be the case as of react-dom 16.1.1, where both the server and the client appear to call componentWillMount.

Is there a way to have an lifecycle method determine whether it's being mounted where there is no DOM or hydrating an existing node?


问:
R: icc{irr}: Attempting one-way model with multiple ratings per rater per subject
I haven't found my particular scenario in any of the other threads online regarding the ICC{psych} / icc{irr} functions.

I am trying to find interrater reliability based on data that has columns for subject, rater, and then multiple rating columns. (From what I'm gathering, most people work with data that has simply raters as columns, subjects as rows, and the single rating in the cell.)

Data sample:

Data sample

Here is the code I have tried:

```<code>icc(data.pers.icc[,5],model="oneway",type="consistency",unit="average",r0=0,conf.level=0.95)

icc(data.pers.icc[,c(1,2,5)],model="oneway",type="consistency",unit="average",conf.level=0.95)
</code>```

I understand why the second line of code gives me an error; the formula is not designed to take each column as a separate data point, but as a separate rater.
But I do not understand why the first line does not work. It gives me an answer of NA:

```<code>Average Score Intraclass Correlation

Model: oneway
Type : consistency

Subjects = 48
Raters = 1
ICC(1) = NA

F-Test, H0: r0 = 0 ; H1: r0 > 0
F(47,0) = NA , p = NA

95%-Confidence Interval for ICC Population Values:
NA < ICC < NA
</code>```

I have also tried including the rating and subject columns, but this latter reads as an ICC(2) and also gives me NA as the answer.

Even if this worked, I would still have to repeat the process for every column, so I have extracted factor scores and added to the column that I could use instead, but am stuck because I have no idea how to run even a single column through this function.

P.S. I have also tried ICC:

```<code>ICC(data.pers.icc[,c(35)],alpha=0.05)
</code>```

but it gives me this error:

ICC error1:

If I include the subject and rating columns, it produces another error message that says: 'contrasts can only be applied to factors with 2 or more levels'.

Would appreciate any help! I have a second, much larger dataframe to do this with, as well. Sorry for my newbie approach to R and stats.

答:
Generally, the first argument of the icc function should be "n*m matrix or dataframe, n subjects m raters.". This means that columns are raters and rows are subjects.
If there is just one column (as in icc(data.pers.icc[,5],model="oneway",type="consistency",unit="average",r0=0,conf.level=0.95)), there is just one rater. Therefore icc can't be computed.

Concerning your second example (icc(data.pers.icc[,c(1,2,5)],model="oneway",type="consistency",unit="average",conf.level=0.95)): the first column contains names of subjects which is wrong. All columns have to be numeric. Moreover, you should treat your traits separately.

The correct input for the Trait1 should look like this:

```<code>  Adam LiaoBo Fatima Maria
A  5.5     NA     NA    NA
B  5.0      4     NA    NA
D   NA     NA      7    NA
E  4.0      7     NA    NA
F  1.0     NA      2     4
</code>```

However, if you put this to the icc function, it will return NA as well. Experimentally, I found out that this function is not able to deal with that many NA values.However, function ICC from the psych package is somehow able to deal with that NAs when you specify, that it should use all cases and not just complete ones:

So you can compute icc like this:

```<code>   my_data <-cbind(
   c(5.5, 5, NA, 4, 1), #Adam
   c(NA, 4, NA, 7, NA), #LiaoBo
   c(NA, NA, 7, NA, 2), #Fatima
   c(NA, NA, NA, NA, 4)) #Maria

ICC(my_data,missing=F)
</code>```

which will give you following output:

```<code>Call: ICC(x = my_data, missing = F)

Intraclass correlation coefficients
                         type  ICC   F df1 df2     p lower bound upper bound
Single_raters_absolute   ICC1 0.26 2.4   4  15 0.096       -0.10        0.83
Single_random_raters     ICC2 0.11 1.5   4  12 0.277       -0.22        0.77
Single_fixed_raters      ICC3 0.10 1.5   4  12 0.277       -0.19        0.75
Average_raters_absolute ICC1k 0.58 2.4   4  15 0.096       -0.58        0.95
Average_random_raters   ICC2k 0.34 1.5   4  12 0.277       -2.50        0.93
Average_fixed_raters    ICC3k 0.31 1.5   4  12 0.277       -1.84        0.92

 Number of subjects = 5     Number of Judges =  4
</code>```

Now, you`ll just select the correct one.

However, I have read that icc index can be used either for fully-crossed design (i.e.: when all raters provides ratings for all subjects) or when a new set of raters is randomly selected for each subject. So icc might isn't the best choice for your dataset.

Index which is able to deal better with NAs is called Krippendorff's alpha and it is available in the irr package too. The only additional argument to specify is type of your data (argument: method = ("nominal","ordinal","interval","ratio")). (I do not know your data, so you`ll might decide for other method then I used bellow.)

Krippendorff's alpha for the Trait1 can be computed like this:

```<code>    kripp.alpha(t(my_data) ,"ratio")
</code>```

will give you

```<code>    Krippendorff's alpha

 Subjects = 5
   Raters = 4
    alpha = -0.167
</code>```

This means that your inter-rater reliability is slightly worse than expected by chance. This result is very different from one obtained by ICC. However I don`t think any index  would be meaningful for such a small matrix with that many missing values.

Generally, be aware of confusing subjects and raters. For example for this index I had to transform my matrix (function t).

If you want to know more about icc, Krippendorff's alpha and inter-rater reliability in general, I  recommend you following articles which are understandable even for non-statisticians:

Hallgren, K. A. (2012). Computing Inter-Rater Reliability for
Observational Data: An Overview and Tutorial. Tutorials in
Quantitative Methods for Psychology, 8(1), 23–34.
http://doi.org/10.20982/tqmp.08.1.p023

Koo, T. K., & Li, M. Y. (2016). A Guideline of Selecting and

Reporting Intraclass Correlation Coefficients for Reliability

Research. Journal of Chiropractic Medicine, 15(2), 155–163.

http://doi.org/10.1016/j.jcm.2016.02.012

Stemler, S. E., & Tsai, J. (2008). Best practices in interrater

reliability: Three common approaches. Best practices in quantitative
methods. http://doi.org/10.4135/9781412995627.d5

Feng, G. C. (2015). Mistakes and how to avoid mistakes in using

intercoder reliability indices. Methodology, 11(1), 13–22.

http://doi.org/10.1027/1614-2241/a000086

http://digital-activism.org/2013/05/picking-the-best-intercoder-reliability-statistic-for-your-digital-activism-content-analysis/

P.S.: I want you know, I'm not a statistician. I've just spent few days reading articles about indexes and dealing with similar problems as you.

Body:
I haven't found my particular scenario in any of the other threads online regarding the ICC{psych} / icc{irr} functions.

I am trying to find interrater reliability based on data that has columns for subject, rater, and then multiple rating columns. (From what I'm gathering, most people work with data that has simply raters as columns, subjects as rows, and the single rating in the cell.)

Data sample:

Data sample

Here is the code I have tried:

icc(data.pers.icc[,5],model="oneway",type="consistency",unit="average",r0=0,conf.level=0.95)

icc(data.pers.icc[,c(1,2,5)],model="oneway",type="consistency",unit="average",conf.level=0.95)

I understand why the second line of code gives me an error; the formula is not designed to take each column as a separate data point, but as a separate rater.
But I do not understand why the first line does not work. It gives me an answer of NA:

Average Score Intraclass Correlation

Model: oneway
Type : consistency

Subjects = 48
Raters = 1
ICC(1) = NA

F-Test, H0: r0 = 0 ; H1: r0 > 0
F(47,0) = NA , p = NA

95%-Confidence Interval for ICC Population Values:
NA < ICC < NA

I have also tried including the rating and subject columns, but this latter reads as an ICC(2) and also gives me NA as the answer.

Even if this worked, I would still have to repeat the process for every column, so I have extracted factor scores and added to the column that I could use instead, but am stuck because I have no idea how to run even a single column through this function.

P.S. I have also tried ICC:

ICC(data.pers.icc[,c(35)],alpha=0.05)

but it gives me this error:

ICC error1:

If I include the subject and rating columns, it produces another error message that says: 'contrasts can only be applied to factors with 2 or more levels'.

Would appreciate any help! I have a second, much larger dataframe to do this with, as well. Sorry for my newbie approach to R and stats.

Body:
Generally, the first argument of the icc function should be "n*m matrix or dataframe, n subjects m raters.". This means that columns are raters and rows are subjects.
If there is just one column (as in icc(data.pers.icc[,5],model="oneway",type="consistency",unit="average",r0=0,conf.level=0.95)), there is just one rater. Therefore icc can't be computed.

Concerning your second example (icc(data.pers.icc[,c(1,2,5)],model="oneway",type="consistency",unit="average",conf.level=0.95)): the first column contains names of subjects which is wrong. All columns have to be numeric. Moreover, you should treat your traits separately.

The correct input for the Trait1 should look like this:

  Adam LiaoBo Fatima Maria
A  5.5     NA     NA    NA
B  5.0      4     NA    NA
D   NA     NA      7    NA
E  4.0      7     NA    NA
F  1.0     NA      2     4

However, if you put this to the icc function, it will return NA as well. Experimentally, I found out that this function is not able to deal with that many NA values.However, function ICC from the psych package is somehow able to deal with that NAs when you specify, that it should use all cases and not just complete ones:

So you can compute icc like this:

   my_data <-cbind(
   c(5.5, 5, NA, 4, 1), #Adam
   c(NA, 4, NA, 7, NA), #LiaoBo
   c(NA, NA, 7, NA, 2), #Fatima
   c(NA, NA, NA, NA, 4)) #Maria

ICC(my_data,missing=F)

which will give you following output:

Call: ICC(x = my_data, missing = F)

Intraclass correlation coefficients
                         type  ICC   F df1 df2     p lower bound upper bound
Single_raters_absolute   ICC1 0.26 2.4   4  15 0.096       -0.10        0.83
Single_random_raters     ICC2 0.11 1.5   4  12 0.277       -0.22        0.77
Single_fixed_raters      ICC3 0.10 1.5   4  12 0.277       -0.19        0.75
Average_raters_absolute ICC1k 0.58 2.4   4  15 0.096       -0.58        0.95
Average_random_raters   ICC2k 0.34 1.5   4  12 0.277       -2.50        0.93
Average_fixed_raters    ICC3k 0.31 1.5   4  12 0.277       -1.84        0.92

 Number of subjects = 5     Number of Judges =  4

Now, you`ll just select the correct one.

However, I have read that icc index can be used either for fully-crossed design (i.e.: when all raters provides ratings for all subjects) or when a new set of raters is randomly selected for each subject. So icc might isn't the best choice for your dataset.

Index which is able to deal better with NAs is called Krippendorff's alpha and it is available in the irr package too. The only additional argument to specify is type of your data (argument: method = ("nominal","ordinal","interval","ratio")). (I do not know your data, so you`ll might decide for other method then I used bellow.)

Krippendorff's alpha for the Trait1 can be computed like this:

    kripp.alpha(t(my_data) ,"ratio")

will give you

    Krippendorff's alpha

 Subjects = 5
   Raters = 4
    alpha = -0.167

This means that your inter-rater reliability is slightly worse than expected by chance. This result is very different from one obtained by ICC. However I don`t think any index  would be meaningful for such a small matrix with that many missing values.

Generally, be aware of confusing subjects and raters. For example for this index I had to transform my matrix (function t).

If you want to know more about icc, Krippendorff's alpha and inter-rater reliability in general, I  recommend you following articles which are understandable even for non-statisticians:

Hallgren, K. A. (2012). Computing Inter-Rater Reliability for
Observational Data: An Overview and Tutorial. Tutorials in
Quantitative Methods for Psychology, 8(1), 23–34.
http://doi.org/10.20982/tqmp.08.1.p023

Koo, T. K., & Li, M. Y. (2016). A Guideline of Selecting and

Reporting Intraclass Correlation Coefficients for Reliability

Research. Journal of Chiropractic Medicine, 15(2), 155–163.

http://doi.org/10.1016/j.jcm.2016.02.012

Stemler, S. E., & Tsai, J. (2008). Best practices in interrater

reliability: Three common approaches. Best practices in quantitative
methods. http://doi.org/10.4135/9781412995627.d5

Feng, G. C. (2015). Mistakes and how to avoid mistakes in using

intercoder reliability indices. Methodology, 11(1), 13–22.

http://doi.org/10.1027/1614-2241/a000086

http://digital-activism.org/2013/05/picking-the-best-intercoder-reliability-statistic-for-your-digital-activism-content-analysis/

P.S.: I want you know, I'm not a statistician. I've just spent few days reading articles about indexes and dealing with similar problems as you.


问:
I can't program a pause based on a condition
I am making an app that will pause a countdown timer when a specific condition exists.  My countdown timer cycles through a string-array to populate text fields.  Each time the counter gets down to zero, it resets and populates the text fields with the next set of text.  I even have a working pause button.  However, I can't program-matically pause the countdown timer based on specific text in one of the text fields.

Heres my timer code:

```<code>class MyTimer extends CountDownTimer {

    //constructor for timer class
    public MyTimer(long millisInFurture, long countDownInterval) {
        super(millisInFurture, countDownInterval);
    }

    // this method called when timer is finished
    @Override
    public void onFinish() {
        // reset all variables
        clockText.setText(clockTime);
        isRunning = false;
        remainMilli = 0;

        advanceLevel();
        goTimer();
    }

    // this method is called for every iteration of time interval
    @Override
    public void onTick(long millisUntilFinished) {
        remainMilli = millisUntilFinished;

        //calculate minutes and seconds from milliseconds
        String minute = "" + (millisUntilFinished/1000)/60;
        String second = "" + (millisUntilFinished/1000)%60;

        // apply style to minute and second
        if((millisUntilFinished/1000)/60 < 10) {
            minute = "0" + (millisUntilFinished/1000)/60;
        }
        if ((millisUntilFinished/1000)%60 < 10) {
            second = "0" + (millisUntilFinished/1000)%60;
        }

        //update textview with remaining time
        clockText.setText(minute + ":" + second);
    }

}
</code>```

Here's my Start and Pause code for the timer:

```<code>public boolean goTimer() {
    breakCheck = blinds.getText().toString();
    Log.i(breakCheck, "level");

    if (isRunning) {
        // cancel (Pause) timer when it is running
        mTimer.cancel();
        mTimer = null;
        isRunning = false;
    } else {
        if (remainMilli == 0) {
            // start timer from initial time
            mTimer = new MyTimer(blindTime, 1000);

        } else {
            //resume timer from where it is paused
            mTimer = new MyTimer(remainMilli, 1000);
        }
        mTimer.start();
        isRunning = true;
        }

    return true;

}
</code>```

...and here is the code that changes the text fields after each loop of the countdown timer:

```<code>public boolean advanceLevel() {
    levelNum = levelNum + 1;
    round = round + 1;
    anteLevel = anteLevel + 1;

    if (round < roundMax) {
        level.setText(String.valueOf(levelNum));
        blinds.setText(blinds_list[round]);
        ante.setText(ante_list[anteLevel]);
    } else if (round == roundMax) {
        level.setText("Max Level");

    } else if (round > roundMax) {
        try {
            mTimer.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
    return true;
}
</code>```

So every time the countdown finishes, the text fields get populated with new text from the String-array.  What I want is for when the blinds text field is showing "BREAK", I want the countdown timer to pause.

So, I put in a:

```<code>String blindCheck = blinds.getText().toString();
</code>```

if (blindCheck == "BREAK") { mTimer.cancel(); }

...but no matter what I do, the countdown timer doesn't pause, it just keeps going.

The Start/Pause button for the timer is on the bottom nav bar, and works great, so when my blindCheck == "BREAK", I tried having it execute the method to Start/Pause the clock, but that didn't work either.

I'm not sure what to do here.  Any help would be appreciated.
Thanks,
Hendo

答:
Do not use CountDownTimer for this Purpose. Instead of this, you should use Handler like this</p>

```<code>final Handler handler = new Handler();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {

            // done your functionality here

            // if you want to continue, or pause is not active
            handler.postDelayed(this, 1*1000);

            // else you will in pause state

        }
    };

    // to start the hanlder
    handler.postDelayed(runnable, 1*1000);

    // to stop or pause the handler
    handler.removeCallbacks(runnable);
</code>```

Body:
I am making an app that will pause a countdown timer when a specific condition exists.  My countdown timer cycles through a string-array to populate text fields.  Each time the counter gets down to zero, it resets and populates the text fields with the next set of text.  I even have a working pause button.  However, I can't program-matically pause the countdown timer based on specific text in one of the text fields.

Heres my timer code:

class MyTimer extends CountDownTimer {

    //constructor for timer class
    public MyTimer(long millisInFurture, long countDownInterval) {
        super(millisInFurture, countDownInterval);
    }

    // this method called when timer is finished
    @Override
    public void onFinish() {
        // reset all variables
        clockText.setText(clockTime);
        isRunning = false;
        remainMilli = 0;

        advanceLevel();
        goTimer();
    }

    // this method is called for every iteration of time interval
    @Override
    public void onTick(long millisUntilFinished) {
        remainMilli = millisUntilFinished;

        //calculate minutes and seconds from milliseconds
        String minute = "" + (millisUntilFinished/1000)/60;
        String second = "" + (millisUntilFinished/1000)%60;

        // apply style to minute and second
        if((millisUntilFinished/1000)/60 < 10) {
            minute = "0" + (millisUntilFinished/1000)/60;
        }
        if ((millisUntilFinished/1000)%60 < 10) {
            second = "0" + (millisUntilFinished/1000)%60;
        }

        //update textview with remaining time
        clockText.setText(minute + ":" + second);
    }

}

Here's my Start and Pause code for the timer:

public boolean goTimer() {
    breakCheck = blinds.getText().toString();
    Log.i(breakCheck, "level");

    if (isRunning) {
        // cancel (Pause) timer when it is running
        mTimer.cancel();
        mTimer = null;
        isRunning = false;
    } else {
        if (remainMilli == 0) {
            // start timer from initial time
            mTimer = new MyTimer(blindTime, 1000);

        } else {
            //resume timer from where it is paused
            mTimer = new MyTimer(remainMilli, 1000);
        }
        mTimer.start();
        isRunning = true;
        }

    return true;

}

...and here is the code that changes the text fields after each loop of the countdown timer:

public boolean advanceLevel() {
    levelNum = levelNum + 1;
    round = round + 1;
    anteLevel = anteLevel + 1;

    if (round < roundMax) {
        level.setText(String.valueOf(levelNum));
        blinds.setText(blinds_list[round]);
        ante.setText(ante_list[anteLevel]);
    } else if (round == roundMax) {
        level.setText("Max Level");

    } else if (round > roundMax) {
        try {
            mTimer.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
    return true;
}

So every time the countdown finishes, the text fields get populated with new text from the String-array.  What I want is for when the blinds text field is showing "BREAK", I want the countdown timer to pause.

So, I put in a:

String blindCheck = blinds.getText().toString();

if (blindCheck == "BREAK") { mTimer.cancel(); }

...but no matter what I do, the countdown timer doesn't pause, it just keeps going.

The Start/Pause button for the timer is on the bottom nav bar, and works great, so when my blindCheck == "BREAK", I tried having it execute the method to Start/Pause the clock, but that didn't work either.

I'm not sure what to do here.  Any help would be appreciated.
Thanks,
Hendo

Body:
Do not use CountDownTimer for this Purpose. Instead of this, you should use Handler like this

final Handler handler = new Handler();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {

            // done your functionality here

            // if you want to continue, or pause is not active
            handler.postDelayed(this, 1*1000);

            // else you will in pause state

        }
    };

    // to start the hanlder
    handler.postDelayed(runnable, 1*1000);

    // to stop or pause the handler
    handler.removeCallbacks(runnable);


问:
Error in FTP connection using domain name, username and password?
I have following details only

domain name:Mydomain.com (I have not Server IP address)
UserId: abc
Password:123456

when I am  trying to connect ftp through Filezilla or Myftp it gives error like

Connection attempt failed with "EAI_NONAME - Neither nodename nor servname provided, or not known".

Please suggest me solution.

答:
Took me almost an hour to figure out, that leaving the port blank was the issue in my case. In Former times port 21 was used by default.

So setting Port: 21 was the solution.


问:
StrSQL Insert into throwing an error in VBA
I am trying to Insert some new records in to an access database.

Here is my code,

```<code>' OPEN ACCESS APPLICATION
    Set objAccess = CreateObject("Access.Application")
    objAccess.OpenCurrentDatabase DatabasePath

 ' OPEN INTERNAL DATABASE
    Set db = objAccess.CurrentDb

BuName = Ws.Sheets("Config").Range("T1").Value
RepName = Ws.Sheets("Config").Range("T2").Value
NumberofUniqueSheets = Ws.Sheets("Config").Range("T3").Value

For i = 1 To NumberofUniqueSheets

    CmpValue = Ws.Sheets("Config").Range("U1").Value
    ShtNamedec = Split(CmpValue, "$")(0)
    HeadRow = Split(CmpValue, "$")(1)
    AddInfo = Split(CmpValue, "$")(2)
    DateInfo = Split(CmpValue, "$")(3)

    ' PREPARE STATEMENT
    strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
               & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo]);"

    ' BUILD TEMP QUERYDEF
    Set qdef = db.CreateQueryDef("", strSQL)

    ' BIND PARAMS TO VARIABLES
    qdef!BusinessUnitparam = BuName
    qdef!ReportNameparam = RepName
    qdef!SheetNameparam = ShtNamedec
    qdef!HeaderRowparam = HeadRow
    qdef!AdditionalInfoparam = AddInfo
    qdef!DateRequiredinfoparam = DateInfo

    ' EXECUTE ACTION QUERY
    qdef.Execute

Next

    Set qdef = Nothing
    Set db = Nothing
    Set objAccess = Nothing
</code>```

I am facing an error in the Build Temp QueryDef Statement and the error says `

Syntax error in Insert into Statement.

`
I added the Values into the Insert Into the statement like below

```<code>strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
               & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo]) VALUES (BuName, RepName, ShtNamedec, HeadRow, AddInfo, DateInfo);"
</code>```

But it gives another on Execute Action Query statement saying too few parameters expected 12. Here is the Table structure for reference -

答:
Your query is bad.

This:

```<code>INSERT INTO ReportTypes ([BusinessUnit],
                         [ReportName],
                         [SheetName],
                         [HeaderRow],
                         [AdditionalInfo],
                         [DateRequiredinfo])
VALUES (BuName,
        RepName,
        ShtNamedec,
        HeadRow,
        AddInfo,
        DateInfo)
</code>```

Will not work.

Although this might:

```<code>"INSERT INTO ReportTypes ([BusinessUnit],
                         [ReportName],
                         [SheetName],
                         [HeaderRow],
                         [AdditionalInfo],
                         [DateRequiredinfo])
VALUES ('" + BuName + "',
        '" + RepName + "',
        '" + ShtNamedec + "',
        " + HeadRow + ",
        '" + AddInfo + "',
        '" + DateInfo + "')"
</code>```

You can probably eliminate all that parameters assignment stuff.  I don't see it adding value here.

Body:
I am trying to Insert some new records in to an access database.

Here is my code,

' OPEN ACCESS APPLICATION
    Set objAccess = CreateObject("Access.Application")
    objAccess.OpenCurrentDatabase DatabasePath

 ' OPEN INTERNAL DATABASE
    Set db = objAccess.CurrentDb

BuName = Ws.Sheets("Config").Range("T1").Value
RepName = Ws.Sheets("Config").Range("T2").Value
NumberofUniqueSheets = Ws.Sheets("Config").Range("T3").Value

For i = 1 To NumberofUniqueSheets

    CmpValue = Ws.Sheets("Config").Range("U1").Value
    ShtNamedec = Split(CmpValue, "$")(0)
    HeadRow = Split(CmpValue, "$")(1)
    AddInfo = Split(CmpValue, "$")(2)
    DateInfo = Split(CmpValue, "$")(3)

    ' PREPARE STATEMENT
    strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
               & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo]);"

    ' BUILD TEMP QUERYDEF
    Set qdef = db.CreateQueryDef("", strSQL)

    ' BIND PARAMS TO VARIABLES
    qdef!BusinessUnitparam = BuName
    qdef!ReportNameparam = RepName
    qdef!SheetNameparam = ShtNamedec
    qdef!HeaderRowparam = HeadRow
    qdef!AdditionalInfoparam = AddInfo
    qdef!DateRequiredinfoparam = DateInfo

    ' EXECUTE ACTION QUERY
    qdef.Execute

Next

    Set qdef = Nothing
    Set db = Nothing
    Set objAccess = Nothing

I am facing an error in the Build Temp QueryDef Statement and the error says `

Syntax error in Insert into Statement.

`
I added the Values into the Insert Into the statement like below

strSQL = "PARAMETERS [BusinessUnitparam] TEXT(255), [ReportNameparam] TEXT(255),[SheetNameparam] TEXT(255), [HeaderRowparam] INTEGER, [AdditionalInfoparam] TEXT(255), [DateRequiredinfoparam] TEXT(255);" _
               & "INSERT INTO ReportTypes ([BusinessUnit], [ReportName], [SheetName], [HeaderRow], [AdditionalInfo], [DateRequiredinfo]) VALUES (BuName, RepName, ShtNamedec, HeadRow, AddInfo, DateInfo);"

But it gives another on Execute Action Query statement saying too few parameters expected 12. Here is the Table structure for reference -

Body:
Your query is bad.

This:

INSERT INTO ReportTypes ([BusinessUnit],
                         [ReportName],
                         [SheetName],
                         [HeaderRow],
                         [AdditionalInfo],
                         [DateRequiredinfo])
VALUES (BuName,
        RepName,
        ShtNamedec,
        HeadRow,
        AddInfo,
        DateInfo)

Will not work.

Although this might:

"INSERT INTO ReportTypes ([BusinessUnit],
                         [ReportName],
                         [SheetName],
                         [HeaderRow],
                         [AdditionalInfo],
                         [DateRequiredinfo])
VALUES ('" + BuName + "',
        '" + RepName + "',
        '" + ShtNamedec + "',
        " + HeadRow + ",
        '" + AddInfo + "',
        '" + DateInfo + "')"

You can probably eliminate all that parameters assignment stuff.  I don't see it adding value here.


问:
Design time data in WPF
[using vs2010 & expression blend v4]

Hi - trying to load up some design time data in WPF and Blend, using Josh Smith's concept here: http://joshsmithonwpf.wordpress.com/2010/04/07/assembly-level-initialization-at-design-time/
e.g.

```<code>[AttributeUsage(AttributeTargets.Assembly)]
public class DesignTimeBootstrapperAttribute : Attribute
{
    public DesignTimeBootstrapperAttribute(Type type)
    {
        var dep = new DependencyObject();
        Debug.WriteLine("here..?");
        if (DesignerProperties.GetIsInDesignMode(dep))
        {
            // TODO: Design-time initialization…
            IBootstrapper instance = Activator.CreateInstance(type) as IBootstrapper;
            if (instance != null)
            {
                instance.Run();
            }
        }
    }
}
</code>```

With my attribute here in AssemblyInfo.cs, where AppBootstrapper extends MefBootstrapper.

```<code>[assembly: AssemblyCopyright("Copyright ©  2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: DesignTimeBootstrapper(typeof(AppBootstrapper))]
</code>```

I don't want to use the Blend sample data, a) as it doesn't seem to create data for ObservableCollection and b) I'm in design mode by definition, so things will change quite a lot, but my 'generated data' will not.

Anyway, nothing seems to be happening.

Q1: How is it possible to debug the design time initialisation of my bootstrapper?
Q2: Do I need additional blend namespaces/ attributes etc in my View XAML?

(In my bootstrapper I'm just registering a different module where I want to replace RunTimeService with a DesignTimeService, exporting the IService interface).

TIA

答:
To debug this:

Open your project in VS2010

Set a breakpoint in the assembly attribute constructor

Start a new instance of Blend 4

From VS2010 use Debug -> Attach to Process: and choose Blend

Switch to Blend and open your project

Open a XAML file that references your sample data

Also, any Debug.WriteLine should appear in the VS2010 output window.

If you can't get the attribute method to work (I haven't tried it myself), you can use this method (which I have used) from MVVM Light:

```<code>private bool? _isInDesignMode;

public bool IsInDesignMode
{
    get
    {
        if (!_isInDesignMode.HasValue)
        {
            var prop = DesignerProperties.IsInDesignModeProperty;
            _isInDesignMode =
                (bool)DependencyPropertyDescriptor
                .FromProperty(prop, typeof(FrameworkElement))
                .Metadata.DefaultValue;
        }

        return _isInDesignMode.Value;
    }
}
</code>```

Title: Design time data in WPF

Body:
[using vs2010 & expression blend v4]

Hi - trying to load up some design time data in WPF and Blend, using Josh Smith's concept here: http://joshsmithonwpf.wordpress.com/2010/04/07/assembly-level-initialization-at-design-time/
e.g.

[AttributeUsage(AttributeTargets.Assembly)]
public class DesignTimeBootstrapperAttribute : Attribute
{
    public DesignTimeBootstrapperAttribute(Type type)
    {
        var dep = new DependencyObject();
        Debug.WriteLine("here..?");
        if (DesignerProperties.GetIsInDesignMode(dep))
        {
            // TODO: Design-time initialization…
            IBootstrapper instance = Activator.CreateInstance(type) as IBootstrapper;
            if (instance != null)
            {
                instance.Run();
            }
        }
    }
}

With my attribute here in AssemblyInfo.cs, where AppBootstrapper extends MefBootstrapper.

[assembly: AssemblyCopyright("Copyright ©  2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: DesignTimeBootstrapper(typeof(AppBootstrapper))]

I don't want to use the Blend sample data, a) as it doesn't seem to create data for ObservableCollection and b) I'm in design mode by definition, so things will change quite a lot, but my 'generated data' will not.

Anyway, nothing seems to be happening.

Q1: How is it possible to debug the design time initialisation of my bootstrapper?
Q2: Do I need additional blend namespaces/ attributes etc in my View XAML?

(In my bootstrapper I'm just registering a different module where I want to replace RunTimeService with a DesignTimeService, exporting the IService interface).

TIA

Body:
To debug this:

Open your project in VS2010

Set a breakpoint in the assembly attribute constructor

Start a new instance of Blend 4

From VS2010 use Debug -> Attach to Process: and choose Blend

Switch to Blend and open your project

Open a XAML file that references your sample data

Also, any Debug.WriteLine should appear in the VS2010 output window.

If you can't get the attribute method to work (I haven't tried it myself), you can use this method (which I have used) from MVVM Light:

private bool? _isInDesignMode;

public bool IsInDesignMode
{
    get
    {
        if (!_isInDesignMode.HasValue)
        {
            var prop = DesignerProperties.IsInDesignModeProperty;
            _isInDesignMode =
                (bool)DependencyPropertyDescriptor
                .FromProperty(prop, typeof(FrameworkElement))
                .Metadata.DefaultValue;
        }

        return _isInDesignMode.Value;
    }
}


问:
PHP - Create a folder and put a file in it
I need to put a file in a folder named after the current date (Ex : folderbefore/2017-11-15/mynewfile.sql).

I tried :

change folderbefore to 777 in the server (I know it's not good, but I tried it and anyway it doesn't work)

add www-data to the owner group of folderbefore

set the umask to 0 before creating the folder :

```<code>$old = umask(0);
$directory_was_created = mkdir($path, 0777);
umask($old);
</code>```

I tried adding chmod after to change the permission

```<code>$old = umask(0);
$directory_was_created = mkdir($path, 0777);
chmod($path, 0777);
umask($old);
</code>```

I'm always getting a folder with 775 permissions and no right to write in this newly created folder (tried with file_put_content who gives me FALSE and fopen who's throwing an error).

What am I missing ?

答:
```<code>$directory_was_created = mkdir($path, 0777);
</code>```

Needs to be

```<code>$directory_was_created = mkdir($path, 0777, true);
</code>```

If you want to create nested directories within the newly created directory

Body:
I need to put a file in a folder named after the current date (Ex : folderbefore/2017-11-15/mynewfile.sql).

I tried :

change folderbefore to 777 in the server (I know it's not good, but I tried it and anyway it doesn't work)

add www-data to the owner group of folderbefore

set the umask to 0 before creating the folder :

$old = umask(0);
$directory_was_created = mkdir($path, 0777);
umask($old);

I tried adding chmod after to change the permission

$old = umask(0);
$directory_was_created = mkdir($path, 0777);
chmod($path, 0777);
umask($old);

I'm always getting a folder with 775 permissions and no right to write in this newly created folder (tried with file_put_content who gives me FALSE and fopen who's throwing an error).

What am I missing ?

Body:
$directory_was_created = mkdir($path, 0777);

Needs to be

$directory_was_created = mkdir($path, 0777, true);

If you want to create nested directories within the newly created directory


问:
How to sync repo in bitbucket to S3 with jenkins
Background: I have a repository say example.com along with master and develop branch. My master branch repo push the change to /efs/prod through jenkins build and develop branch repo push the change to /efs/qa through jenkins build. Now I have setup a folder say /s3 in my develop branch of repo to push the changes to amazon S3, for this I have used "Publish Artifacts to S3 Bucket" plugin in jenkins.

Requirement: I am able to move the bitbucket uploads to aws s3 but when someone delete the file in bitbucket repo then I am unable to sync it with AWS s3.
I have followed below source to move the repo changes to s3

```<code>http://www.devops-share.com/upload-builds-from-jenkins-to-s3/
</code>```

Could someone let me know how could I make jenkins to sync the bitbucket repo with S3.

答:
A possible solution is to install aws-cli on the jenkins instance, set it up with aws configure, ideally granting it specific permissions to upload to a specific S3 bucket through IAM policies.

Next up is actually uploading your data, after your jenkins is done processing / building / compiling your code, run the following command from the directory you'd like to sync to S3:

aws s3 sync . s3://YOUR_BUCKET_NAME

If you'd like it to exclude certain directories, add --exclude "folder_name/**"

As it states in the aws-cli docs: "Recursively copies new and updated files from the source directory to the destination."

It will not delete files that are absent in the source directory but exist in the bucket.

If you really want this behaviour, you could blow away the bucket contents before each upload but this would result in downtime so perhaps consider a CloudFront setup that caches your bucket contents and you can clean this cache from Jenkins after your aws s3 sync has concluded successfully.

To invalidate a CloudFront cache, see the docs

Body:
Background: I have a repository say example.com along with master and develop branch. My master branch repo push the change to /efs/prod through jenkins build and develop branch repo push the change to /efs/qa through jenkins build. Now I have setup a folder say /s3 in my develop branch of repo to push the changes to amazon S3, for this I have used "Publish Artifacts to S3 Bucket" plugin in jenkins.

Requirement: I am able to move the bitbucket uploads to aws s3 but when someone delete the file in bitbucket repo then I am unable to sync it with AWS s3.
I have followed below source to move the repo changes to s3

http://www.devops-share.com/upload-builds-from-jenkins-to-s3/

Could someone let me know how could I make jenkins to sync the bitbucket repo with S3.


问:
How To Rearrange Data Set?
I am trying to rearrange my data set which currently looks like this:

To this:

I have been manually transposing and adding up the values for each source and trying my hand at using Python to automate this task. Would anybody be so kind to help me get started in the right direction?

Title: How To Rearrange Data Set?

Body:
Here's a potential pandas solution.

I made a test csv file. Didn't copy yours verbatim but the structure is there

test_data.csv

Source,10/30/2017,10/31/2017,11/1/2017,11/2/2017,11/3/2017,11/4/2017,11/5/2017
A,10,11,12,13,14,15,16
B,15,16,17,18,19,20,21
C,20,21,22,23,24,25,26
A,25,26,27,28,29,30,31
B,30,31,32,33,34,35,36
C,35,36,37,38,39,40,41

Here's the python code to process the data as you want it

import pandas as pd
df = pd.read_csv('test_data.csv')
df = df.set_index('Source')
ser = df.unstack('Source')
ser = ser.groupby(level=[0, 1]).sum()
ser = ser.sort_index(level=1)

At this point, ser looks like this

            Source
10/30/2017  A         35
10/31/2017  A         37
11/1/2017   A         39
11/2/2017   A         41
11/3/2017   A         43
11/4/2017   A         45
11/5/2017   A         47
10/30/2017  B         45
10/31/2017  B         47
11/1/2017   B         49
11/2/2017   B         51
11/3/2017   B         53
11/4/2017   B         55
11/5/2017   B         57
10/30/2017  C         55
10/31/2017  C         57
11/1/2017   C         59
11/2/2017   C         61
11/3/2017   C         63
11/4/2017   C         65
11/5/2017   C         67
dtype: int64

Anything else beyond this would be formatting and saving it to your liking.

Hope this Helps.