问:
While cloning a repository using GitHub Desktop, I'm facing 'Filename is too long' error
Unable to clone my repository from GitHub using GitHub Desktop application.

'Filename is too long' error thrown at final moment of cloning.

Anyone Please help to set up my repository.

答:
Make sure to use the latest Git for Windows, and, as mentioned in "Filename too long in git for windows"

```<code>git config --system core.longpaths true
</code>```

Then try to clone again.

The alternative would be to use a subst Y: C:\path\to\arent\folder, switch to the Y: drive, and clone from there. But with recent msys2 shell, that should not be needed anymore.

Body:
Make sure to use the latest Git for Windows, and, as mentioned in "Filename too long in git for windows"

git config --system core.longpaths true

Then try to clone again.

The alternative would be to use a subst Y: C:\path\to\arent\folder, switch to the Y: drive, and clone from there. But with recent msys2 shell, that should not be needed anymore.


来源: stackexchange

问:
How do you concat data in jQuery?
I am trying to send the 4 data tag's value to post, I can't figure out how to concat it though. I also need the data to be one data per line, so a
 in between will suffice.

```<code>$("#login-1").click(function() {
   send += text($("#" + iconId).data("name"));
   send += text($("#" + iconId).data("login1"));
   send += text($("#" + iconId).data("username1"));
   send += text($("#" + iconId).data("password1"));
   $("#post").text($("#" + iconId).send));
   cancel();
});
</code>```

This is jQuery and I want an easy to read solution, I am learning still.

For example

```<code>$("#post").text($("#" + iconId).data("name"));
</code>```

This sends the first data, but I can't get the rest to send.

答:
You could try like this.</p>

```<code>   $("#login-1").click(function() {
       var send='';
       send += $("#" + iconId).data("name")+"</br>";
       send += $("#" + iconId).data("login1")+"</br>";
       send += $("#" + iconId).data("username1")+"</br>";
       send += $("#" + iconId).data("password1")+"</br>";
       $("#post").html(send);
       cancel();
    });
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do you concat data in jQuery?

Body:
I am trying to send the 4 data tag's value to post, I can't figure out how to concat it though. I also need the data to be one data per line, so a
 in between will suffice.

$("#login-1").click(function() {
   send += text($("#" + iconId).data("name"));
   send += text($("#" + iconId).data("login1"));
   send += text($("#" + iconId).data("username1"));
   send += text($("#" + iconId).data("password1"));
   $("#post").text($("#" + iconId).send));
   cancel();
});

This is jQuery and I want an easy to read solution, I am learning still.

For example

$("#post").text($("#" + iconId).data("name"));

This sends the first data, but I can't get the rest to send.

Body:
You could try like this.

   $("#login-1").click(function() {
       var send='';
       send += $("#" + iconId).data("name")+"</br>";
       send += $("#" + iconId).data("login1")+"</br>";
       send += $("#" + iconId).data("username1")+"</br>";
       send += $("#" + iconId).data("password1")+"</br>";
       $("#post").html(send);
       cancel();
    });


问:
Array versus List<T>: When to use which?
```<code>MyClass[] array;
List<MyClass> list;
</code>```

What are the scenarios when one is preferable over the other? And why?

答: Lists in .NET are wrappers over arrays, and use an array internally.  The time complexity of operations on lists is the same as would be with arrays, however there is a little more overhead with all the added functionality / ease of use of lists (such as automatic resizing and the methods that come with the list class).  Pretty much, I would recommend using lists in all cases unless there is a compelling reason not to do so, such as if you need to write extremely optimized code, or are working with other code that is built around arrays.

OwnerDisplayName: Frederick

Body:
MyClass[] array;
List<MyClass> list;

What are the scenarios when one is preferable over the other? And why?


问:
"Uncaught ReferenceError: require is not defined" with Angular 2/webpack
I am working an HTML template from a graphic design company into my Angular 2 project using node and webpack.

The HTML pulls in various scripts like this:

```<code><script src="js/jquery.icheck.min.js"></script>
<script src="js/waypoints.min.js"></script>
</code>```

so I am requiring them in my component.ts:

```<code>var icheckJs = require('../js/jquery.icheck.min');
var waypointsJs = require('../js/waypoints.min');
</code>```

There are several other scripts too and some SASS which appears to be working correctly.

webpack is happy and build it all and an 'npm start' is successful too. However, when it reaches the browser, I get this complaint:

```<code>Uncaught ReferenceError: require is not defined node_modules/angular2/platform/browser.js:1 Uncaught ReferenceError: require is not defined
</code>```

which is actually thrown by this line from url.js:

```<code>var punycode = require('punycode');
</code>```

Is this a CommonJs require? I hadn't used this in web development before a few weeks ago so I'm still untangling the various requires from webback, CommonJs et at.

An extract from my webpack.config.js for the .js loader looks like this:

```<code>{ test: /\.js$/, loader: 'script' }
</code>```

How do I work around this error?

答:
For anyone that is looking for an answer but the above doesn't work:

Short

Add or Replace current target in webpack.config.js to target: 'web'

A bit longer

Webpack has different targets, if you've experimented with this and changed your target to node it will use 'require' to load chuncks.
The best thing is to make your target (or to add) target: 'web' in your webpack.config.js. This is the default target and loads your chuncks in a way the browser can handle.

I eventually found this solution here.

Body:
I am working an HTML template from a graphic design company into my Angular 2 project using node and webpack.

The HTML pulls in various scripts like this:

so I am requiring them in my component.ts:

var icheckJs = require('../js/jquery.icheck.min');
var waypointsJs = require('../js/waypoints.min');

There are several other scripts too and some SASS which appears to be working correctly.

webpack is happy and build it all and an 'npm start' is successful too. However, when it reaches the browser, I get this complaint:

Uncaught ReferenceError: require is not defined node_modules/angular2/platform/browser.js:1 Uncaught ReferenceError: require is not defined

which is actually thrown by this line from url.js:

var punycode = require('punycode');

Is this a CommonJs require? I hadn't used this in web development before a few weeks ago so I'm still untangling the various requires from webback, CommonJs et at.

An extract from my webpack.config.js for the .js loader looks like this:

{ test: /\.js$/, loader: 'script' }

How do I work around this error?


问:
What exactly are Static Constructor in C#?
I have couple of question regarding Static Constructor in C#.

What exactly are Static Constructor and how they are different from non-static Constructor.

How can we use them in our application ?

**Edited

```<code>public class Test
{
    // Static constructor:
    static Test()
    {
        Console.WriteLine("Static constructor invoked.");
    }

    public static void TestMethod()
    {
       Console.WriteLine("TestMethod invoked.");
    }
}

class Sample
{
    static void Main()
    {
        Test.TestMethod();
    }
}
</code>```

Output :
Static constructor invoked.
TestMethod invoked.
So, this means that static constructor will be called once. if we again call  Test.TestMethod(); static constructor won't invoke.

Any pointer or suggestion would be appreciated
 '

Thanks

答:
it runs when class is loaded.

It will print :
{

hi from static A

A

}

```<code>public class A{
  static A{
     print("hi from static A");
  }

  public A() {
    print("A");
  }

  main() {
      new A();
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have couple of question regarding Static Constructor in C#.

What exactly are Static Constructor and how they are different from non-static Constructor.

How can we use them in our application ?

**Edited

public class Test
{
    // Static constructor:
    static Test()
    {
        Console.WriteLine("Static constructor invoked.");
    }

    public static void TestMethod()
    {
       Console.WriteLine("TestMethod invoked.");
    }
}

class Sample
{
    static void Main()
    {
        Test.TestMethod();
    }
}

Output :
Static constructor invoked.
TestMethod invoked.
So, this means that static constructor will be called once. if we again call  Test.TestMethod(); static constructor won't invoke.

Any pointer or suggestion would be appreciated
 '

Thanks

Body:
it runs when class is loaded.

It will print :
{

hi from static A

A

}

public class A{
  static A{
     print("hi from static A");
  }

  public A() {
    print("A");
  }

  main() {
      new A();
  }
}


问:
Javascript - only allow numbers in input field & a character counter
I have an input field. I want it so that only numbers can be used in the input field.

Below the input field I also want a counter that shows the number of characters currently inside the input field.

HTML:

```<code><input type="text" id="test" onkeypress="return isNumber(event)" />
<p id='demo'></p>
</code>```

Javascript:

```<code>function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    let inputValue = document.getElementById('test').value;
    let inputLength = inputValue.length;
    document.getElementById("demo").innerHTML = inputLength;
    return true;
    }
</code>```

jsfiddle:
http://jsfiddle.net/s831nwej/

It almost works. The problem is that the character counter below the input box is always 1 character less than the total number of characters in the input field. I think there is some quark about the keypress event that I am missing.

答:
Firstly if you want inputs to be only numbers use type="number" instead of type "text" and the count is always less than one because your event handling for checking the value should be on onKeyUp instead of onKeyPress

check this snippet

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    let inputValue = document.getElementById('test').value;
  let inputLength = inputValue.length;
  document.getElementById("demo").innerHTML = inputLength;
    return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="test" onkeyup="return isNumber(event)" />
<p id='demo'></p></code>```

Body:
I have an input field. I want it so that only numbers can be used in the input field.

Below the input field I also want a counter that shows the number of characters currently inside the input field.

HTML:

<input type="text" id="test" onkeypress="return isNumber(event)" />

Javascript:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    let inputValue = document.getElementById('test').value;
    let inputLength = inputValue.length;
    document.getElementById("demo").innerHTML = inputLength;
    return true;
    }

jsfiddle:
http://jsfiddle.net/s831nwej/

It almost works. The problem is that the character counter below the input box is always 1 character less than the total number of characters in the input field. I think there is some quark about the keypress event that I am missing.

Body:
Firstly if you want inputs to be only numbers use type="number" instead of type "text" and the count is always less than one because your event handling for checking the value should be on onKeyUp instead of onKeyPress

check this snippet

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    let inputValue = document.getElementById('test').value;
  let inputLength = inputValue.length;
  document.getElementById("demo").innerHTML = inputLength;
    return true;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="test" onkeyup="return isNumber(event)" />
<p id='demo'></p>


问:
Polymer2.0 - Looking for json format icon - { } using paper icon
I was looking for json format icon from the polymer iron icons list which is not available

something similar to http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/high-resolution-dark-blue-denim-jeans-icons-alphanumeric/072287-high-resolution-dark-blue-denim-jeans-icon-alphanumeric-bracket-curley.png

I am tried below workaround but it didnt work either

```<code><paper-icon-button id="json">{}</paper-icon-button>
</code>```

https://codepen.io/nagasai/pen/rwqYYZ

```<code><head>
<base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="paper-icon-button/paper-icon-button.html">
<link rel="import" href="iron-icons/iron-icons.html">
<div class="toolbar">
</head>

<body>
      <paper-icon-button id="json">{}</paper-icon-button>
      <paper-icon-button id="save" icon="icons:save"></paper-icon-button>
</body>
</code>```

答:
<paper-icon-button> has a src property to specify the URL of the desired image. You could even specify the .png URL you indicated in the question, like this:

```<code><paper-icon-button src="http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/high-resolution-dark-blue-denim-jeans-icons-alphanumeric/072287-high-resolution-dark-blue-denim-jeans-icon-alphanumeric-bracket-curley.png"></paper-icon-button>
</code>```

codepen

Body:
I was looking for json format icon from the polymer iron icons list which is not available

something similar to http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/high-resolution-dark-blue-denim-jeans-icons-alphanumeric/072287-high-resolution-dark-blue-denim-jeans-icon-alphanumeric-bracket-curley.png

I am tried below workaround but it didnt work either

<paper-icon-button id="json">{}</paper-icon-button>

https://codepen.io/nagasai/pen/rwqYYZ

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

      <paper-icon-button id="json">{}</paper-icon-button>
      <paper-icon-button id="save" icon="icons:save"></paper-icon-button>

Body:
<paper-icon-button> has a src property to specify the URL of the desired image. You could even specify the .png URL you indicated in the question, like this:

<paper-icon-button src="http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/high-resolution-dark-blue-denim-jeans-icons-alphanumeric/072287-high-resolution-dark-blue-denim-jeans-icon-alphanumeric-bracket-curley.png"></paper-icon-button>

codepen


问:
Routing Laravel namepsace issue
When I remove the inital use Illuminate\Http\Request and add use App\Item instead in the Controller file, the items/create route responds with a 404.  How can I still use the App\Item namespace and get to the items/create route? I've tried adding both, but does not work.

web.php

```<code>Route::get('items', 'ItemsController@index');
Route::get('items/{item}', 'ItemsController@show');
Route::get('items/create', 'ItemsController@create');
</code>```

ItemsController.php

```<code><?php

namespace App\Http\Controllers;

use App\Item;

class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show(Item $item){
      return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}
</code>```

Item.php

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    //
}
</code>```

答:
Can you try this, please.</p>

```<code><?php

namespace App\Http\Controllers;
use App\Item;
class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show($id){
      $item= Item::find($id);
        return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}
</code>```

Title: Routing Laravel namepsace issue

Body:
When I remove the inital use Illuminate\Http\Request and add use App\Item instead in the Controller file, the items/create route responds with a 404.  How can I still use the App\Item namespace and get to the items/create route? I've tried adding both, but does not work.

web.php

Route::get('items', 'ItemsController@index');
Route::get('items/{item}', 'ItemsController@show');
Route::get('items/create', 'ItemsController@create');

ItemsController.php

<?php

namespace App\Http\Controllers;

use App\Item;

class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show(Item $item){
      return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}

Item.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    //
}

Body:
Can you try this, please.

<?php

namespace App\Http\Controllers;
use App\Item;
class ItemsController extends Controller
{
    public function index(){
      $items = Item::all();
      return view('items.index', ['items' => $items]);
    }

    public function show($id){
      $item= Item::find($id);
        return $item->body;
    }

    public function create(){
      return view('items.create');
    }
}


问:
Integrate OpenCV into Xcode using Swift Language
I try to integrate OpenCV into Xcode by following this tutorial.
https://www.youtube.com/watch?v=ywUBHqxwM5Q

edit: I have tried more tutorials and always see those type of warnings.

However, I found a lot of warning after doing this. I have solved some of them but there is still a big chunk of warnings.

The warning is called

```<code>Apple Mach-O Linker Warning Group:

direct access in function '___cxx_global_var_init' from
file '/Users/user/Desktop/OpenCV-SwiftTest/OpenCV-
SwiftTest/opencv2.framework/opencv2(flann.o)' to global weak symbol
'guard variable for
cvflann::anyimpl::SinglePolicy<cvflann::anyimpl::empty_any>::policy'
from file
'/Users/user/Library/Developer/Xcode/DerivedData/OpenCV-
SwiftTest-awmplbufjrmhqrbptnqhlxqxvptp/Build/Intermediates/OpenCV-
SwiftTest.build/Debug-iphonesimulator/OpenCV-SwiftTest.build/Objects-
normal/x86_64/OpenCVWrapper.o' means the weak symbol cannot be
overridden at runtime.
This was likely caused by different translation units being compiled
with different visibility settings.
</code>```

I found some related answers such as

```<code>  1.Symbols Hidden by Default
  2.Inline Methods Hidden
</code>```

Since the tutorial only includes OpenCV for one project and I have checked its setting with the above requirement.

It just a simple project where is the different translation units?

Thanks for any help

答:
Swift cannot work with C++ directly, so you need to use at a minimum Objective C wrappers to communicate with OpenCV.

For example, I have the following method in my C++ class:

```<code>cv::Mat crop(const cv::Mat &src, cv::Rect2f &rect);
</code>```

I then have an Objective-C method that exists in an Objective-C++ files (this means the filename in XCode has a second m (ex: MyWrapper.mm).

The function to call this in Obj-C would look something like this:

```<code>- (void)crop:(nonnull UIImage *)source
        rect:(CGRect)rect
completionHandler:(nonnull ImageCompletionHandler)completionHandler {
    MAT src = [Conversion cvMatWithImage:source];
    RECT_2F rect_2f = [Conversion cvRectFromRect:rect];
    MAT dst = self.basicPtr->crop(src, rect_2f);

    completionHandler([Conversion imageFromCVMat:dst]);
}
</code>```

The first Conversion call converts a UIImage into a Mat for OpenCV to process

The second Conversion call converts a CGRect into a cv::Rect2f

The self.basicPts->crop(src, rect_2f) function is using a pointer to my class to access the crop function above

Finally, I have a closure that takes the Mat object OpenCV gives me and converts it into a UIImage for iOS to work with

Then, back in Swift land, you need to first have a bridging header for the Objective-C wrapper so that Swift can access it.

Once you have that, then calling the function is trivial:

```<code>func crop(with image: UIImage, rect: CGRect) {
    let wrapper = BasicWrapper()
    wrapper.crop(image, rect: rect) { (image) in
        // Handle image
    }
}
</code>```

It took a lot of work to fill in all those pieces, but if you look around here, you can find all the pieces you need (I know I did).

Body:
I try to integrate OpenCV into Xcode by following this tutorial.
https://www.youtube.com/watch?v=ywUBHqxwM5Q

edit: I have tried more tutorials and always see those type of warnings.

However, I found a lot of warning after doing this. I have solved some of them but there is still a big chunk of warnings.

The warning is called

Apple Mach-O Linker Warning Group:

direct access in function '___cxx_global_var_init' from
file '/Users/user/Desktop/OpenCV-SwiftTest/OpenCV-
SwiftTest/opencv2.framework/opencv2(flann.o)' to global weak symbol
'guard variable for
cvflann::anyimpl::SinglePolicy<cvflann::anyimpl::empty_any>::policy'
from file
'/Users/user/Library/Developer/Xcode/DerivedData/OpenCV-
SwiftTest-awmplbufjrmhqrbptnqhlxqxvptp/Build/Intermediates/OpenCV-
SwiftTest.build/Debug-iphonesimulator/OpenCV-SwiftTest.build/Objects-
normal/x86_64/OpenCVWrapper.o' means the weak symbol cannot be
overridden at runtime.
This was likely caused by different translation units being compiled
with different visibility settings.

I found some related answers such as

  1.Symbols Hidden by Default
  2.Inline Methods Hidden

Since the tutorial only includes OpenCV for one project and I have checked its setting with the above requirement.

It just a simple project where is the different translation units?

Thanks for any help

Body:
Swift cannot work with C++ directly, so you need to use at a minimum Objective C wrappers to communicate with OpenCV.

For example, I have the following method in my C++ class:

cv::Mat crop(const cv::Mat &src, cv::Rect2f &rect);

I then have an Objective-C method that exists in an Objective-C++ files (this means the filename in XCode has a second m (ex: MyWrapper.mm).

The function to call this in Obj-C would look something like this:

- (void)crop:(nonnull UIImage *)source
        rect:(CGRect)rect
completionHandler:(nonnull ImageCompletionHandler)completionHandler {
    MAT src = [Conversion cvMatWithImage:source];
    RECT_2F rect_2f = [Conversion cvRectFromRect:rect];
    MAT dst = self.basicPtr->crop(src, rect_2f);

    completionHandler([Conversion imageFromCVMat:dst]);
}

The first Conversion call converts a UIImage into a Mat for OpenCV to process

The second Conversion call converts a CGRect into a cv::Rect2f

The self.basicPts->crop(src, rect_2f) function is using a pointer to my class to access the crop function above

Finally, I have a closure that takes the Mat object OpenCV gives me and converts it into a UIImage for iOS to work with

Then, back in Swift land, you need to first have a bridging header for the Objective-C wrapper so that Swift can access it.

Once you have that, then calling the function is trivial:

func crop(with image: UIImage, rect: CGRect) {
    let wrapper = BasicWrapper()
    wrapper.crop(image, rect: rect) { (image) in
        // Handle image
    }
}

It took a lot of work to fill in all those pieces, but if you look around here, you can find all the pieces you need (I know I did).


问:
Microsoft.DotNet.Docker.CommandLineClientException: client version 1.22 is too old
I get the following error  building my ASPNETCORE Web Api Project.
When I created the project I checked Docker For Windows.</p>

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   MSB4018 The "CleanWorkspace" task failed unexpectedly.
Microsoft.DotNet.Docker.CommandLineClientException: client version 1.22 is too old. Minimum supported API version is 1.24, please upgrade your client to a newer version.

For more troubleshooting information, go to http://aka.ms/DockerToolsTroubleshooting ---> Microsoft.DotNet.Docker.CommandLineClientException: client version 1.22 is too old. Minimum supported API version is 1.24, please upgrade your client to a newer version
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DotNet.Docker.DockerComposeClient.<ExecuteAsync>d__18.MoveNext()
   --- End of inner exception stack trace ---
   at Microsoft.DotNet.Docker.DockerComposeClient.<ExecuteAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DotNet.Docker.DockerComposeClient.<DownAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DotNet.Docker.DockerWorkspace.<CleanWorkspaceAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DotNet.Docker.BuildTasks.DockerBaseTask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() docker-compose  C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\VisualStudio\v15.0\Docker\Microsoft.VisualStudio.Docker.Compose.targets  208
</code>```

答: This was because I was switched to Windows containers. Switching to Unix resolved it.</p>

Body:
I get the following error  building my ASPNETCORE Web Api Project.
When I created the project I checked Docker For Windows.

Severity    Code    Description Project File    Line    Suppression State
Error   MSB4018 The "CleanWorkspace" task failed unexpectedly.
Microsoft.DotNet.Docker.CommandLineClientException: client version 1.22 is too old. Minimum supported API version is 1.24, please upgrade your client to a newer version.

For more troubleshooting information, go to http://aka.ms/DockerToolsTroubleshooting ---> Microsoft.DotNet.Docker.CommandLineClientException: client version 1.22 is too old. Minimum supported API version is 1.24, please upgrade your client to a newer version
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DotNet.Docker.DockerComposeClient.<ExecuteAsync>d__18.MoveNext()
   --- End of inner exception stack trace ---
   at Microsoft.DotNet.Docker.DockerComposeClient.<ExecuteAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DotNet.Docker.DockerComposeClient.<DownAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DotNet.Docker.DockerWorkspace.<CleanWorkspaceAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.DotNet.Docker.BuildTasks.DockerBaseTask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() docker-compose  C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\VisualStudio\v15.0\Docker\Microsoft.VisualStudio.Docker.Compose.targets  208


问:
Nginx Live transcoding with ffmpeg
I'm live streaming video to my server(It's external somewhere in the world).
And what I'm trying to do here, is that my server will transcode the input to a lower bitrate before it pushes it to the video site like twitch and so on.

And I'm doing this on windows. I have tried to google around watched youtube videos. and so on.. But couldn't find any solution for it. So here is what I have at this moment(not working).

In my nginx.conf:

```<code>rtmp {
server {
    listen 1935;
    chunk_size 8192;

    application code {
        live on;

    }

    application twitch {
        push rtmp://live-ams.twitch.tv/app/live_xxxxxxxxxxxxxxxxx;
    }
}
</code>```

So here the application code is receving the stream from my computer at home. I'm using ffmpeg to transcode it.

And here is my batch file(That I have to start manualy. Can't start it within the config of nginx on windows.)

```<code>ffmpeg -i rtmp://localhost/code -vcodec flv -acodec copy -s 1280x720 -f flv rtmp://localhost/twitch
pause
</code>```

Right now It's just downscaling but that is okay. So this is supposed to send the stream back to the "twitch" application in my nginx config. And then nginx will stream it to twitch.

But when I launch my ffmpeg bat file.. I get this:

So it's here my road ends. Anyone knows how to do this?

Thanks in advance :) Stian

答:
The reason you are getting the rtmp packet header errors is because it was expecting a stream key after the localhost/code so the command should of been

```<code>ffmpeg -i rtmp://localhost/code/streamKey -vcodec flv -acodec copy -s 1280x720 -f flv rtmp://localhost/twitch/streamKey
</code>```

so with whatever software you were using that whole url has to be provided to the encoder you are using before transcoding.

Just a note that the command above doesnt do any sort of downscaling or changing output bitrates or anything. You may want to take a look at more articles such as this. Stuff like that should point you into the right direction on downscaling and the other stuff needed for transcoding.

Title: Nginx Live transcoding with ffmpeg

Body:
I'm live streaming video to my server(It's external somewhere in the world).
And what I'm trying to do here, is that my server will transcode the input to a lower bitrate before it pushes it to the video site like twitch and so on.

And I'm doing this on windows. I have tried to google around watched youtube videos. and so on.. But couldn't find any solution for it. So here is what I have at this moment(not working).

In my nginx.conf:

rtmp {
server {
    listen 1935;
    chunk_size 8192;

    application code {
        live on;

    }

    application twitch {
        push rtmp://live-ams.twitch.tv/app/live_xxxxxxxxxxxxxxxxx;
    }
}

So here the application code is receving the stream from my computer at home. I'm using ffmpeg to transcode it.

And here is my batch file(That I have to start manualy. Can't start it within the config of nginx on windows.)

ffmpeg -i rtmp://localhost/code -vcodec flv -acodec copy -s 1280x720 -f flv rtmp://localhost/twitch
pause

Right now It's just downscaling but that is okay. So this is supposed to send the stream back to the "twitch" application in my nginx config. And then nginx will stream it to twitch.

But when I launch my ffmpeg bat file.. I get this:

So it's here my road ends. Anyone knows how to do this?

Thanks in advance :) Stian

Body:
The reason you are getting the rtmp packet header errors is because it was expecting a stream key after the localhost/code so the command should of been

ffmpeg -i rtmp://localhost/code/streamKey -vcodec flv -acodec copy -s 1280x720 -f flv rtmp://localhost/twitch/streamKey

so with whatever software you were using that whole url has to be provided to the encoder you are using before transcoding.

Just a note that the command above doesnt do any sort of downscaling or changing output bitrates or anything. You may want to take a look at more articles such as this. Stuff like that should point you into the right direction on downscaling and the other stuff needed for transcoding.


问:
codeigniter login after email verified
I am trying to make sure user can login after confirming their email verification in which STATUS in the database changes from 0 to 1. how do I log users in based on the change of status in the database. Thanks in advance

MODEL:

```<code>   public function login($username, $password){
    //validation
    $this->db->where('username', $username);
    $this->db->where('password', $password);

    $result = $this->db->get('users');
    if($result->num_rows() == 1){
        return $result->row(0)->id;

    } else {
        return FALSE;
    }
}
</code>```

CONTROLLER:

```<code>   public function login(){
    $data['title'] = 'Login';

    $this->form_validation-> set_rules('username', 'Username', 'required');
    $this->form_validation-> set_rules('password', 'Password', 'required');

    if($this->form_validation->run() === FALSE){

    $this->load->view('templates/header');
    $this->load->view('users/login', $data);
    $this->load->view('templates/footer');
    } else {

        // fetching user
    $username = $this->input->post('username');
        //password
    $password = ($this->input->post('password'));

    //login user
    $user_id = $this->user_model->login($username, $password);

    if($user_id){
        //creating session
        $user_data = array(
            'user_id' => $user_id,
            'username' => $username,
            'logged_in' => TRUE,

        );
        $this->session->set_userdata($user_data);
                // Set message to be sent
    $this->session->set_flashdata('user_login', 'Welcome');
    redirect('posts');
    } else {
        // Set message to be sent
    $this->session->set_flashdata('login_fail', 'Login Failed');
    redirect('users/login');
    }

    }

}
</code>```

答:
Considering you have the verification system ready and you're changing the status column in db from 0 to 1.
Using the code below, you will be able to perform login based on that requirement by informing the user in case he isn't verified.

Model (return with proper errors):

```<code>public function login($username, $password){

  $this->db->where('username', $username);
  $this->db->where('password', $password);

  $result = $this->db->get('users');
  if($result->num_rows() == 1){
     $user=$result->row_array();
     if($user['status']==1){ // user is verified
       $response['error']="false";
       $response['user']=$user['id'];
     }
     else{ // not verified
        $response['error']="true";
        $response['error_msg']="Please verify your email first!";
     }

  }
  else { // credentials mismatch
     $response['error']="true";
     $response['error_msg']="Invalid username or password";
  }
  return $response;
}
</code>```

Controller (use returned array from model)

```<code>//login user
$login = $this->user_model->login($username, $password);
if($login['error']){ // login failed
   $this->session->set_flashdata('login_fail', $login['error']);
   redirect('users/login');
}
else{ // success
    $user=$login['user'];
    // do whatever you want after successful login
}
</code>```

Title: codeigniter login after email verified

Body:
I am trying to make sure user can login after confirming their email verification in which STATUS in the database changes from 0 to 1. how do I log users in based on the change of status in the database. Thanks in advance

MODEL:

   public function login($username, $password){
    //validation
    $this->db->where('username', $username);
    $this->db->where('password', $password);

    $result = $this->db->get('users');
    if($result->num_rows() == 1){
        return $result->row(0)->id;

    } else {
        return FALSE;
    }
}

CONTROLLER:

   public function login(){
    $data['title'] = 'Login';

    $this->form_validation-> set_rules('username', 'Username', 'required');
    $this->form_validation-> set_rules('password', 'Password', 'required');

    if($this->form_validation->run() === FALSE){

    $this->load->view('templates/header');
    $this->load->view('users/login', $data);
    $this->load->view('templates/footer');
    } else {

        // fetching user
    $username = $this->input->post('username');
        //password
    $password = ($this->input->post('password'));

    //login user
    $user_id = $this->user_model->login($username, $password);

    if($user_id){
        //creating session
        $user_data = array(
            'user_id' => $user_id,
            'username' => $username,
            'logged_in' => TRUE,

        );
        $this->session->set_userdata($user_data);
                // Set message to be sent
    $this->session->set_flashdata('user_login', 'Welcome');
    redirect('posts');
    } else {
        // Set message to be sent
    $this->session->set_flashdata('login_fail', 'Login Failed');
    redirect('users/login');
    }

    }

}

Body:
Considering you have the verification system ready and you're changing the status column in db from 0 to 1.
Using the code below, you will be able to perform login based on that requirement by informing the user in case he isn't verified.

Model (return with proper errors):

public function login($username, $password){

  $this->db->where('username', $username);
  $this->db->where('password', $password);

  $result = $this->db->get('users');
  if($result->num_rows() == 1){
     $user=$result->row_array();
     if($user['status']==1){ // user is verified
       $response['error']="false";
       $response['user']=$user['id'];
     }
     else{ // not verified
        $response['error']="true";
        $response['error_msg']="Please verify your email first!";
     }

  }
  else { // credentials mismatch
     $response['error']="true";
     $response['error_msg']="Invalid username or password";
  }
  return $response;
}

Controller (use returned array from model)

//login user
$login = $this->user_model->login($username, $password);
if($login['error']){ // login failed
   $this->session->set_flashdata('login_fail', $login['error']);
   redirect('users/login');
}
else{ // success
    $user=$login['user'];
    // do whatever you want after successful login
}


问:
Fatal error: Uncaught Error: Call to a member function bindParam() on string i
I am trying to create a registation page and succesfully created it and want to validitate it to only one email account so that a user can create an account by an email only once and the next time it should give an error saying you have already registered with the email account but in the trail I got an error saying the fallowing

```<code>Fatal error: Uncaught Error: Call to a member function bindParam() on string
in C:\xampp\htdocs\sign\register.php:20 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\sign\register.php on line 20
</code>```

and my php registration code is as fallows

```<code><?php
include('connection.php');
$form = $_POST;
$username = $form['username'];
$password = $form['password'];
$repass = $form['repass'];
$email = $form['email'];
$date = $form['date'];
$month = $form['month'];
$year = $form['year'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email please type a valid one";
}
else{
if($username !='' && $password !='' && $repass!='' && $email !='' &&
$date!='' && $month !='' && $year !='')
{
if($password == $repass)
{
$query = "SELECT * FROM users where email = :email AND username =
:username";
$query->bindParam(':username',$username);
$query->bindParam(':email',$email);
$count1 = $query->rowCount();
if($count> 0)
{
    echo "soryy the email you are trying to register is already
registered!";
}
else{

$insert = $connection->prepare("INSERT INTO users
(username,password,email,date,month,year)  values (:username, :password,
:email, :date, :month, :year)");
$insert->bindParam(':username',$username);
$insert->bindParam(':password',$password);
$insert->bindParam(':email',$email);
$insert->bindParam(':date',$date);
$insert->bindParam(':month',$month);
$insert->bindParam(':year',$year);
$out = $insert->execute();
if(isset($out)){
    echo "thankyou you have sucessfully registered";
}
else{
    echo " sorry some error occured please try again!";
}
}
}
else{
echo " passwords do not match";
die();
}
}
else{
echo " you have not filled the registration form completely so please it";
}
}
?>
</code>```

can anyone help me out in solving the issue thankyou

答:
you have to bind params on prepared statement. change select query statement to

```<code>$query = $connection->prepare("SELECT * FROM users where email = :email AND username =
:username");
</code>```

EDIT

To count number of rows from select query use fetchColumn. Also you are assigning value to $count1   and using $count. So use same variable name

```<code>$count = $query->fetchColumn();
if($count> 0)
{
    echo "soryy the email you are trying to register is already
registered!";
}
</code>```

Body:
I am trying to create a registation page and succesfully created it and want to validitate it to only one email account so that a user can create an account by an email only once and the next time it should give an error saying you have already registered with the email account but in the trail I got an error saying the fallowing

Fatal error: Uncaught Error: Call to a member function bindParam() on string
in C:\xampp\htdocs\sign\register.php:20 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\sign\register.php on line 20

and my php registration code is as fallows

<?php
include('connection.php');
$form = $_POST;
$username = $form['username'];
$password = $form['password'];
$repass = $form['repass'];
$email = $form['email'];
$date = $form['date'];
$month = $form['month'];
$year = $form['year'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email please type a valid one";
}
else{
if($username !='' && $password !='' && $repass!='' && $email !='' &&
$date!='' && $month !='' && $year !='')
{
if($password == $repass)
{
$query = "SELECT * FROM users where email = :email AND username =
:username";
$query->bindParam(':username',$username);
$query->bindParam(':email',$email);
$count1 = $query->rowCount();
if($count> 0)
{
    echo "soryy the email you are trying to register is already
registered!";
}
else{

$insert = $connection->prepare("INSERT INTO users
(username,password,email,date,month,year)  values (:username, :password,
:email, :date, :month, :year)");
$insert->bindParam(':username',$username);
$insert->bindParam(':password',$password);
$insert->bindParam(':email',$email);
$insert->bindParam(':date',$date);
$insert->bindParam(':month',$month);
$insert->bindParam(':year',$year);
$out = $insert->execute();
if(isset($out)){
    echo "thankyou you have sucessfully registered";
}
else{
    echo " sorry some error occured please try again!";
}
}
}
else{
echo " passwords do not match";
die();
}
}
else{
echo " you have not filled the registration form completely so please it";
}
}
?>

can anyone help me out in solving the issue thankyou

Body:
you have to bind params on prepared statement. change select query statement to

$query = $connection->prepare("SELECT * FROM users where email = :email AND username =
:username");

EDIT

To count number of rows from select query use fetchColumn. Also you are assigning value to $count1   and using $count. So use same variable name

$count = $query->fetchColumn();
if($count> 0)
{
    echo "soryy the email you are trying to register is already
registered!";
}


问:
Check if key/value pairs exist within array
I need to check if a set of query params exists within a larger set of query params. For example, I want to check if array('option' => 'com_pages', 'view' => 'page'), exists within:

```<code>Array
(
    [option] => com_pages
    [format] => html
    [view] => page
)
</code>```

or

```<code>Array
(
    [option] => com_archive
)
</code>```

I tried to find a php function that would provide this kind of search, but could't find any that matched what I was looking for. So I created the below function:

```<code>function checkRoute($params, $request) {
    foreach($params as $key => $value) {
        if(!array_key_exists($key, $request)) {
            return false;
        }

        if($request[$key] != $value) {
            return false;
        }
    }

    return true;
}
</code>```

Where $request is an array of the current request's query params.

Is there a quicker way to do this with array functions that I'm missing?

答:
You could use an array_intersect_assoc for the two array and check if the count of the result is equal to the number of expected  match...

```<code> if ( count(array_intersect_assoc($a, $b)) == count($a) ){
   // then match ...
 }
</code>```

Body:
I need to check if a set of query params exists within a larger set of query params. For example, I want to check if array('option' => 'com_pages', 'view' => 'page'), exists within:

Array
(
    [option] => com_pages
    [format] => html
    [view] => page
)

or

Array
(
    [option] => com_archive
)

I tried to find a php function that would provide this kind of search, but could't find any that matched what I was looking for. So I created the below function:

function checkRoute($params, $request) {
    foreach($params as $key => $value) {
        if(!array_key_exists($key, $request)) {
            return false;
        }

        if($request[$key] != $value) {
            return false;
        }
    }

    return true;
}

Where $request is an array of the current request's query params.

Is there a quicker way to do this with array functions that I'm missing?

Body:
You could use an array_intersect_assoc for the two array and check if the count of the result is equal to the number of expected  match...

 if ( count(array_intersect_assoc($a, $b)) == count($a) ){
   // then match ...
 }

ContentLicense: CC BY-SA 4.0


问:
No visible @interface for 'NSFontManager' declares the selector 'fontpanel:'
ALL,

The following code:

in fontpropertypage.cpp:

```<code>#import "AppKit/AppKit.h"

CFontPropertyPage::CFontPropertyPage()
{
    m_font = font;
    NSFontManager *manager = [NSFontManager sharedFontManager];
    NSFontPanel *panel = [manager fontpanel:true];
}
</code>```

In the fontpropertypage.mm

```<code>#include "fontpropertypage.cpp"
</code>```

I'm receiving the error in subject from the Xcode when trying to get NSFontPanel pointer.

Can someone please help with the fix?

Both files are present in the Xcode project.

TIA!!

答:
NSFontManager and NSFontPanel are GUI objects in Cocoa and can only be accessed with Objective-C (or Objective C++, your .mm file).

This code would surely compile if you put it directly in the .mm file, but having it in a .cpp file that you're including is wierd (I usually only ever include header files like .h or .hpp).

I suggest putting that class directly into the .mm file.

Also, the code you have up there has a few errors in general:

```<code>CFontPropertyPage::CFontPropertyPage()
{
    // m_font should be a class member ; what about font?
    m_font = font;
    NSFontManager *manager = [NSFontManager sharedFontManager];
    // fontPanel needs a capital P
    NSFontPanel *panel = [manager fontPanel:true];
}
</code>```

Body:
ALL,

The following code:

in fontpropertypage.cpp:

#import "AppKit/AppKit.h"

CFontPropertyPage::CFontPropertyPage()
{
    m_font = font;
    NSFontManager *manager = [NSFontManager sharedFontManager];
    NSFontPanel *panel = [manager fontpanel:true];
}

In the fontpropertypage.mm

#include "fontpropertypage.cpp"

I'm receiving the error in subject from the Xcode when trying to get NSFontPanel pointer.

Can someone please help with the fix?

Both files are present in the Xcode project.

TIA!!

Body:
NSFontManager and NSFontPanel are GUI objects in Cocoa and can only be accessed with Objective-C (or Objective C++, your .mm file).

This code would surely compile if you put it directly in the .mm file, but having it in a .cpp file that you're including is wierd (I usually only ever include header files like .h or .hpp).

I suggest putting that class directly into the .mm file.

Also, the code you have up there has a few errors in general:

CFontPropertyPage::CFontPropertyPage()
{
    // m_font should be a class member ; what about font?
    m_font = font;
    NSFontManager *manager = [NSFontManager sharedFontManager];
    // fontPanel needs a capital P
    NSFontPanel *panel = [manager fontPanel:true];
}


问:
Upgraded to Rails 3 and Ruby 1.9 and Unicode data in Postgres database now returning as ASCII (potential bug?)
I'm running into a really strange phenomena after upgrading from Rails 2.3/Ruby 1.8 to Rails 3/Ruby 1.9. As I mentioned in the title, I'm using Postgres, along with the pg gem 0.10.0.

When I make a call to a model's string or text fields that contain Unicode, it works correctly, and they are returned with an encoding of UTF-8.

However, I also make use of serialized Hashes in a number of models, and whenever I make a call to read their contents (which worked perfectly prior to the upgrade), I get the following puzzling behavior:

If the contents contains Unicode data, it returns as ASCII, and is displayed as escaped characters.

If the contents contains ASCII data, it returns as UTF-8 (correctly), and is properly displayed.

I can simply re-encode the Unicode-returned-as-ASCII strings back to UTF-8, and everything will work fine. However, that is definitely a hack, and doesn't strike me as a good approach.

Is there a way to make serialized UTF-8 fields display correctly? If this is a bug somewhere, any idea where, and if it's known already?

答: Does this answer it? Why are all strings ASCII-8BIT after I upgraded to Rails 3?</p>


问:
Understanding THE_REQUEST variable in RewriteCond
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/

I understand everything in the line above except for the following segment:

([#?][^\ ]*)?\ HTTP/

I've done some research and found out that the square brackets are used to match any one of the characters within them. However, I have also learned that ? is used to make the preceding token optional and that ^ means "match start."

As such, why do the square brackets in the segment above contain both ? and ^? I thought that the square brackets were simply used as a "character class."

Also, what is the purpose of HTTP/ in the segment specifically? All of my searches have come to no avail.

答:
First understand what is THE_REQUEST.

THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of some rewrite rules. Example value of this variable is:

```<code>GET /index.php?id=123 HTTP/1.1
</code>```

Now the part you want more clarification on:

```<code>([#?][^\ ]*)?\ HTTP/
</code>```

Here is what is happening here:

It matches ? or # literally since inside [...] almost all special characters are matched literally

Followed by a negated character class that matches 0 or more characters of anything except a space

? after ([#?][^\ ]*) makes it an optional match

\ HTTP matches a space followed by HTTP

Now let me tell you that matching # is not needed here since a web server never receives a URL after #. That is all handled by client browsers.

It is better to use this RewriteCond:

```<code>RewriteCond %{THE_REQUEST} ^(.+)\.php(\?\S*)?\ HTTP/ [NC]
</code>```

Body:
First understand what is THE_REQUEST.

THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of some rewrite rules. Example value of this variable is:

GET /index.php?id=123 HTTP/1.1

Now the part you want more clarification on:

([#?][^\ ]*)?\ HTTP/

Here is what is happening here:

It matches ? or # literally since inside [...] almost all special characters are matched literally

Followed by a negated character class that matches 0 or more characters of anything except a space

? after ([#?][^\ ]*) makes it an optional match

\ HTTP matches a space followed by HTTP

Now let me tell you that matching # is not needed here since a web server never receives a URL after #. That is all handled by client browsers.

It is better to use this RewriteCond:

RewriteCond %{THE_REQUEST} ^(.+)\.php(\?\S*)?\ HTTP/ [NC]


问:
ImportError: libcusolver.so.8.0: cannot open shared object file: No such file or directory
Possible duplicate of this question.
I have a gpu account to whom I connect through putty (ssh login). I have created a virtualenv there and I am installing tenorflow through pip for gpu. Everything works fine, when I run command

```<code>$ pip list
</code>```

following list is being shown:

```<code> backports.weakref (1.0rc1)
 bleach (1.5.0)
 funcsigs (1.0.2)
 html5lib (0.9999999)
 Markdown (2.6.8)
 mock (2.0.0)
 numpy (1.13.1)
 olefile (0.44)
 pbr (3.1.1)
 Pillow (4.2.1)
 pip (9.0.1)
 protobuf (3.3.0)
 setuptools (36.0.1)
 six (1.10.0)
 tensorflow-gpu (1.2.1)
 Werkzeug (0.12.2)
 wheel (0.29.0)
</code>```

But when I run:

```<code>$ python
>>> import tensorflow
</code>```

It shows the following error:

```<code>  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/__init__.py", line 24, in <module>
  from tensorflow.python import *
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/__init__.py", line 49, in <module>
  from tensorflow.python import pywrap_tensorflow
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
  raise ImportError(msg)
  ImportError: Traceback (most recent call last):
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
  from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in
  <module>
  _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in
  swig_import_helper
  _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname,
  description)
  ImportError: libcusolver.so.8.0: cannot open shared object file: No such
  file or directory
  Failed to load the native TensorFlow runtime.
  See https://www.tensorflow.org/install/install_sources#common_installation_problems
  for some common reasons and solutions.  Include the entire stack trace
  above this error message when asking for help.
</code>```

I have also set my environment variables like this:

```<code>  export CUDA_HOME=/opt/cuda
  export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$CUDA_HOME/lib64:$CUDA_HOME/extras/CUPTI/lib64"
</code>```

Moreover, I found that libcusolver.so.8.0 is not there, while libcusolver.so.7.5
is there in cuda/lib64/.
Somehow tensorflow is finding wrong file or I ain't know nothing.
Any help would be appreciated as I am new to all this stuff.
Python version: 2.7
OS: Linux

答:
I solved the issue. Actually I have cuda 7.5 installed and I was installing latest tensorflow version which probably support cuda 8.0.
So I downgraded. </p>

```<code> pip install --upgrade \ https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.10.0-cp27-none-linux_x86_64.whl
</code>```

Body:
Possible duplicate of this question.
I have a gpu account to whom I connect through putty (ssh login). I have created a virtualenv there and I am installing tenorflow through pip for gpu. Everything works fine, when I run command

$ pip list

following list is being shown:

 backports.weakref (1.0rc1)
 bleach (1.5.0)
 funcsigs (1.0.2)
 html5lib (0.9999999)
 Markdown (2.6.8)
 mock (2.0.0)
 numpy (1.13.1)
 olefile (0.44)
 pbr (3.1.1)
 Pillow (4.2.1)
 pip (9.0.1)
 protobuf (3.3.0)
 setuptools (36.0.1)
 six (1.10.0)
 tensorflow-gpu (1.2.1)
 Werkzeug (0.12.2)
 wheel (0.29.0)

But when I run:

$ python
>>> import tensorflow

It shows the following error:

  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/__init__.py", line 24, in <module>
  from tensorflow.python import *
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/__init__.py", line 49, in <module>
  from tensorflow.python import pywrap_tensorflow
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
  raise ImportError(msg)
  ImportError: Traceback (most recent call last):
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
  from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in
  <module>
  _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/nauman/junaid/final/test/lib/python2.7/site-
  packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in
  swig_import_helper
  _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname,
  description)
  ImportError: libcusolver.so.8.0: cannot open shared object file: No such
  file or directory
  Failed to load the native TensorFlow runtime.
  See https://www.tensorflow.org/install/install_sources#common_installation_problems
  for some common reasons and solutions.  Include the entire stack trace
  above this error message when asking for help.

I have also set my environment variables like this:

  export CUDA_HOME=/opt/cuda
  export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$CUDA_HOME/lib64:$CUDA_HOME/extras/CUPTI/lib64"

Moreover, I found that libcusolver.so.8.0 is not there, while libcusolver.so.7.5
is there in cuda/lib64/.
Somehow tensorflow is finding wrong file or I ain't know nothing.
Any help would be appreciated as I am new to all this stuff.
Python version: 2.7
OS: Linux

Body:
I solved the issue. Actually I have cuda 7.5 installed and I was installing latest tensorflow version which probably support cuda 8.0.
So I downgraded.

 pip install --upgrade \ https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow-0.10.0-cp27-none-linux_x86_64.whl


问:
Turbo C++ compile error "too many types in declaration"
whenever I compile this program, I get an error saying "Too many types in decleration on line 13". I do not see any possible syntax errors but still I am facing this issue.

```<code>#include<iostream.h>
#include<conio.h>

class currency
{
    private:
    int rupee,paise;
    int total;
    public:
    void getdata(int r,int p);
    void display();

}
void currency::getdata(int r, int p){

    rupee=r;
    paise=p;
    total=r*100+p;

}
void currency::display(){

cout<<rupee<<" Rupees"<<" and "<<paise<<"Paise"<<endl;
cout<<"Converted value="<<total;

}

int main(){

    currency c;
        c.getdata(5,25);
        c.display();
        getch();
        return 0;

}
</code>```

答:
There needs to be a semicolon to terminate the class definition:

```<code>}  ;   // semicolon needed here.
void currency::getdata( ...
</code>```

Otherwise, it looks like this to the compiler:

```<code>class blahblah {int etc, etc1; int etc2; } void currency::getdata (...
</code>```

Body:
whenever I compile this program, I get an error saying "Too many types in decleration on line 13". I do not see any possible syntax errors but still I am facing this issue.

#include<iostream.h>
#include<conio.h>

class currency
{
    private:
    int rupee,paise;
    int total;
    public:
    void getdata(int r,int p);
    void display();

}
void currency::getdata(int r, int p){

    rupee=r;
    paise=p;
    total=r*100+p;

}
void currency::display(){

cout<<rupee<<" Rupees"<<" and "<<paise<<"Paise"<<endl;
cout<<"Converted value="<<total;

}

int main(){

    currency c;
        c.getdata(5,25);
        c.display();
        getch();
        return 0;

}

Body:
There needs to be a semicolon to terminate the class definition:

}  ;   // semicolon needed here.
void currency::getdata( ...

Otherwise, it looks like this to the compiler:

class blahblah {int etc, etc1; int etc2; } void currency::getdata (...


答:
you are not declaring a statement and directly binding params to query use something like this.</p>

```<code>$select = $connection->prepare($query);
$select->bindParam(':username',$username);
</code>```

Title: Fatal error: Uncaught Error: Call to a member function bindParam() on string i

Body:
you are not declaring a statement and directly binding params to query use something like this.

$select = $connection->prepare($query);
$select->bindParam(':username',$username);


问:
Reduce size of captured image from camera in android
Here, I am saving the captured image on sdcard from camera. Here, captured image size is greater than 1 MB. I want to reduce this size to nearly 500kb to 600kb before saving to sdcard. How could I do that?

```<code>try
        {
            Bitmap mPhoto;
            mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, CheckInGallery.mUri);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            mPhoto.compress(Bitmap.CompressFormat.PNG, 100, bytes);

            File direct = new File(Environment.getExternalStorageDirectory() + "/RetailRun");
            String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
            Toast.makeText(getBaseContext(), "Time :" + mydate, 5000).show();

            if(!direct.exists())
            {
                direct.mkdir();
                File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/MyImage/image" + mydate +".jpg");
                file.createNewFile();
                FileOutputStream fo = new FileOutputStream(file);
                fo.write(bytes.toByteArray());
                fo.close();
             }

         else
            {
                File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/MyImage/image" + mydate +".jpg");
                file.createNewFile();
                FileOutputStream fo = new FileOutputStream(file);
                fo.write(bytes.toByteArray());
                fo.close();
            }

        }

        catch (Exception e)
        {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
</code>```

答:
This is what worked for me.

```<code>    public void onImageSelected(){
    Uri uri=null; // get the uri of the image result from the intent
    try {

        Bitmap bitmap = handleSamplingAndRotationBitmap(this, uri);
        byte[] bytes = getBytesFromBitmap(bitmap);
        //getPresenter.upload(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * returns an aligned bitmap with size not exceeding the MAX_HEIGHT
 * @param context
 * @param selectedImage
 * @return
 * @throws IOException
 */
public Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
        throws IOException {
    Bitmap decoded = getImageSampleOutput(context,selectedImage);
    decoded = rotateImageIfRequired(this, decoded, selectedImage);
    return decoded;
}

public Bitmap getImageSampleOutput(Context context, Uri selectedImage) throws IOException {
    int MAX_HEIGHT = 1200;
    int MAX_WIDTH = 1600;

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
    BitmapFactory.decodeStream(imageStream, null, options);
    imageStream.close();

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    imageStream = context.getContentResolver().openInputStream(selectedImage);
    Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
    Bitmap decoded = compressImage(img);
    return decoded;
}

/**
 * Used to compress the image to prevent any Memory overflows.
 * @param bitmap
 * @return
 */
public Bitmap compressImage(Bitmap bitmap) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
    return BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
}

private static int calculateInSampleSize(BitmapFactory.Options options,
                                         int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee a final image
        // with both dimensions larger than or equal to the requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

        // This offers some additional logic in case the image has a strange
        // aspect ratio. For example, a panorama may have a much larger
        // width than height. In these cases the total pixels might still
        // end up being too large to fit comfortably in memory, so we should
        // be more aggressive with sample down the image (=larger inSampleSize).

        final float totalPixels = width * height;

        // Anything more than 2x the requested pixels we'll sample down further
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }
    }
    return inSampleSize;
}

private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) {

    // Detect rotation
    int rotation = getRotation(context, selectedImage);
    if (rotation != 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotation);
        Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
        img.recycle();
        return rotatedImg;
    } else {
        return img;
    }
}

/**
 * Get the rotation of the last image added.
 *
 * @param context
 * @param selectedImage
 * @return
 */
private static int getRotation(Context context, Uri selectedImage) {

    int rotation = 0;
    ContentResolver content = context.getContentResolver();

    Cursor mediaCursor = content.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[]{"orientation", "date_added"},
            null, null, "date_added desc");

    if (mediaCursor != null && mediaCursor.getCount() != 0) {
        while (mediaCursor.moveToNext()) {
            rotation = mediaCursor.getInt(0);
            break;
        }
    }
    mediaCursor.close();
    return rotation;
}

public byte[] getBytesFromBitmap(Bitmap bmp){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG,70,stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}
</code>```

On a Samusung Galaxy S7, i was able to reduce the size down to 300kb.

Body:
Here, I am saving the captured image on sdcard from camera. Here, captured image size is greater than 1 MB. I want to reduce this size to nearly 500kb to 600kb before saving to sdcard. How could I do that?

try
        {
            Bitmap mPhoto;
            mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, CheckInGallery.mUri);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            mPhoto.compress(Bitmap.CompressFormat.PNG, 100, bytes);

            File direct = new File(Environment.getExternalStorageDirectory() + "/RetailRun");
            String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
            Toast.makeText(getBaseContext(), "Time :" + mydate, 5000).show();

            if(!direct.exists())
            {
                direct.mkdir();
                File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/MyImage/image" + mydate +".jpg");
                file.createNewFile();
                FileOutputStream fo = new FileOutputStream(file);
                fo.write(bytes.toByteArray());
                fo.close();
             }

         else
            {
                File file = new File(Environment.getExternalStorageDirectory()+File.separator + "/MyImage/image" + mydate +".jpg");
                file.createNewFile();
                FileOutputStream fo = new FileOutputStream(file);
                fo.write(bytes.toByteArray());
                fo.close();
            }

        }

        catch (Exception e)
        {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

Body:
This is what worked for me.

    public void onImageSelected(){
    Uri uri=null; // get the uri of the image result from the intent
    try {

        Bitmap bitmap = handleSamplingAndRotationBitmap(this, uri);
        byte[] bytes = getBytesFromBitmap(bitmap);
        //getPresenter.upload(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * returns an aligned bitmap with size not exceeding the MAX_HEIGHT
 * @param context
 * @param selectedImage
 * @return
 * @throws IOException
 */
public Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
        throws IOException {
    Bitmap decoded = getImageSampleOutput(context,selectedImage);
    decoded = rotateImageIfRequired(this, decoded, selectedImage);
    return decoded;
}

public Bitmap getImageSampleOutput(Context context, Uri selectedImage) throws IOException {
    int MAX_HEIGHT = 1200;
    int MAX_WIDTH = 1600;

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
    BitmapFactory.decodeStream(imageStream, null, options);
    imageStream.close();

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    imageStream = context.getContentResolver().openInputStream(selectedImage);
    Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
    Bitmap decoded = compressImage(img);
    return decoded;
}

/**
 * Used to compress the image to prevent any Memory overflows.
 * @param bitmap
 * @return
 */
public Bitmap compressImage(Bitmap bitmap) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
    return BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
}

private static int calculateInSampleSize(BitmapFactory.Options options,
                                         int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee a final image
        // with both dimensions larger than or equal to the requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

        // This offers some additional logic in case the image has a strange
        // aspect ratio. For example, a panorama may have a much larger
        // width than height. In these cases the total pixels might still
        // end up being too large to fit comfortably in memory, so we should
        // be more aggressive with sample down the image (=larger inSampleSize).

        final float totalPixels = width * height;

        // Anything more than 2x the requested pixels we'll sample down further
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }
    }
    return inSampleSize;
}

private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) {

    // Detect rotation
    int rotation = getRotation(context, selectedImage);
    if (rotation != 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotation);
        Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
        img.recycle();
        return rotatedImg;
    } else {
        return img;
    }
}

/**
 * Get the rotation of the last image added.
 *
 * @param context
 * @param selectedImage
 * @return
 */
private static int getRotation(Context context, Uri selectedImage) {

    int rotation = 0;
    ContentResolver content = context.getContentResolver();

    Cursor mediaCursor = content.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[]{"orientation", "date_added"},
            null, null, "date_added desc");

    if (mediaCursor != null && mediaCursor.getCount() != 0) {
        while (mediaCursor.moveToNext()) {
            rotation = mediaCursor.getInt(0);
            break;
        }
    }
    mediaCursor.close();
    return rotation;
}

public byte[] getBytesFromBitmap(Bitmap bmp){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG,70,stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}

On a Samusung Galaxy S7, i was able to reduce the size down to 300kb.


问:
Are there cases where a singleton is the best option?
There is a lot of discussion on this site about why singletons should be avoided but are there any cases where a singleton makes sense and is the best option?

An example where I think that a singleton is the best option is when implementing an Identity Map where you need to keep track of all models that have already been loaded from the database in your mapping layer. In this case it is important that the map is effectively global so that all client code uses the same instance of the map and they are all accessing the same list of loaded models. The simplest solution seems to be to implement the class as a singleton (or as static methods). Is this the best approach or is there another way?

Are there any other cases where it is OK to use a singleton or are they always bad?

答: Singletons make sense when you're using web programming: you generally only ever want one instance of a page output class per request, and one user object for it. Databases are different though - implementing privilege separation is a good reason for wanting more than one db object.</p>


问:
Magick++ in VS2010 - unresolved external symbol
I'm trying to use ImageMagick Magick++ for a C++ Project in VS2010.
I installed the Library from here: klick

Then in my Project, I added c:/program files/ImageMagick-6.6.6-Q16/include to the include folders. Then I tried to use Magick++ with this code:

```<code>#include <Magick++.h>
void main(int argc, char ** argv){
    InitializeMagick(*argv);
}
</code>```

But this does not work!
VS2010 returns the following errors:

```<code>error LNK2001: unresolved external symbol "__declspec(dllimport) void __cdecl    Magick::InitializeMagick(char const *)" (__imp_?InitializeMagick@Magick@@YAXPBD@Z)
error LNK1120: 1 unresolved externals
</code>```

What am I doing wrong?

Thanks very much for your help!

UPDATE:

Set Linker -> Input -> Additionnal Dependencies to:

```<code>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;CORE_RL_Magick++_.lib
</code>```

And Linker -> General -> Additionnal Library Directories to:

```<code>C:\Program Files\ImageMagick-6.6.6-Q16\lib
</code>```

It still results in the same error...

UPDATE 2

Opening the .lib files in C:\Program Files\ImageMagick-6.6.6-Q16\lib results in this error:

UPDATE 3

CORE_RL_Magick++_.lib does contain ?InitializeMagick@Magick@@YAXPEBD@Z, but not ?InitializeMagick@Magick@@YAXPBD@Z. Does this mean the .lib file is corrupted?

UPDATE 4

I solved my problem by manually compliling the .lib files.
Thanks to all!

答:
You should also indicate to Visual Studio the .lib to be used for linking
    in Linker -> Input -> Additionnal Dependencies

Thank you!
The additional dependecies line contains now the following text (look at the end):
    kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;C:\Program Files\ImageMagick-6.6.6-Q16\lib\CORE_RL_Magick++_.lib

It still does not work. Is it the wrong .lib file?

what is this .lib file for?
Shouldn't source code just work? There isn't any DLL...

Body:
I'm trying to use ImageMagick Magick++ for a C++ Project in VS2010.
I installed the Library from here: klick

Then in my Project, I added c:/program files/ImageMagick-6.6.6-Q16/include to the include folders. Then I tried to use Magick++ with this code:

#include <Magick++.h>
void main(int argc, char ** argv){
    InitializeMagick(*argv);
}

But this does not work!
VS2010 returns the following errors:

error LNK2001: unresolved external symbol "__declspec(dllimport) void __cdecl    Magick::InitializeMagick(char const *)" (__imp_?InitializeMagick@Magick@@YAXPBD@Z)
error LNK1120: 1 unresolved externals

What am I doing wrong?

Thanks very much for your help!

UPDATE:

Set Linker -> Input -> Additionnal Dependencies to:

kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;CORE_RL_Magick++_.lib

And Linker -> General -> Additionnal Library Directories to:

C:\Program Files\ImageMagick-6.6.6-Q16\lib

It still results in the same error...

UPDATE 2

Opening the .lib files in C:\Program Files\ImageMagick-6.6.6-Q16\lib results in this error:

UPDATE 3

CORE_RL_Magick++_.lib does contain ?InitializeMagick@Magick@@YAXPEBD@Z, but not ?InitializeMagick@Magick@@YAXPBD@Z. Does this mean the .lib file is corrupted?

UPDATE 4

I solved my problem by manually compliling the .lib files.
Thanks to all!


问:
How to load balance with common database
I am using Docker to create a container for each of the following:
NGINX, Flask Application, Redis, PostgreSQL. I realize that Flask is not as powerful as a single node, so I want to load balance between multiple Flask instances. I am wondering how that would work.

Should I create multiple servers with the Flask container? How do I make sure they all use the same Redis instance and PostgreSQL database? Would this be a functional setup?

Containers by server:

```<code>Server 1: NGINX, Flask, Redis, PostgreSQL
Server 2: Flask
Server 3: Flask
</code>```

Any other thoughts and tips?

答:
You could run your containers behind Traefik, a "HTTP reverse proxy and load balancer made to deploy microservices with ease".

See for instance "Running your application over HTTPS with traefik".

His project beenje/flask_traefik_letsencrypt use a flask container, with traefik settings.

You can then scale that service to multiple flask containers.

Body:
I am using Docker to create a container for each of the following:
NGINX, Flask Application, Redis, PostgreSQL. I realize that Flask is not as powerful as a single node, so I want to load balance between multiple Flask instances. I am wondering how that would work.

Should I create multiple servers with the Flask container? How do I make sure they all use the same Redis instance and PostgreSQL database? Would this be a functional setup?

Containers by server:

Server 1: NGINX, Flask, Redis, PostgreSQL
Server 2: Flask
Server 3: Flask

Any other thoughts and tips?


问:
Xcode can't find my cell identifier
I'm getting an error with my code that says...

"Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'unable to dequeue a cell
  with identifier ItemCell - must register a nib or a class for the
  identifier or connect a prototype cell in a storyboard'?"

I've set the cell to ItemCell and I've run Product > Clean. It still can't find it. Can anyone see what I've done wrong? I've included a screen shot of my code and my storyboard.

```<code>import UIKit

 class ItemsViewController: UITableViewController {

  var itemStore: ItemStore!

@IBAction func addNewItem(_ sender: UIButton) {

    let newItem = itemStore.createItem()

    if let index = itemStore.allItems.index(of: newItem) {
        let indexPath = IndexPath(row: index, section: 0)

        tableView.insertRows(at: [indexPath], with: .automatic)
    }
}

@IBAction func toggleEditingMode(_ sender: UIButton) {
    if isEditing {
        sender.setTitle("Edit", for: .normal)

        setEditing(false, animated: true)
    } else {
        sender.setTitle("Done", for: .normal)

        setEditing(true, animated: true)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    let statusBarHeight = UIApplication.shared.statusBarFrame.height

    let insets = UIEdgeInsetsMake(statusBarHeight, 0, 0, 0)
    tableView.contentInset = insets
    tableView.scrollIndicatorInsets = insets

    tableView.rowHeight = 65
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return itemStore.allItems.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell

    let item = itemStore.allItems[indexPath.row]

    cell.nameLabel.text = item.name
    cell.serialNumberLabel.text = item.serialNumber
    cell.valueLabel.text = "$\(item.valueInDollars)"

    return cell
}

override func tableView(_ tableView: UITableView,
                        commit editingStyle: UITableViewCellEditingStyle,
                        forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        let item = itemStore.allItems[indexPath.row]

        let title = "Delete \(item.name)"
        let message = "You sure ya wanna delete this?"

        let ac = UIAlertController(title: title,
                                   message: message,
                                   preferredStyle: .actionSheet)

        let cancelAction  = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        ac.addAction(cancelAction)

        let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { (action) -> Void in

        self.itemStore.removeItem(item)

        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    })
        ac.addAction(deleteAction)
        present(ac, animated: true, completion: nil)
    }

}
override func tableView(_ tableView: UITableView,
                        moveRowAt sourceIndexPath: IndexPath,
                        to destinationIndexPath: IndexPath) {
    itemStore.moveItem(from: sourceIndexPath.row, to: destinationIndexPath.row)
}
</code>```

This is my ItemCell

```<code> import UIKit

 class ItemCell: UITableViewCell {

@IBOutlet var nameLabel: UILabel!
@IBOutlet var serialNumberLabel: UILabel!
@IBOutlet var valueLabel: UILabel!

   }
</code>```

And my ItemStore

```<code>  import UIKit

  class ItemStore {

  var allItems = [Item] ()

@discardableResult func createItem() -> Item {
    let newItem = Item(random: true)

    allItems.append(newItem)

    return newItem
}

func removeItem(_ item: Item) {
    if let index = allItems.index(of: item) {
        allItems.remove(at: index)
    }
}

func moveItem(from fromIndex: Int, to toIndex: Int) {
    if fromIndex == toIndex {
        return
    }

    let movedItem = allItems[fromIndex]

    allItems.remove(at: fromIndex)

    allItems.insert(movedItem, at: toIndex)
}

 }
</code>```

答: Check if you have set the correct custom class for the cell (ItemCell in this case) in Identity Inspector.

Title: Xcode can't find my cell identifier

Body:
I'm getting an error with my code that says...

"Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'unable to dequeue a cell
  with identifier ItemCell - must register a nib or a class for the
  identifier or connect a prototype cell in a storyboard'?"

I've set the cell to ItemCell and I've run Product > Clean. It still can't find it. Can anyone see what I've done wrong? I've included a screen shot of my code and my storyboard.

import UIKit

 class ItemsViewController: UITableViewController {

  var itemStore: ItemStore!

@IBAction func addNewItem(_ sender: UIButton) {

    let newItem = itemStore.createItem()

    if let index = itemStore.allItems.index(of: newItem) {
        let indexPath = IndexPath(row: index, section: 0)

        tableView.insertRows(at: [indexPath], with: .automatic)
    }
}

@IBAction func toggleEditingMode(_ sender: UIButton) {
    if isEditing {
        sender.setTitle("Edit", for: .normal)

        setEditing(false, animated: true)
    } else {
        sender.setTitle("Done", for: .normal)

        setEditing(true, animated: true)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    let statusBarHeight = UIApplication.shared.statusBarFrame.height

    let insets = UIEdgeInsetsMake(statusBarHeight, 0, 0, 0)
    tableView.contentInset = insets
    tableView.scrollIndicatorInsets = insets

    tableView.rowHeight = 65
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return itemStore.allItems.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell

    let item = itemStore.allItems[indexPath.row]

    cell.nameLabel.text = item.name
    cell.serialNumberLabel.text = item.serialNumber
    cell.valueLabel.text = "$\(item.valueInDollars)"

    return cell
}

override func tableView(_ tableView: UITableView,
                        commit editingStyle: UITableViewCellEditingStyle,
                        forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        let item = itemStore.allItems[indexPath.row]

        let title = "Delete \(item.name)"
        let message = "You sure ya wanna delete this?"

        let ac = UIAlertController(title: title,
                                   message: message,
                                   preferredStyle: .actionSheet)

        let cancelAction  = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        ac.addAction(cancelAction)

        let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { (action) -> Void in

        self.itemStore.removeItem(item)

        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    })
        ac.addAction(deleteAction)
        present(ac, animated: true, completion: nil)
    }

}
override func tableView(_ tableView: UITableView,
                        moveRowAt sourceIndexPath: IndexPath,
                        to destinationIndexPath: IndexPath) {
    itemStore.moveItem(from: sourceIndexPath.row, to: destinationIndexPath.row)
}

This is my ItemCell

 import UIKit

 class ItemCell: UITableViewCell {

@IBOutlet var nameLabel: UILabel!
@IBOutlet var serialNumberLabel: UILabel!
@IBOutlet var valueLabel: UILabel!

   }

And my ItemStore

  import UIKit

  class ItemStore {

  var allItems = [Item] ()

@discardableResult func createItem() -> Item {
    let newItem = Item(random: true)

    allItems.append(newItem)

    return newItem
}

func removeItem(_ item: Item) {
    if let index = allItems.index(of: item) {
        allItems.remove(at: index)
    }
}

func moveItem(from fromIndex: Int, to toIndex: Int) {
    if fromIndex == toIndex {
        return
    }

    let movedItem = allItems[fromIndex]

    allItems.remove(at: fromIndex)

    allItems.insert(movedItem, at: toIndex)
}

 }


问:
Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'
I am new to EF core and I'm trying to get it to work with my ASP.NET Core project.

I get the above error in my startup.cs when trying configure the DbContext to use a connection string from config. I am following this tutorial.

The problematic code is in startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using tracV2.models;
using tracV2.data;

namespace tracV2
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddSingleton<IConfiguration>(Configuration);

            string conn = Configuration.GetConnectionString("optimumDB");

            services.AddDbContext<tracContext>(options => options.usesqlserver(conn));
        }
```
<p>The <code>UseSqlServer</code> method is recognized if I put it directly into the context:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace tracV2.data
{
    public class tracContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("myrealconnectionstring");
        }
</code>```

All my research online points to missing references, but I can't seem to find out which one I am missing (see image).

答:
adding
using Microsoft.EntityFrameworkCore;

manually solved the problem for me

Found that here

Edit...

for dotnet core 3.1 add

Microsoft.EntityFrameworkCore.SqlServer

Body:
I am new to EF core and I'm trying to get it to work with my ASP.NET Core project.

I get the above error in my startup.cs when trying configure the DbContext to use a connection string from config. I am following this tutorial.

The problematic code is in startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using tracV2.models;
using tracV2.data;

namespace tracV2
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddSingleton<IConfiguration>(Configuration);

            string conn = Configuration.GetConnectionString("optimumDB");

            services.AddDbContext<tracContext>(options => options.usesqlserver(conn));
        }

The UseSqlServer method is recognized if I put it directly into the context:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace tracV2.data
{
    public class tracContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("myrealconnectionstring");
        }

All my research online points to missing references, but I can't seem to find out which one I am missing (see image).


问:
ASP .Net core Logging - How to filter logger providers?
I have 2 logger providers in my asp.net core project:
1. Console provider.
2. Database provider (custom provider).
I do not want to log every time to all the providers, however, sometimes write to the Console provider and sometimes write to Database provider.
I saw the filter provider options, but it let you to filter only by log level or category.
Do ASP .net core Logging library has an option to write only to one provider?
or should I have to write Logging service all by myself and not use ASP .net core Logging library?  </p>

答:
Yes, you can use filtering to selectively log to Console vs. Debug. There is an overload for the AddConsole and AddDebug methods that lets you specific the criteria by which to filter to that logging provider.

```<code>public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory
        .AddConsole(LogLevel.Warning)
        .AddDebug((category, logLevel) => (category.Contains("TodoApi") && logLevel >= LogLevel.Trace));
</code>```

For more info, see Microsoft's documentation: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging#log-filtering

Body:
Yes, you can use filtering to selectively log to Console vs. Debug. There is an overload for the AddConsole and AddDebug methods that lets you specific the criteria by which to filter to that logging provider.

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    loggerFactory
        .AddConsole(LogLevel.Warning)
        .AddDebug((category, logLevel) => (category.Contains("TodoApi") && logLevel >= LogLevel.Trace));

For more info, see Microsoft's documentation: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging#log-filtering