问:
Converting user input to uppercase
I am attempting to create a program in Unix that accesses a data file, adding, deleting, and searching within the file for names and usernames. With this if statement, I am attempting to allow the user to search for data in the file by the first field.

All of the data in the file uses uppercase letters, so I first must convert any text the user input from lowercase to uppercase letters. For some reason, this code is not working with both converting to uppercase and searching and printing the data.

How can I fix it?

```<code>if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
        tput cup 3 12
        echo "Enter the first name of the user you would like to search for: "
        tput cup 4 12; read search | tr '[a-z]' '[A-Z]'
        echo "$search"
        awk -F ":" '$1 == "$search" {print $3 " " $1 " " $2 }'
        capstonedata.txt
fi
</code>```

答:
Awk is not shell (google that). Just do:</p>

```<code>if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
        read search
        echo "$search"
        awk -F':' -v srch="$search" '$1 == toupper(srch) {print $3, $1, $2}' capstonedata.txt
fi
</code>```

Title: Converting user input to uppercase

Body:
I am attempting to create a program in Unix that accesses a data file, adding, deleting, and searching within the file for names and usernames. With this if statement, I am attempting to allow the user to search for data in the file by the first field.

All of the data in the file uses uppercase letters, so I first must convert any text the user input from lowercase to uppercase letters. For some reason, this code is not working with both converting to uppercase and searching and printing the data.

How can I fix it?

if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
        tput cup 3 12
        echo "Enter the first name of the user you would like to search for: "
        tput cup 4 12; read search | tr '[a-z]' '[A-Z]'
        echo "$search"
        awk -F ":" '$1 == "$search" {print $3 " " $1 " " $2 }'
        capstonedata.txt
fi

Body:
Awk is not shell (google that). Just do:

if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
        read search
        echo "$search"
        awk -F':' -v srch="$search" '$1 == toupper(srch) {print $3, $1, $2}' capstonedata.txt
fi


来源: stackexchange

问:
Applicability of Reflection
There are some great articles out there such as this one on Reflection.

What I want to know is real world examples where it is used and real world reasons or when it's useful and why outside the raw "you can get type info"...I get all that in this article and others.

Ok, so what, it doesn't really help me in context to actual programming situations.  I'm trying to figure out how people are using it in apps, good examples of times that they have been used just to get my head wrapped around when you'd want to use it.

答:
As pointed out by Mehrdad, run-time plugins are one are where reflection is used. A good example is the JDBC API. You use reflection to load the driver class by name; that's the only way to do it, as the JVM cannot know which class to load on its own.

Another situation where reflection is useful is for application frameworks that are supposed to run arbitrary code. Examples:

application servers

unit testing frameworks (JUnit uses reflection extensively)

RPC-type applications (e.g. XML-RPC)

Yet another is persistence frameworks, which can load/save arbitrary class instances (e.g. Hibernate).

ContentLicense: CC BY-SA 2.5

Title: Applicability of Reflection


问:
How to put JSON data into a HTML div?
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output"></div></code>```

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?

答:
as your json data children are array you can use $.each function:

Example:

```<code>var noma = data.NOMA;
var html_append = '';
$.each(noma, function(key,value) {
   html_append += value +'<br>';
});

$('#output').html(html_append);
</code>```

The same code you can use for also data.DATENAISSANCE and data.SEXE

ContentLicense: CC BY-SA 3.0

Title: How to put JSON data into a HTML div?

Body:
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?

Body:
as your json data children are array you can use $.each function:

Example:

var noma = data.NOMA;
var html_append = '';
$.each(noma, function(key,value) {
   html_append += value +'<br>';
});

$('#output').html(html_append);

The same code you can use for also data.DATENAISSANCE and data.SEXE


问:
Inner classes evaluation order in python
Say I do this in python 3.6:

```<code>class A:
    class B:
        pass
    class C:
        x = B()
</code>```

This fails complaining that B is not defined when instantiating it in C.
However, this:

```<code>class A:
    x = 1
    y = x

    def f(self):
        return self

    z = f
</code>```

works fine.

And of course, this:

```<code>class A:
    pass

class B:
    x = A()
</code>```

also works.

Why do inner classes definitions not follow the same logical rules as everything else?

答:
The problem here is not the definition order, which works like everything else, it is the special nature of class-body scope. Essentially, variables in the class-body scope can only be accessed using the class-namespace, e.g. MyClass.my_class_variable. The special aspect of it is that it does not create an enclosing scope, which is why you cannot access my_class_variable and are forced to use the class-namespace inside a method definition, for example. Read more about that in this answer. So again, B is in fact defined. Note, the following works:

```<code>In [4]: class A:
   ...:     class B:
   ...:         pass
   ...:     x = B.__name__
   ...:
   ...:

In [5]: A.x
Out[5]: 'B'
</code>```

Now, you might hope the following would work:

```<code>In [6]: class A:
   ...:     class B:
   ...:         pass
   ...:     class C:
   ...:         x = A.B()
   ...:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-a145c80eee84> in <module>()
----> 1 class A:
      2     class B:
      3         pass
      4     class C:
      5         x = A.B()

<ipython-input-1-a145c80eee84> in A()
      2     class B:
      3         pass
----> 4     class C:
      5         x = A.B()
      6

<ipython-input-1-a145c80eee84> in C()
      3         pass
      4     class C:
----> 5         x = A.B()
      6
</code>```

However, it does not, because A hasn't actually been defined yet! So, the solution is something like this:

```<code>In [7]: class A:
   ...:     class B:
   ...:         pass
   ...:     class C:
   ...:         pass
   ...:
   ...:

In [8]: A.C.x = A.B
</code>```

Edited

So, this example should be illuminating:

```<code>In [14]: x = 'global'

In [15]: class Foo:
    ...:     x = 'foooooo!'
    ...:     def bar(self):
    ...:         return x
    ...:

In [16]: Foo().bar()
Out[16]: 'global'

In [17]: Foo.x
Out[17]: 'foooooo!'
</code>```

Body:
Say I do this in python 3.6:

class A:
    class B:
        pass
    class C:
        x = B()

This fails complaining that B is not defined when instantiating it in C.
However, this:

class A:
    x = 1
    y = x

    def f(self):
        return self

    z = f

works fine.

And of course, this:

class A:
    pass

class B:
    x = A()

also works.

Why do inner classes definitions not follow the same logical rules as everything else?

Body:
The problem here is not the definition order, which works like everything else, it is the special nature of class-body scope. Essentially, variables in the class-body scope can only be accessed using the class-namespace, e.g. MyClass.my_class_variable. The special aspect of it is that it does not create an enclosing scope, which is why you cannot access my_class_variable and are forced to use the class-namespace inside a method definition, for example. Read more about that in this answer. So again, B is in fact defined. Note, the following works:

In [4]: class A:
   ...:     class B:
   ...:         pass
   ...:     x = B.__name__
   ...:
   ...:

In [5]: A.x
Out[5]: 'B'

Now, you might hope the following would work:

In [6]: class A:
   ...:     class B:
   ...:         pass
   ...:     class C:
   ...:         x = A.B()
   ...:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-a145c80eee84> in <module>()
----> 1 class A:
      2     class B:
      3         pass
      4     class C:
      5         x = A.B()

<ipython-input-1-a145c80eee84> in A()
      2     class B:
      3         pass
----> 4     class C:
      5         x = A.B()
      6

<ipython-input-1-a145c80eee84> in C()
      3         pass
      4     class C:
----> 5         x = A.B()
      6

However, it does not, because A hasn't actually been defined yet! So, the solution is something like this:

In [7]: class A:
   ...:     class B:
   ...:         pass
   ...:     class C:
   ...:         pass
   ...:
   ...:

In [8]: A.C.x = A.B

Edited

So, this example should be illuminating:

In [14]: x = 'global'

In [15]: class Foo:
    ...:     x = 'foooooo!'
    ...:     def bar(self):
    ...:         return x
    ...:

In [16]: Foo().bar()
Out[16]: 'global'

In [17]: Foo.x
Out[17]: 'foooooo!'


问:
Compressing a JPG image to a given size in KB?
I have a byte array returned by the camera in input.

I need to scale down my image to make its size equal to 500KB. I am trying to achieve this using a Bitmap, but I cannot find how to get the proper compression value.

```<code>public static byte[] compressCapture(byte[] capture) {

    // How to get the right compression value ?
    int compression = 50;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}
</code>```

The problem is that the compression is not proportional to the image size, meaning that compression equals to 50 will not divide the image size by 2.

Is there a way to get a fixed image size in output that does not depend on the focus, or the smartphone model ?

EDIT :

I do not want to use a File (I work with confidential data).

答:
Did not notice the reply from @dlemstra

Imagemagick has a file size option but it is slower as from memory it is trying different options for the output size and is not exact:

```<code>convert input -define jpeg:extent=500kb output.jpg
</code>```

Of course -define may not be supported on your phone.

Body:
I have a byte array returned by the camera in input.

I need to scale down my image to make its size equal to 500KB. I am trying to achieve this using a Bitmap, but I cannot find how to get the proper compression value.

public static byte[] compressCapture(byte[] capture) {

    // How to get the right compression value ?
    int compression = 50;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}

The problem is that the compression is not proportional to the image size, meaning that compression equals to 50 will not divide the image size by 2.

Is there a way to get a fixed image size in output that does not depend on the focus, or the smartphone model ?

EDIT :

I do not want to use a File (I work with confidential data).

Body:
Did not notice the reply from @dlemstra

Imagemagick has a file size option but it is slower as from memory it is trying different options for the output size and is not exact:

convert input -define jpeg:extent=500kb output.jpg

Of course -define may not be supported on your phone.


问:
Are needless write operations in multi-thread kernels in CUDA inefficient?
I have a kernel in my CUDA code where I want a bunch of threads to do a bunch of computations on some piece of shared memory (because it's much faster than doing so on global memory), and then write the result to global memory (so I can use it in later kernels). The kernel looks something like this:

```<code>__global__ void calc(float * globalmem)
{
    __shared__ float sharemem; //initialize shared memory
    sharemem = 0; //set it to initial value
    __syncthreads();

   //do various calculations on the shared memory
   //for example I use atomicAdd() to add each thread's
   //result to sharedmem...

   __syncthreads();
   *globalmem = sharedmem;//write shared memory to global memory
}
</code>```

The fact that every single thread is writing the data out from shared to global memory, when I really only need to write it out once, feels fishy to me. I also get the same feeling from the fact that every thread initializes the shared memory to zero at the start of the code. Is there a faster way to do this than my current implementation?

答:
At the warp level, there's probably not much performance difference between doing a redundant read or write vs. having a single thread do it.

However I would expect a possibly measurable performance difference by having multiple warps in a threadblock do the redundant read or write (vs. a single thread).

It should be sufficient to address these concerns by having a single thread do the read or write, rather than redundantly:

```<code>__global__ void calc(float * globalmem)
{
    __shared__ float sharemem; //initialize shared memory
    if (!threadIdx.x) sharemem = 0; //set it to initial value
    __syncthreads();

   //do various calculations on the shared memory
   //for example I use atomicAdd() to add each thread's
   //result to sharedmem...

   __syncthreads();
   if (!threadIdx.x) *globalmem = sharemem;//write shared memory to global memory
}
</code>```

Although you didn't ask about it, using atomics within a threadblock on shared memory may possibly be replaceable (for possibly better performance) by a shared memory reduction method.

ContentLicense: CC BY-SA 4.0

Body:
I have a kernel in my CUDA code where I want a bunch of threads to do a bunch of computations on some piece of shared memory (because it's much faster than doing so on global memory), and then write the result to global memory (so I can use it in later kernels). The kernel looks something like this:

__global__ void calc(float * globalmem)
{
    __shared__ float sharemem; //initialize shared memory
    sharemem = 0; //set it to initial value
    __syncthreads();

   //do various calculations on the shared memory
   //for example I use atomicAdd() to add each thread's
   //result to sharedmem...

   __syncthreads();
   *globalmem = sharedmem;//write shared memory to global memory
}

The fact that every single thread is writing the data out from shared to global memory, when I really only need to write it out once, feels fishy to me. I also get the same feeling from the fact that every thread initializes the shared memory to zero at the start of the code. Is there a faster way to do this than my current implementation?

Body:
At the warp level, there's probably not much performance difference between doing a redundant read or write vs. having a single thread do it.

However I would expect a possibly measurable performance difference by having multiple warps in a threadblock do the redundant read or write (vs. a single thread).

It should be sufficient to address these concerns by having a single thread do the read or write, rather than redundantly:

__global__ void calc(float * globalmem)
{
    __shared__ float sharemem; //initialize shared memory
    if (!threadIdx.x) sharemem = 0; //set it to initial value
    __syncthreads();

   //do various calculations on the shared memory
   //for example I use atomicAdd() to add each thread's
   //result to sharedmem...

   __syncthreads();
   if (!threadIdx.x) *globalmem = sharemem;//write shared memory to global memory
}

Although you didn't ask about it, using atomics within a threadblock on shared memory may possibly be replaceable (for possibly better performance) by a shared memory reduction method.


问:
Exception in thread "main" org.openqa.selenium.InvalidElementStateException:
Here I am opening a Chrome browser and trying to send input string to the WebElement search text box:

```<code>// search for a text in Google
WebDriverWait wait3 = new WebDriverWait(driver1,30);
WebElement textBox = wait3.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@class = 'gsfi']")));
</code>```

Error Observed for Chrome

```<code>Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state
(Session info: chrome=62.0.3202.94)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'ADMIN-PC', ip: '192.168.1.5', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\admin\AppData\Local\Temp\scoped_dir15624_26281}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=62.0.3202.94, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]
Session ID: d4178e5e05d8efc8800ec1e1ceb1f63a
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:279)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:100)
    at packageFF.browserAutomation.main(browserAutomation.java:76)
</code>```

答:
By.xpath("//input[@class = 'gsfi']") is not found through xpath because it is not opened successfully. You can set sleep time also.

And if possible, you can use id or class instead of xpath.

Body:
Here I am opening a Chrome browser and trying to send input string to the WebElement search text box:

// search for a text in Google
WebDriverWait wait3 = new WebDriverWait(driver1,30);
WebElement textBox = wait3.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@class = 'gsfi']")));

Error Observed for Chrome

Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state
(Session info: chrome=62.0.3202.94)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'ADMIN-PC', ip: '192.168.1.5', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_151'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{mobileEmulationEnabled=false, hasTouchScreen=false, platform=XP, acceptSslCerts=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformName=XP, setWindowRect=true, unexpectedAlertBehaviour=, applicationCacheEnabled=false, rotatable=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\admin\AppData\Local\Temp\scoped_dir15624_26281}, takesHeapSnapshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=, databaseEnabled=false, handlesAlerts=true, version=62.0.3202.94, browserConnectionEnabled=false, nativeEvents=true, locationContextEnabled=true, cssSelectorsEnabled=true}]
Session ID: d4178e5e05d8efc8800ec1e1ceb1f63a
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:82)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:45)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:279)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:100)
    at packageFF.browserAutomation.main(browserAutomation.java:76)


问:
PHP Form Redirect Based Off of Drop Down Selection
This relates to a previous question I had asked about filling out a php form and using those answers to populate a page. When finished filling out the form, I want to determine what page it goes to after you submit the form by a dropdown you choose while filling out the form.

For example, you type in:

Your Name

Email

Phone Number

Then from a drop down you'd pick "Page 3".

Then hit submit.

I would need it then to redirect you to "Page 3" because that's the one you chose in the drop down. I know this should be simple, I just can't seem to figure out how to do it. Thank you in advance to all that help!

答:
Example

```<code><script type="text/javascript">
function OnChangeForm()
{
    var e = document.getElementById("changeFormAct");
    var strType = e.options[e.selectedIndex].value;
    if(strType == '1')
    {
        document.myform.action ="football.html";   // here myform is the name of theform
    }
    else
    if(strType == '2')
    {
        document.myform.action ="cricket.html";
    }
    else
    if(strType == '3')
    {
        document.myform.action ="hockey.html";
    }
    else
    if(strType == '4')
    {
        document.myform.action ="tennis.html";
    }
    return true;
}
</script>

<select onchange="OnChangeForm" id="changeFormAct">
    <option value="1">Football</option>
    <option value="2">Cricket</option>
    <option value="3">Hockey</option>
    <option value="4">Tennis</option>
</select>
</code>```

Body:
Example

<script type="text/javascript">
function OnChangeForm()
{
    var e = document.getElementById("changeFormAct");
    var strType = e.options[e.selectedIndex].value;
    if(strType == '1')
    {
        document.myform.action ="football.html";   // here myform is the name of theform
    }
    else
    if(strType == '2')
    {
        document.myform.action ="cricket.html";
    }
    else
    if(strType == '3')
    {
        document.myform.action ="hockey.html";
    }
    else
    if(strType == '4')
    {
        document.myform.action ="tennis.html";
    }
    return true;
}
</script>

<select onchange="OnChangeForm" id="changeFormAct">
    <option value="1">Football</option>
    <option value="2">Cricket</option>
    <option value="3">Hockey</option>
    <option value="4">Tennis</option>
</select>


问:
Affix is not working in Bootstrap 4 (alpha)
According to Bootstrap 3 docs I have added following attributes to a navbar:

```<code><nav class="navbar no-margin-bottom" data-spy="affix" data-offset-top="90" >
...
</nav>
</code>```

After scrolling down the page Bootstrap 4 is not adding class to navbar which is affix. Can anyone tell me how to solve this problem? Bootstrap.js and jQuery.js are working.

答:
After trying every solution I could find (and being aware that affix was removed from bootstrap 4), the only way I could get the desired sticky results I needed was to use sticky-kit.

This is s really simple jQuery plugin that was easy to set-up.

Just include the code in your project and then assign the element you want to stick with

```<code>$("#sidebar").stick_in_parent();
</code>```

Body:
According to Bootstrap 3 docs I have added following attributes to a navbar:

...

After scrolling down the page Bootstrap 4 is not adding class to navbar which is affix. Can anyone tell me how to solve this problem? Bootstrap.js and jQuery.js are working.

Body:
After trying every solution I could find (and being aware that affix was removed from bootstrap 4), the only way I could get the desired sticky results I needed was to use sticky-kit.

This is s really simple jQuery plugin that was easy to set-up.

Just include the code in your project and then assign the element you want to stick with

$("#sidebar").stick_in_parent();


问:
How to resize an image and upload using multer in nodejs to s3 and using easy-image npm module?
I have done resizing of an image using easy image npm module in nodejs using the below code.

```<code>var easyimg = require('easyimage');

easyimg.rescrop({
     src:'1.jpg', dst:'/var/www/html/bangalore.jpg',
     width:100, height:100

  }),function(image,err){
     // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
     if(image){
     console.log(image);
     }
     else{
     console.log(err);
     }

  }
</code>```

I have got successfull output.
Then i have uploaded my image to s3 using the below code with multer.

```<code>var storage = multerS3({
              s3: s3,
              bucket: 'my_bucket_name',
              key: function (req, file, cb) {
                  console.log(file);
                  file_name = file.originalname;
                  var newFileName = Date.now() + "-" + file.originalname;
                  cb(null, newFileName);
              }
           });
              var upload = multer({storage: storage}).single('profileImage');
             upload(req, resq, function (err,res,response) {
              console.log(response);
             });
</code>```

Now my question is how to resize an image before uploading to s3 and then uploading the resized image to s3?

I have also tried using multer-imager module.

```<code>var transfer = imager({

              secretAccessKey: 'secretAccessKey',
              accessKeyId: 'myaccesskey',
              dirname:'avatar',
              bucket: 'my_bucket',

              region:'myregion',

              key: function (req, file, cb) {
                  console.log(file);
                  file_name = file.originalname;
                  var newFileName = Date.now() + "-" + file.originalname;

                cb(null, newFileName);
                console.log(newFileName);

              },                                    //
    gm: {                                 // [Optional]: define graphicsmagick options
      width: 200,                         // doc: http://aheckmann.github.io/gm/docs.html#resize
      height: 200,
      options: '!',
      format: 'png'                       // Default: jpg
    }
           });
              var upload = multer({storage: transfer}).single('myimage');
             upload(req, resq, function (err,res,response) {
              console.log(req.file); //i am getting this as undefined
             })
</code>```

But it doesnt work.
in 'req.file' i am getting undefined.?

答:
Why not using multer-s3-transofrm with built in transforms combined with multer s3 module?

```<code>var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'some-bucket',
    shouldTransform: function (req, file, cb) {
      cb(null, /^image/i.test(file.mimetype))
    },
    transforms: [{
      id: 'original',
      key: function (req, file, cb) {
        cb(null, 'image-original.jpg')
      },
      transform: function (req, file, cb) {
        //Perform desired transformations
        cb(null, sharp().resize(600, 600).max())
      }
    }]
  })
})
</code>```

From the docs:

The optional shouldTransform option tells multer whether it should transform the file before it is uploaded. By default, it is set to false. If set to true, transforms option must be added, which tells how to transform the file.

transforms option should be an Array, containing objects with can have properties id, key and transform.

This example uses sharp for the transform (a well known Node.js image processing module).

Body:
I have done resizing of an image using easy image npm module in nodejs using the below code.

var easyimg = require('easyimage');

easyimg.rescrop({
     src:'1.jpg', dst:'/var/www/html/bangalore.jpg',
     width:100, height:100

  }),function(image,err){
     // console.log('Resized and cropped: ' + image.width + ' x ' + image.height);
     if(image){
     console.log(image);
     }
     else{
     console.log(err);
     }

  }

I have got successfull output.
Then i have uploaded my image to s3 using the below code with multer.

var storage = multerS3({
              s3: s3,
              bucket: 'my_bucket_name',
              key: function (req, file, cb) {
                  console.log(file);
                  file_name = file.originalname;
                  var newFileName = Date.now() + "-" + file.originalname;
                  cb(null, newFileName);
              }
           });
              var upload = multer({storage: storage}).single('profileImage');
             upload(req, resq, function (err,res,response) {
              console.log(response);
             });

Now my question is how to resize an image before uploading to s3 and then uploading the resized image to s3?

I have also tried using multer-imager module.

var transfer = imager({

              secretAccessKey: 'secretAccessKey',
              accessKeyId: 'myaccesskey',
              dirname:'avatar',
              bucket: 'my_bucket',

              region:'myregion',

              key: function (req, file, cb) {
                  console.log(file);
                  file_name = file.originalname;
                  var newFileName = Date.now() + "-" + file.originalname;

                cb(null, newFileName);
                console.log(newFileName);

              },                                    //
    gm: {                                 // [Optional]: define graphicsmagick options
      width: 200,                         // doc: http://aheckmann.github.io/gm/docs.html#resize
      height: 200,
      options: '!',
      format: 'png'                       // Default: jpg
    }
           });
              var upload = multer({storage: transfer}).single('myimage');
             upload(req, resq, function (err,res,response) {
              console.log(req.file); //i am getting this as undefined
             })

But it doesnt work.
in 'req.file' i am getting undefined.?

Body:
Why not using multer-s3-transofrm with built in transforms combined with multer s3 module?

var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'some-bucket',
    shouldTransform: function (req, file, cb) {
      cb(null, /^image/i.test(file.mimetype))
    },
    transforms: [{
      id: 'original',
      key: function (req, file, cb) {
        cb(null, 'image-original.jpg')
      },
      transform: function (req, file, cb) {
        //Perform desired transformations
        cb(null, sharp().resize(600, 600).max())
      }
    }]
  })
})

From the docs:

The optional shouldTransform option tells multer whether it should transform the file before it is uploaded. By default, it is set to false. If set to true, transforms option must be added, which tells how to transform the file.

transforms option should be an Array, containing objects with can have properties id, key and transform.

This example uses sharp for the transform (a well known Node.js image processing module).


问:
Customise Banner In spring Shell 2
I have used spring Shell 1.x.  It provided provision for customise the banner. I am not trying to use Spring shell 2 and trying to do that same but i cannot  finding the class.

Document also does not speak about it. Do any body know how to customise the same?

答: Banner is now the responsibility of Spring Boot, as explained here. Just drop a banner.txt file in your resources and it should be picked up

Title: Customise Banner In spring Shell 2


问:
What's the difference between 'green threads' and 'user threads'
At the moment, I am dealing with operating systems concepts. However, I have a problem understanding the difference between "kernel thread" and "user thread".

So I surfed the internet and saw this post:
https://stackoverflow.com/a/15984127/5005715

Unfortunately, I do not understand what's the difference between "green threads" and "user threads". For me it is basically the same.

Am I right?

答:
You are getting locked up by terminology. Let me try to hopefully un-confuse you with new terminology.

There are THREADS (aka kernel threads) and there are SIMULATED THREAD (aka user threads and what I have never heard before green threads.

CPUs only knows about processes. A traditional process consisted of a single stream of execution (you could call that a THREAD) and an address space. The operating system can fool the CPU by creating multiple instruction streams (THREADS) that share the same address space.

In a modern operating system, a process consists of an address space and one or more streams of execution (THREADS). Because these are managed by the operating system kernel, they have been called "kernel threads,:

On a system that supports THREADS, a process consists of an address space and one or more instruction streams of execution (ie THREADS).

In ye olde days, operating systems only allowed one thread per process. And it was not even called a "thread." We just had processes. Then came along languages, such as Ada, that needed multi-threading. Because the operating system did not support threads, the threads were implemented in language support libraries. These libraries used timers to switch among different streams of execution. These libraries simulated threads. Operating system books call this method "user threads."

The big question is why this is a major topic at all in an operating system book. Either the operating system supports threads or it does not.

"User threads" are application level programming so there is no need to operating system books to cover them other than to say they exist when threads are not available.

You are suffering from a simple topic being made overly complex.


问:
RK4 Python Explanation
I'd like to use an implementation of RK4 I found online for something, but I'm having a bit of difficulty wrapping my head around the implementations I have found online.
For example:

```<code>def rk4(f, x0, y0, x1, n):
    vx = [0] * (n + 1)
    vy = [0] * (n + 1)
    h = (x1 - x0) / float(n)
    vx[0] = x = x0
    vy[0] = y = y0
    for i in range(1, n + 1):
        k1 = h * f(x, y)
        k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
        k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
        k4 = h * f(x + h, y + k3)
        vx[i] = x = x0 + i * h
        vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4) / 6
return vx, vy
</code>```

Could someone please help me understand what exactly the parameters are? If possible, I'd like a more general explanation, but, if being more specific makes it easier to explain, I'm going to be using it specifically for an ideal spring system.

答:
You are asking for the parameters here:

```<code>def rk4(f, x0, y0, x1, n):
    ...
    return vx, vy
</code>```

f is the ODE function, declared as def f(x,y) for the differential equation y'(x)=f(x,y(x)),

(x0,y0) is the initial point and value,

x1 is the end of the integration interval [x0,x1]

n is the number of sub-intervals or integration steps

vx,vx are the computed sample points, vy[k] approximates y(vx[k]).

You can not use this for the spring system, as that code only works for a scalar v. You would need to change it to work with numpy for vector operations.

```<code>def rk4(func, x0, y0, x1, n):
    y0 = np.array(y0)
    f = lambda x,y: np.array(func(x,y))
    vx = [0] * (n + 1)
    vy = np.zeros( (n + 1,)+y0.shape)
    h = (x1 - x0) / float(n)
    vx[0] = x = x0
    vy[0] = y = y0[:]
    for i in range(1, n + 1):
        k1 = h * f(x, y)
        k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
        k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
        k4 = h * f(x + h, y + k3)
        vx[i] = x = x0 + i * h
        vy[i] = y = y + (k1 + 2*(k2 + k3) + k4) / 6
    return vx, vy
</code>```

Title: RK4 Python Explanation

Body:
I'd like to use an implementation of RK4 I found online for something, but I'm having a bit of difficulty wrapping my head around the implementations I have found online.
For example:

def rk4(f, x0, y0, x1, n):
    vx = [0] * (n + 1)
    vy = [0] * (n + 1)
    h = (x1 - x0) / float(n)
    vx[0] = x = x0
    vy[0] = y = y0
    for i in range(1, n + 1):
        k1 = h * f(x, y)
        k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
        k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
        k4 = h * f(x + h, y + k3)
        vx[i] = x = x0 + i * h
        vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4) / 6
return vx, vy

Could someone please help me understand what exactly the parameters are? If possible, I'd like a more general explanation, but, if being more specific makes it easier to explain, I'm going to be using it specifically for an ideal spring system.

Body:
You are asking for the parameters here:

def rk4(f, x0, y0, x1, n):
    ...
    return vx, vy

f is the ODE function, declared as def f(x,y) for the differential equation y'(x)=f(x,y(x)),

(x0,y0) is the initial point and value,

x1 is the end of the integration interval [x0,x1]

n is the number of sub-intervals or integration steps

vx,vx are the computed sample points, vy[k] approximates y(vx[k]).

You can not use this for the spring system, as that code only works for a scalar v. You would need to change it to work with numpy for vector operations.

def rk4(func, x0, y0, x1, n):
    y0 = np.array(y0)
    f = lambda x,y: np.array(func(x,y))
    vx = [0] * (n + 1)
    vy = np.zeros( (n + 1,)+y0.shape)
    h = (x1 - x0) / float(n)
    vx[0] = x = x0
    vy[0] = y = y0[:]
    for i in range(1, n + 1):
        k1 = h * f(x, y)
        k2 = h * f(x + 0.5 * h, y + 0.5 * k1)
        k3 = h * f(x + 0.5 * h, y + 0.5 * k2)
        k4 = h * f(x + h, y + k3)
        vx[i] = x = x0 + i * h
        vy[i] = y = y + (k1 + 2*(k2 + k3) + k4) / 6
    return vx, vy


问:
Reading a configfs file
I am writing an user space process that will read data from the configfs entry continuously. I have defined callback function for read in kernel.
When I invoke read in a loop, only for the first time callback is called and for the next iterations control is not hitting the callback.

Kernel callback for read is simple function that will return a character.

```<code>static ssize_t show(struct config_item *item, char *page)
{
    static char a = 'a';
    printk("reading data\n");
    page[0] = a++;
    return 1;
}
</code>```

User space process will read the data and display it on the screen.

```<code>int main()
{
   int fd = open("/sys/kernel/config/sample/showme", O_RDONLY);
   int ret;
   int i = 5;
   char receive[8];

   if (fd < 0) {
       perror("Failed to open the device...");
       return errno;
   }
   while(i--) {
       ret = read(fd, receive, 1);
       if (ret < 0) {
           perror("Failed to read the message\n");
           return errno;
       }
       printf("Message is %x with size %d\n", receive[0], ret);
   }
   close(fd);
}
</code>```

output:

    Message is 61 with size 1

    Message is 61 with size 0

    Message is 61 with size 0

    Message is 61 with size 0

    Message is 61 with size 0

Note: The flow goes well if I close and open the file for all reads.

How to fix the above problem? I want the data to be reflected on all read.

答:
A file under configfs filesystem is interpreted as an attribute, which have specific finite content at any moment.

E.g., a file may have content:

"123" at moment 1ns

"abc" at moment 2ns

"" (empty) at moment 3ns

and so on.

Moreover, configfs filesystem ensures, that after opening the file, any read() performed by the user will see portion of data consistent with other read()s. Assuming the example above, user won't read first symbol "1" (as at moment 1ns), 2nd symbol "b" (as at moment 2ns) and then found 3d symbol to be absent (as at moment 3ns).

So, after opening the file, .show() method is called once, and is expected to return whole content of the file. This content (or an appropriate portion of it) is returned upon futher read requests from the user.

Consistency guarantee is cleared at closing the file; so when you open it again, .show() will be called once more, and user's read requests will return updated content of the file.

I am writing an user space process that will read data from the configfs entry continuously.

With this semantic abstraction of finite file's content is lost, so you cannot implement that for configfs files.

However, you may implement this semantic with any "general" filesystem, which allows directly to set file_operations callbacks. You may create a file, e.g., under debugfs (/sys/kernel/debug/):

```<code>ssize_t my_read (struct file * filp, char __user * buf, size_t size, loff_t * offp)
{
    static char a = 'a';
    printk("reading data\n");
    a++;
    copy_to_user(buf, &a, 1);
    return 1;
}

struct file_operations my_ops = {
    .owner = THIS_MODULE,
    .read = &my_read
};

int module_init(void)
{
    debugfs_create_file("showme", S_IRUGO, NULL, NULL, &my_ops);
    ...
}
</code>```

Title: Reading a configfs file

Body:
I am writing an user space process that will read data from the configfs entry continuously. I have defined callback function for read in kernel.
When I invoke read in a loop, only for the first time callback is called and for the next iterations control is not hitting the callback.

Kernel callback for read is simple function that will return a character.

static ssize_t show(struct config_item *item, char *page)
{
    static char a = 'a';
    printk("reading data\n");
    page[0] = a++;
    return 1;
}

User space process will read the data and display it on the screen.

int main()
{
   int fd = open("/sys/kernel/config/sample/showme", O_RDONLY);
   int ret;
   int i = 5;
   char receive[8];

   if (fd < 0) {
       perror("Failed to open the device...");
       return errno;
   }
   while(i--) {
       ret = read(fd, receive, 1);
       if (ret < 0) {
           perror("Failed to read the message\n");
           return errno;
       }
       printf("Message is %x with size %d\n", receive[0], ret);
   }
   close(fd);
}

output:

    Message is 61 with size 1

    Message is 61 with size 0

    Message is 61 with size 0

    Message is 61 with size 0

    Message is 61 with size 0

Note: The flow goes well if I close and open the file for all reads.

How to fix the above problem? I want the data to be reflected on all read.

Body:
A file under configfs filesystem is interpreted as an attribute, which have specific finite content at any moment.

E.g., a file may have content:

"123" at moment 1ns

"abc" at moment 2ns

"" (empty) at moment 3ns

and so on.

Moreover, configfs filesystem ensures, that after opening the file, any read() performed by the user will see portion of data consistent with other read()s. Assuming the example above, user won't read first symbol "1" (as at moment 1ns), 2nd symbol "b" (as at moment 2ns) and then found 3d symbol to be absent (as at moment 3ns).

So, after opening the file, .show() method is called once, and is expected to return whole content of the file. This content (or an appropriate portion of it) is returned upon futher read requests from the user.

Consistency guarantee is cleared at closing the file; so when you open it again, .show() will be called once more, and user's read requests will return updated content of the file.

I am writing an user space process that will read data from the configfs entry continuously.

With this semantic abstraction of finite file's content is lost, so you cannot implement that for configfs files.

However, you may implement this semantic with any "general" filesystem, which allows directly to set file_operations callbacks. You may create a file, e.g., under debugfs (/sys/kernel/debug/):

ssize_t my_read (struct file * filp, char __user * buf, size_t size, loff_t * offp)
{
    static char a = 'a';
    printk("reading data\n");
    a++;
    copy_to_user(buf, &a, 1);
    return 1;
}

struct file_operations my_ops = {
    .owner = THIS_MODULE,
    .read = &my_read
};

int module_init(void)
{
    debugfs_create_file("showme", S_IRUGO, NULL, NULL, &my_ops);
    ...
}


问:
Importing Swift into Objective-C: Objective-C header "-Swift.h" is not created
In my Swift Project, I added a new cocoa Objective-C class (UIViewController), Xcode prompted me whether I want it to automatically generate an Objective-C bridging header file.

I am a bit confused because the generated file is ProductModuleName-Bridging-Header.h while, as per Apple documentation, I was waiting to get a ProductModuleName-Swift.h instead (In order to import Swift into Objective-C).

The ProductModuleName-Bridging-Header.h is mandatory in order to be able to import Objective-C from Swift, and not the inverse.

Any clarification on this?

Thanks

答:
The behavior you describe is exactly correct. You're adding Obj-C to your Swift project, therefore Xcode offers to create a -Bridging-Header.h file which allows that imported Obj-C to be used in your Swift code. This is described in the documentation you linked under "Importing Objective-C into Swift".

Unlike the bridging header, the -Swift.h file doesn't appear in your file hierachy, and is not something you see or edit. It's generated and managed entirely by Xcode during the build process. You simply import into .m files when needed.


问:
ImageView stays empty if I extend Activity but works as expected if I extend AppCompatActivity
I am not sure why I am not able to show images in my app using ImageView. Any ideas? Please ask if you need more information. Thanks!

In my activity_main.xml I have:

```<code><ImageView
            android:id="@+id/imageView2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:srcCompat="@drawable/armas_barcode" />
</code>```

Perhaps the contents are irrelevant. In my MainActivity I have public class MainActivity extends Activity { then the image is not printed and no errors are logged. If I change it to public class MainActivity extends AppCompatActivity { then image is printed on screen as expected. The image is a vector image.

I have other vector images which I use in settings/preferences as android:icon and they seem to work fine.

My build.gradle is as folllows:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.zebget.pricemap"
        minSdkVersion 25
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:design:27.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

答:
If a layout file contains lines which do not work because they require e.g. a different API level, then they are simply ignored, the code compiles and the app works. More or less.

If your MainActivity extends Activity, then the following line in the layout will not be applicable.

app:srcCompat="@drawable/armas_barcode"

This is because the app namespace ( xmlns:app="http://schemas.android.com/apk/res-auto") only works with an AppCompatActivity.

But you can also set the drawable resource for your ImageView like this:

```<code>android:src="@drawable/armas_barcode"
</code>```

Body:
I am not sure why I am not able to show images in my app using ImageView. Any ideas? Please ask if you need more information. Thanks!

In my activity_main.xml I have:

<ImageView
            android:id="@+id/imageView2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:srcCompat="@drawable/armas_barcode" />

Perhaps the contents are irrelevant. In my MainActivity I have public class MainActivity extends Activity { then the image is not printed and no errors are logged. If I change it to public class MainActivity extends AppCompatActivity { then image is printed on screen as expected. The image is a vector image.

I have other vector images which I use in settings/preferences as android:icon and they seem to work fine.

My build.gradle is as folllows:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.zebget.pricemap"
        minSdkVersion 25
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:design:27.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Body:
If a layout file contains lines which do not work because they require e.g. a different API level, then they are simply ignored, the code compiles and the app works. More or less.

If your MainActivity extends Activity, then the following line in the layout will not be applicable.

app:srcCompat="@drawable/armas_barcode"

This is because the app namespace ( xmlns:app="http://schemas.android.com/apk/res-auto") only works with an AppCompatActivity.

But you can also set the drawable resource for your ImageView like this:

android:src="@drawable/armas_barcode"


问:
Can anyone tell me where can I get sample UML diagrams for an ERP system?
I want to study an ERP system. For that I want to study its processes. So if anyone can give me some useful links then it will be helpful to me, thanks.</p>

答:
This is a tipical UML, I was looking for same that you, to show this to a client, and this is the best example
https://creately.com/diagram/example/hn34ipx61/ERP</p>

OwnerDisplayName: UML


问:
symfony3.4 service container in template
I do have defined a service in my MainBundle/MainFunctions/ and in Controller I can call the service. How can I get the service container in SYMFONY 3.4 in a template now? Read the docs that it is not public anymore.

```<code>#view/template.html.php
<?php $shop_id = $this->container->get('main_functions')->getSessionShopId(); ?>
</code>```

My config.yml

```<code>imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: "@FrontendMainBundle/Resources/config/services.yml
</code>```

my FrontendMainBundle/Resources/config/services.yml

```<code>services:
    _defaults:
        public: true
    frontend_locale.locale_listener:
        class: Frontend\MainBundle\EventListener\LocaleListener
        arguments: ["%kernel.default_locale%"]
        tags:
            - { name: kernel.event_subscriber }
    main_functions:
        public: true
        class: "%main_functions_class.class%"
        arguments: ['@translator', '@doctrine.orm.entity_manager'....
</code>```

I read the docs that it is not public anymore. But I can't get to main_functions in template. How?

THANKS!!!

答:
if you need some inteligence in your template, I advice you to use twig extension: https://symfony.com/doc/current/templating/twig_extension.html

this you will be able to call {{ yourFunction }}

this is quite simple.

Body:
I do have defined a service in my MainBundle/MainFunctions/ and in Controller I can call the service. How can I get the service container in SYMFONY 3.4 in a template now? Read the docs that it is not public anymore.

#view/template.html.php
<?php $shop_id = $this->container->get('main_functions')->getSessionShopId(); ?>

My config.yml

imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: "@FrontendMainBundle/Resources/config/services.yml

my FrontendMainBundle/Resources/config/services.yml

services:
    _defaults:
        public: true
    frontend_locale.locale_listener:
        class: Frontend\MainBundle\EventListener\LocaleListener
        arguments: ["%kernel.default_locale%"]
        tags:
            - { name: kernel.event_subscriber }
    main_functions:
        public: true
        class: "%main_functions_class.class%"
        arguments: ['@translator', '@doctrine.orm.entity_manager'....

I read the docs that it is not public anymore. But I can't get to main_functions in template. How?

THANKS!!!


问:
Java cast ArrayList to C#
Need to cast a Java ArrayList to C# ArrayList.

It does not work.

```<code>//code in C#
public void DoSomething(Java.Lang.Object obj){
    Java.Util.ArrayList list = (Java.Util.ArrayList) obj;
}
</code>```

The Exception:

Unhandled Exception:

System.InvalidCastException: Specified cast is not valid.

When I print out obj.Class, it returns class java.util.ArrayList

How to fix it?

答: I do not write C# code but if this was me and I needed to convert an object for use in a different language I would just serialize the Java object to JSON and deserialize it to my object in C#.</p>

Title: Java cast ArrayList to C#

Body:
Need to cast a Java ArrayList to C# ArrayList.

It does not work.

//code in C#
public void DoSomething(Java.Lang.Object obj){
    Java.Util.ArrayList list = (Java.Util.ArrayList) obj;
}

The Exception:

Unhandled Exception:

System.InvalidCastException: Specified cast is not valid.

When I print out obj.Class, it returns class java.util.ArrayList

How to fix it?


问:
Dealing with special characters in pandas Data Frame´s column Name
I am importing an excel worksheet that has the following columns name:

```<code>N° Pedido
   1234
   6424
   4563
</code>```

The column name ha a special character (°). Because of that, I can´t merge this with another Data Frame or rename the column. I don´t get any error message just the name stays the same. What should I do?

This is the code I am using and the result of the Dataframes:

```<code>    import pandas as pd
    import numpy as np
    # Importando Planilhas
    CRM = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
    Vendas\relatorio_vendas_CRM.xlsx', encoding= 'utf-8')
    protheus = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
    Vendas\relatorio_vendas_protheus.xlsx', encoding= 'utf-8')
    #transformando em Data Frame
    df_crm = CRM.parse('190_pedido_export (33)')
    df_protheus = protheus.parse('Relatorio de Pedido de Venda')]
    # Transformando Campos em float o protheus
    def turn_to_float(x):
    return np.float(x)

    df_protheus["TES"] = df_protheus["TES"].apply(turn_to_float)
    df_protheus["Qtde"] = df_protheus["Qtde"].apply(turn_to_float)
    df_protheus["Valor"] = df_protheus["Valor"].apply(turn_to_float)
    #Tirando Tes de não venda do protheus
    # tirando valores com código errado 6
    df_protheus_1 = df_protheus[df_protheus.TES != 513.0]
    df_protheus_2 = df_protheus_1[df_protheus_1.TES != 576.0]

    **df_crm.columns = df_crm.columns.str.replace('N° Pedido', 'teste')
    df_crm.columns**

    Orçamento Origem    N° Pedido   Nº Pedido ERP   Estabelecimento Tipo de
    Pedido  Classificação(Tipo) Aplicação   Conta   CNPJ/CPF    Contato ...
    Aprovação Parcial   Antecipa Entrega    Desconto da Tabela de Preço
    Desconto do Cliente Desconto Informado  Observações Observações NF  Vl
    Total Bruto Vl Total    Completo
    0   20619.0 23125   NaN Optitex 1 - Venda   NaN Industrialização/Revenda
    XAVIER E ARAUJO LTDA ME 7970626000170   NaN ... N   N   0   0   0
</code>```

Note that I used other codes for the bold part with the same result:

```<code>#renomeando tabela para dar Merge
#df_crm['proc'] = df_crm['N\xc2\xb0 Pedido']

#df_crm['N Pedido'] = df_crm['N° Pedido']
#df_crm.drop('N° Pedido',inplace=True,axis=1)
#df_crm

#df_crm['N Pedido'] = df_crm['N° Pedido']
#df.drop('N° Pedido',inplace=True,axis=1)
#df_crm

#df_crm_1 = df_crm.rename(columns={"N°Pedido": "teste"})
#df_crm_1
</code>```

答:
I was able to copy the values into another column. You could try that</p>

```<code>df['N Pedido'] = df['N° Pedido']
df.drop('N° Pedido',inplace=True,axis=1)
</code>```

Body:
I am importing an excel worksheet that has the following columns name:

N° Pedido
   1234
   6424
   4563

The column name ha a special character (°). Because of that, I can´t merge this with another Data Frame or rename the column. I don´t get any error message just the name stays the same. What should I do?

This is the code I am using and the result of the Dataframes:

    import pandas as pd
    import numpy as np
    # Importando Planilhas
    CRM = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
    Vendas\relatorio_vendas_CRM.xlsx', encoding= 'utf-8')
    protheus = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de
    Vendas\relatorio_vendas_protheus.xlsx', encoding= 'utf-8')
    #transformando em Data Frame
    df_crm = CRM.parse('190_pedido_export (33)')
    df_protheus = protheus.parse('Relatorio de Pedido de Venda')]
    # Transformando Campos em float o protheus
    def turn_to_float(x):
    return np.float(x)

    df_protheus["TES"] = df_protheus["TES"].apply(turn_to_float)
    df_protheus["Qtde"] = df_protheus["Qtde"].apply(turn_to_float)
    df_protheus["Valor"] = df_protheus["Valor"].apply(turn_to_float)
    #Tirando Tes de não venda do protheus
    # tirando valores com código errado 6
    df_protheus_1 = df_protheus[df_protheus.TES != 513.0]
    df_protheus_2 = df_protheus_1[df_protheus_1.TES != 576.0]

    **df_crm.columns = df_crm.columns.str.replace('N° Pedido', 'teste')
    df_crm.columns**

    Orçamento Origem    N° Pedido   Nº Pedido ERP   Estabelecimento Tipo de
    Pedido  Classificação(Tipo) Aplicação   Conta   CNPJ/CPF    Contato ...
    Aprovação Parcial   Antecipa Entrega    Desconto da Tabela de Preço
    Desconto do Cliente Desconto Informado  Observações Observações NF  Vl
    Total Bruto Vl Total    Completo
    0   20619.0 23125   NaN Optitex 1 - Venda   NaN Industrialização/Revenda
    XAVIER E ARAUJO LTDA ME 7970626000170   NaN ... N   N   0   0   0

Note that I used other codes for the bold part with the same result:

#renomeando tabela para dar Merge
#df_crm['proc'] = df_crm['N\xc2\xb0 Pedido']

#df_crm['N Pedido'] = df_crm['N° Pedido']
#df_crm.drop('N° Pedido',inplace=True,axis=1)
#df_crm

#df_crm['N Pedido'] = df_crm['N° Pedido']
#df.drop('N° Pedido',inplace=True,axis=1)
#df_crm

#df_crm_1 = df_crm.rename(columns={"N°Pedido": "teste"})
#df_crm_1

Body:
I was able to copy the values into another column. You could try that

df['N Pedido'] = df['N° Pedido']
df.drop('N° Pedido',inplace=True,axis=1)


问:
SSRS - One tablix with 2 Datasets
I am trying to build a report to show projects and subprojects status updates with data for projects and subprojects coming from 2 separate sharepoint lists i.e. datasets in the same data source.

The problem is

That I do not know how to build a lookup function for tablix to pull data from different sharepoint lists.

Tablix needs to have a rule for exceptions: 3 projects have subprojects but the other do not have subprojects.

The expected result is for tablix to display status report in the following way:

```<code>status update   next steps
project1
project2
project3
    subproject 3.1
    subproject 3.2
    subproject 3.3
</code>```

I have linked the projects to subprojects using a key.

Advice much appreciated.

答:
In current release of Reporting Services, each tablix can contains only one dataset. So in your scenario, the easiest way to achieve your requirement is combining the two datasets into one using Join in the query if it is possible. If the datasets cannot be combined, there are two ways you can give a try

a. Subreport - create a subreport to display in another report

1.Create another report as the subreport and insert the child row data.

2.Create a parameter named ID in the subreport.

3.In the main report, right-click to insert a subreport in the child row.

4.Right-click the subpeort to open the Subreport Properties, and select the
subreport name in the drop-down list.

5.In the left panel of the Subreport Properties dialog box, click Parameters.

6.Select Name in the drop-down list of ID, and select [ID] in the drop-down list
of Value.

b.  Use 'lookupset' function (more on lookupset function Lookupset Function

Title: SSRS - One tablix with 2 Datasets

Body:
I am trying to build a report to show projects and subprojects status updates with data for projects and subprojects coming from 2 separate sharepoint lists i.e. datasets in the same data source.

The problem is

That I do not know how to build a lookup function for tablix to pull data from different sharepoint lists.

Tablix needs to have a rule for exceptions: 3 projects have subprojects but the other do not have subprojects.

The expected result is for tablix to display status report in the following way:

status update   next steps
project1
project2
project3
    subproject 3.1
    subproject 3.2
    subproject 3.3

I have linked the projects to subprojects using a key.

Advice much appreciated.


问:
How to remove line breaks with PHP or JS
I've tried about everything to delete some extra \n  characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.

And yes I've tried things like

In JS:

```<code>text.replace(/\n/g,"")
</code>```

In PHP:

```<code>preg_replace("[\n]","",$result);
str_replace("\n","",$result);
</code>```

and when I try

```<code> text.replace(/\n/g,"")
</code>```

in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.

I'm desperate, picky and this is killing me. Any input is appreciated.

EDIT:

If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.

Answer Explanation:

Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!

In my case:

Why this works?   str_replace('\n', '', $result)

And this doesn't?   str_replace("\n", '', $result)

Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.

If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.

答:
In javascript, the .replace() method doesn't modify the string. It returns a new modified string, so you need to reference the result.

```<code>text = text.replace(/\n/g,"")
</code>```

Body:
I've tried about everything to delete some extra \n  characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.

And yes I've tried things like

In JS:

text.replace(/\n/g,"")

In PHP:

preg_replace("[\n]","",$result);
str_replace("\n","",$result);

and when I try

 text.replace(/\n/g,"")

in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.

I'm desperate, picky and this is killing me. Any input is appreciated.

EDIT:

If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.

Answer Explanation:

Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!

In my case:

Why this works?   str_replace('\n', '', $result)

And this doesn't?   str_replace("\n", '', $result)

Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.

If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.

Body:
In javascript, the .replace() method doesn't modify the string. It returns a new modified string, so you need to reference the result.

text = text.replace(/\n/g,"")


问:
Hosting WCF Service within WinForm Application doesn't work when running the application executable

Over the past few weeks I have developed a 64-bit WinForms application that needs to communicate with a 32-bit DLL (job specs require it).

After doing some reading around the internet and finding out that there is not going to be any fun way of doing this, I decided to go with hosting a WCF Service Application within my WinForms application for communicating to the 32-bit DLL... or so I thought I was doing.

During development (while running within Visual Studio) it has been working really well, but of course, now that I need to deploy, I am running into problems. I am having trouble getting a strong enough understanding of WCF Services to know if I am going about this in a terrible way or if I am just missing some minute detail.

I created the project as Admin. After development was finished I tried to run the WinForm executable (both debug and release), WindowsFormsApplication1.exe. The application started up, but after I tried to complete a task involving the use of the WCF service, an exception was thrown:

This has led me to believe that Visual Studio was doing the hosting of the service during development instead of the WinForm application, or my configs and/or directory structures are incorrect.

[UPDATED] WCF Service Web.config:

```<code><?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" maxRequestLength="2147483647"/>
  </system.web>

  <system.net>
    <defaultProxy>
      <proxy usesystemdefault="False"/>
    </defaultProxy>
  </system.net>

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="xml"
           type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="C:\logs\Traces.svclog" />
    </sharedListeners>
  </system.diagnostics>

  <system.serviceModel>
    <diagnostics wmiProviderEnabled="true">
      <messageLogging
           logEntireMessage="true"
           logMalformedMessages="true"
           logMessagesAtServiceLevel="true"
           logMessagesAtTransportLevel="true"
           maxMessagesToLog="3000"
       />
    </diagnostics>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadadiscovery>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

<services>
  <service name="ServiceReference1.Service1" behaviorConfiguration="metadadiscovery">
    <endpoint address="" binding="basicHttpBinding" contract="ServiceReference1.IService1"></endpoint>
  </service>
</services>

    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="false"/>
  </system.webServer>

</configuration>
</code>```

WinForm App.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService2" />
        <binding name="BasicHttpBinding_IService3" />
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:45053/Service2.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService2" contract="ServiceReference2.IService2"
        name="BasicHttpBinding_IService2" />
      <endpoint address="http://localhost:46351/Service3.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService3" contract="ServiceReference3.IService3"
        name="BasicHttpBinding_IService3" />
      <endpoint address="http://localhost:44848/Service1.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
        name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>
  <appSettings>
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>
</code>```

Directory Where EXE resides:

The directory containing the WCF Service resides within the directory WcfService1 from the image above.

I have mostly been using the following method of instantiating the service:

```<code>ServiceReference1.Service1Client = new ServiceReference1.SErvice1Client();
</code>```

Once I tried to switch to using a service host (below), but when I used that method, the service would timeout whenever it tried to communicate to the DLL.

```<code>Uri address = new Uri("http://localhost:44848/Service1.svc");
ServiceHost host = new ServiceHost(typeof(ServiceReference1.Service1Client), address);
host.Open();
</code>```

And then I closed the host later. At this point, I am willing to try anything to get this working.

[EDIT] Below is the code of my WindowsFormsApplication1.exe.config file. All three contracts are giving the warning that they're "invalid according to its datatype 'clientContractType'". I think this could be the source of my problems, but I do not know why it is showing this warning:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService2" />
        <binding name="BasicHttpBinding_IService3" />
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:45053/Service2.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService2" contract="ServiceReference2.IService2" name="BasicHttpBinding_IService2" />
      <endpoint address="http://localhost:46351/Service3.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService3" contract="ServiceReference3.IService3" name="BasicHttpBinding_IService3" />
      <endpoint address="http://localhost:44848/Service1.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>
</configuration>
</code>```

Thank you for any help and guidance you can provide.

答:
After sufficient struggling I decided to get rid of the WCF service that visual studio generates for you when you create it as a new project. I instead followed this tutorial verbatim:

Hosting Service In App

Doing this came with huge advantages:

No configuration file was necessary

Running it this way must've gotten rid of a large amount of overhead because the communication to the DLL (what I am using the service for) used to take several seconds to do large amounts of calls to the DLL, but now is able to handle 10k+ calls in the blink of an eye.

No service reference is necessary. I just needed the file for my main function, the file containing the service function implementations and the file containing the interface for the implementation.

So far, this has been the easiest and most robust way I have found for using a 32 bit DLL in a 64 bit application. Let me know if I can give any guidance for anyone else who may be struggling with this problem. I know this is not a fun thing to deal with if you've never done anything like it before.

Body:
Over the past few weeks I have developed a 64-bit WinForms application that needs to communicate with a 32-bit DLL (job specs require it).

After doing some reading around the internet and finding out that there is not going to be any fun way of doing this, I decided to go with hosting a WCF Service Application within my WinForms application for communicating to the 32-bit DLL... or so I thought I was doing.

During development (while running within Visual Studio) it has been working really well, but of course, now that I need to deploy, I am running into problems. I am having trouble getting a strong enough understanding of WCF Services to know if I am going about this in a terrible way or if I am just missing some minute detail.

I created the project as Admin. After development was finished I tried to run the WinForm executable (both debug and release), WindowsFormsApplication1.exe. The application started up, but after I tried to complete a task involving the use of the WCF service, an exception was thrown:

This has led me to believe that Visual Studio was doing the hosting of the service during development instead of the WinForm application, or my configs and/or directory structures are incorrect.

[UPDATED] WCF Service Web.config:

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" maxRequestLength="2147483647"/>
  </system.web>

  <system.net>
    <defaultProxy>
      <proxy usesystemdefault="False"/>
    </defaultProxy>
  </system.net>

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
          <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="xml"
           type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="C:\logs\Traces.svclog" />
    </sharedListeners>
  </system.diagnostics>

  <system.serviceModel>
    <diagnostics wmiProviderEnabled="true">
      <messageLogging
           logEntireMessage="true"
           logMalformedMessages="true"
           logMessagesAtServiceLevel="true"
           logMessagesAtTransportLevel="true"
           maxMessagesToLog="3000"
       />
    </diagnostics>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadadiscovery>

          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

<services>
  <service name="ServiceReference1.Service1" behaviorConfiguration="metadadiscovery">
    <endpoint address="" binding="basicHttpBinding" contract="ServiceReference1.IService1"></endpoint>
  </service>
</services>

    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>

    <directoryBrowse enabled="false"/>
  </system.webServer>

</configuration>

WinForm App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService2" />
        <binding name="BasicHttpBinding_IService3" />
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:45053/Service2.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService2" contract="ServiceReference2.IService2"
        name="BasicHttpBinding_IService2" />
      <endpoint address="http://localhost:46351/Service3.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService3" contract="ServiceReference3.IService3"
        name="BasicHttpBinding_IService3" />
      <endpoint address="http://localhost:44848/Service1.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
        name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>
  <appSettings>
    <add key="ClientSettingsProvider.ServiceUri" value="" />
  </appSettings>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

Directory Where EXE resides:

The directory containing the WCF Service resides within the directory WcfService1 from the image above.

I have mostly been using the following method of instantiating the service:

ServiceReference1.Service1Client = new ServiceReference1.SErvice1Client();

Once I tried to switch to using a service host (below), but when I used that method, the service would timeout whenever it tried to communicate to the DLL.

Uri address = new Uri("http://localhost:44848/Service1.svc");
ServiceHost host = new ServiceHost(typeof(ServiceReference1.Service1Client), address);
host.Open();

And then I closed the host later. At this point, I am willing to try anything to get this working.

[EDIT] Below is the code of my WindowsFormsApplication1.exe.config file. All three contracts are giving the warning that they're "invalid according to its datatype 'clientContractType'". I think this could be the source of my problems, but I do not know why it is showing this warning:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService2" />
        <binding name="BasicHttpBinding_IService3" />
        <binding name="BasicHttpBinding_IService1" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:45053/Service2.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService2" contract="ServiceReference2.IService2" name="BasicHttpBinding_IService2" />
      <endpoint address="http://localhost:46351/Service3.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService3" contract="ServiceReference3.IService3" name="BasicHttpBinding_IService3" />
      <endpoint address="http://localhost:44848/Service1.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
    </client>
  </system.serviceModel>
</configuration>

Thank you for any help and guidance you can provide.


问:
How to delete specific elements in a vector using struct data type
i'm new to C++. My program is a quiz game which user can choose category and level for the questions. At first, i use the struct data type

```<code>struct QuestionInfo
{
   string category;
   string level;
   string question;
   string answer;
};
</code>```

then

```<code>vector<QuestionInfo> vec;
</code>```

The idea of this part is to store the info of the question include (category, level, question and answer) to each element.
Then after building menu and the output questions UI, i go to the filters

```<code>void category_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (category_choice != vec[i].category)
         vec.erase(vec.begin() + i );
   }
}
Void level_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (level_choice != vec[i].level)
         vec.erase(vec.begin() + i );
   }
}
</code>```

So the idea of the filters is to delete the elements which not contain the matched category and level. But the output questions did not match with the category and the level i had choose before.  I'm not sure what I'm doing wrong.

答:
You might want to remove_if + erase:

```<code>#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
    struct QuestionInfo
    {
        std::string category;
        std::string level;
        std::string question;
        std::string answer;
        QuestionInfo(std::string category, std::string level, std::string question, std::string answer) :
            category(category), level(level), question(question), answer(answer) {}
    };

    std::vector<QuestionInfo> vec;
    std::string category_choice = "cat1";
    std::string level_choice = "lev1";

    vec.push_back(QuestionInfo("cat1", "lev1", "q1", "a1"));
    vec.push_back(QuestionInfo("cat1", "lev2", "q2", "a2"));
    vec.push_back(QuestionInfo("cat2", "lev1", "q3", "a3"));
    vec.push_back(QuestionInfo("cat2", "lev2", "q4", "a4"));

    std::cout << "\nNot filered" << std::endl;
    for (auto const &info : vec)
        std::cout << "Category:" << info.category << " Level:" << info.level << std::endl;

    auto filter_category = std::remove_if(vec.begin(), vec.end(), [&](auto const &info) {return category_choice != info.category; });
    vec.erase(filter_category, vec.end());

    std::cout << "\nFilered by category" << std::endl;
    for (auto const &info : vec)
        std::cout << "Category:" << info.category << " Level:" << info.level << std::endl;

    auto filter_level = std::remove_if(vec.begin(), vec.end(), [&](auto const &info) {return level_choice != info.level; });
    vec.erase(filter_level, vec.end());

    std::cout << "\nFiltered by level" << std::endl;
    for (auto const &info : vec)
        std::cout << "Category:" << info.category << " Level:" << info.level << std::endl;

    system("pause");
    return 0;
}
</code>```

Body:
i'm new to C++. My program is a quiz game which user can choose category and level for the questions. At first, i use the struct data type

struct QuestionInfo
{
   string category;
   string level;
   string question;
   string answer;
};

then

vector<QuestionInfo> vec;

The idea of this part is to store the info of the question include (category, level, question and answer) to each element.
Then after building menu and the output questions UI, i go to the filters

void category_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (category_choice != vec[i].category)
         vec.erase(vec.begin() + i );
   }
}
Void level_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (level_choice != vec[i].level)
         vec.erase(vec.begin() + i );
   }
}

So the idea of the filters is to delete the elements which not contain the matched category and level. But the output questions did not match with the category and the level i had choose before.  I'm not sure what I'm doing wrong.

Body:
You might want to remove_if + erase:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
    struct QuestionInfo
    {
        std::string category;
        std::string level;
        std::string question;
        std::string answer;
        QuestionInfo(std::string category, std::string level, std::string question, std::string answer) :
            category(category), level(level), question(question), answer(answer) {}
    };

    std::vector<QuestionInfo> vec;
    std::string category_choice = "cat1";
    std::string level_choice = "lev1";

    vec.push_back(QuestionInfo("cat1", "lev1", "q1", "a1"));
    vec.push_back(QuestionInfo("cat1", "lev2", "q2", "a2"));
    vec.push_back(QuestionInfo("cat2", "lev1", "q3", "a3"));
    vec.push_back(QuestionInfo("cat2", "lev2", "q4", "a4"));

    std::cout << "\nNot filered" << std::endl;
    for (auto const &info : vec)
        std::cout << "Category:" << info.category << " Level:" << info.level << std::endl;

    auto filter_category = std::remove_if(vec.begin(), vec.end(), [&](auto const &info) {return category_choice != info.category; });
    vec.erase(filter_category, vec.end());

    std::cout << "\nFilered by category" << std::endl;
    for (auto const &info : vec)
        std::cout << "Category:" << info.category << " Level:" << info.level << std::endl;

    auto filter_level = std::remove_if(vec.begin(), vec.end(), [&](auto const &info) {return level_choice != info.level; });
    vec.erase(filter_level, vec.end());

    std::cout << "\nFiltered by level" << std::endl;
    for (auto const &info : vec)
        std::cout << "Category:" << info.category << " Level:" << info.level << std::endl;

    system("pause");
    return 0;
}


问:
How do you access data in the template when using DRF ModelViewSet and TemplateHTMLRenderer?
I've got a Django Rest Framework ModelViewSet and am trying to use the TemplateHTMLRenderer to display HTML. Following along in the tutorial:

```<code>from rest_framework import permissions, renderers, viewsets
from rest_framework.decorators import link

from . import models, serializers
from .permissions import IsOwnerOrReadOnly

class SnippetViewSet(viewsets.ModelViewSet):
    template_name = 'snippet-list.html'
    queryset = models.Snippet.objects.all()
    serializer_class = serializers.SnippetSerializer
    renderer_classes = (renderers.TemplateHTMLRenderer,)
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

    @link(renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

    def pre_save(self, obj):
        obj.owner = self.request.user
</code>```

If I add a key in def resolve_context() I can access the model objects in my template that are passed into the RequestContext. If I don't add the data key then I don't know how to access the Snippets.

```<code>def resolve_context(self, data, request, response):
    if response.exception:
        data['status_code'] = response.status_code

    #return RequestContext(request, data)  # original source on github
    return RequestContext(request, {'data': data})  # if I add a key I can access it
</code>```

So I've got to be missing something easy or how I'm expecting this to behave is not how the authors intended?

答:
Inside the viewset use renderer class

renderer_classes = (renderers.JSONRenderer, renderers.TemplateHTMLRenderer)

like above and override the ListModelMixin's list method.

mariodev's answer gives the best example also.

Body:
I've got a Django Rest Framework ModelViewSet and am trying to use the TemplateHTMLRenderer to display HTML. Following along in the tutorial:

from rest_framework import permissions, renderers, viewsets
from rest_framework.decorators import link

from . import models, serializers
from .permissions import IsOwnerOrReadOnly

class SnippetViewSet(viewsets.ModelViewSet):
    template_name = 'snippet-list.html'
    queryset = models.Snippet.objects.all()
    serializer_class = serializers.SnippetSerializer
    renderer_classes = (renderers.TemplateHTMLRenderer,)
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

    @link(renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

    def pre_save(self, obj):
        obj.owner = self.request.user

If I add a key in def resolve_context() I can access the model objects in my template that are passed into the RequestContext. If I don't add the data key then I don't know how to access the Snippets.

def resolve_context(self, data, request, response):
    if response.exception:
        data['status_code'] = response.status_code

    #return RequestContext(request, data)  # original source on github
    return RequestContext(request, {'data': data})  # if I add a key I can access it

So I've got to be missing something easy or how I'm expecting this to behave is not how the authors intended?