问:
Textview size needs to change according to user's given value in EditText
Dynamically change the TextView size based on user input. If user changes the value, textview needs to change

```<code>     et0=(EditText)findViewById(R.id.EditText0);
     bt = (Button)findViewById(R.id.btn);

     bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));
                    float i=et0.getTextSize();

                    tv.setText(text);
                    tv.setTextSize(i) ;
        }
    }

//problem is value is changing one time if edit again text size is not changing
any help advance thanks
</code>```

答: Try setting a variable so that it takes whatever the user gives you and uses that value as its set text size. Does that make sense? </p>

Body:
Dynamically change the TextView size based on user input. If user changes the value, textview needs to change

     et0=(EditText)findViewById(R.id.EditText0);
     bt = (Button)findViewById(R.id.btn);

     bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = ((et.getText().toString()));
                    float i=et0.getTextSize();

                    tv.setText(text);
                    tv.setTextSize(i) ;
        }
    }

//problem is value is changing one time if edit again text size is not changing
any help advance thanks


来源: stackexchange

问:
Keep Wingdi graphics permanent
I am making a C++ console application with lots of wingdi graphics mainly revolving around Rectangle() and FillRect() but as it is wingdi, the graphics are not permanent. The graphics get reset when i minimize the console, enlarge it, scroll down and whatsoever. I've seen in some threads that there is no predefined solution so you have to make one of your own.

One thing i tried, was drawing the rectangle once and then attaching a thread with infinite loop that checks the first pixel of rectangle in every iteration, if it's color is black, it draws whole rectangle again. As silly as it sounds, that's all i could think of. I know it's utterly inefficient. Is there any other solution for this?

答:
Although you've been able to use GDI to draw on your application's console window (presumably by calling GetConsoleWindow and then GetDC), it isn't really designed for that.  The system has code for the console window that tries to redraw the window itself whenever it needs to update.  It's not aware of anything your program does through GDI, so it has no way to preserve that.

If you just need to draw colorful rectangles on a console window, you can do those kinds of things with the Console API.  You can set the text colors as needed and draw blocks of spaces or block characters.

If you want to do more general graphics, your program will have to create a (non-console) window, and then you can draw whatever you want whenever your window receives a WM_PAINT message.

ContentLicense: CC BY-SA 3.0

Title: Keep Wingdi graphics permanent


问:
How do I create a string intermixed with specially formatted placeholders for custom text
I would like to create a string which has a placeholder held within curly brackets for custom text. For example

```<code>string mySpecialMessage = "Hi there developer {name}.
I see that you have {reputation} reputation points!
Thanks for looking at my stack overflow. You're a real {compliment}";
</code>```

I would then feed it into a method

```<code>Display(mySpecialMessage, MessageType.HighPriority, 2);
</code>```

And the method looks like this

```<code>public void Display (string messageContents, messageType messageType, float displayDuration)
{
// TODO - Format messageContents with replaced placeholders
// Create a new instance of message

Message newMessage = new Message(messageContents, messageType, displayDuration);

// Adds message to queue

messageQueue.Enqueue(newMessage);
if (!processing)
    {
        StartCoroutine(ProcessMessageQueue());
    }
}
}
</code>```

My question is: How do I extract all these curly brackets and format it back into the string?

答:
```<code>mySpecialMessage.Replace("{name}", "Your Name");
mySpecialMessage.Replace("{reputation}", "123");
mySpecialMessage.Replace("{compliment}", "hero");
</code>```

Body:
I would like to create a string which has a placeholder held within curly brackets for custom text. For example

string mySpecialMessage = "Hi there developer {name}.
I see that you have {reputation} reputation points!
Thanks for looking at my stack overflow. You're a real {compliment}";

I would then feed it into a method

Display(mySpecialMessage, MessageType.HighPriority, 2);

And the method looks like this

public void Display (string messageContents, messageType messageType, float displayDuration)
{
// TODO - Format messageContents with replaced placeholders
// Create a new instance of message

Message newMessage = new Message(messageContents, messageType, displayDuration);

// Adds message to queue

messageQueue.Enqueue(newMessage);
if (!processing)
    {
        StartCoroutine(ProcessMessageQueue());
    }
}
}

My question is: How do I extract all these curly brackets and format it back into the string?


问:
Ionic native Google Maps Android not working
I have to add a view with Google maps map on my project. I followed the official ionic native Google maps documentation but it does not work.

I assigned background color pink to the div that contains the map (for testing), before adding the map to the div, the div shows correctly. But when the map is added to the div the background of the modal window turns to transparent, and the div disappears. But no error is shown.

I tried different ways to attach the map on the div, but the results are the same.

When I use the code of the Ionic docs I got this error message "GoogleMaps [deprecated] Please use GoogleMaps.create()". I tried using GoogleMaps.create() instead of the argument of the constructor avoiding this error message, but still not working.

My ion-content:

```<code><ion-content fullscreen overflow-scroll="true" class="container">

  <div #map id="map"></div>

</ion-content>
</code>```

Part of the css:

```<code>#map {
        height: 90%;
        width: 100%;
        border-width: 5px;
        border-color: red;
        background: pink;
    }
</code>```

And here we got fragments of the ts:

```<code>import {
  GoogleMaps,
  GoogleMap,
  GoogleMapsEvent,
  GoogleMapOptions,
  CameraPosition,
  MarkerOptions,
  Marker
 } from '@ionic-native/google-maps';

...

export class PerfilPage {
  @ViewChild(Content) content: Content;
  @ViewChild('map') mapElement: ElementRef;
  map: GoogleMap;

...

ionViewDidLoad() {
// I use this for changing the nab-bar color
    this.content.ionScroll.subscribe((scroll) => {
      // console.log('user scrolled', scroll);
      if ( scroll.scrollTop > 100 ) {
        this.toolbar_color = "bg_search"
      } else {
        this.toolbar_color = "transparent"
      }
      this.ref.detectChanges();
    });

    // this.loadMap();
    // this.initMap();
    // this.testMap();
    this.offiMap();
  }

// Official Ionic documentation code
 offiMap() {
    let mapOptions: GoogleMapOptions = {
      camera: {
        target: {
          lat: 43.0741904,
          lng: -89.3809802
        },
        zoom: 18,
        tilt: 30
      }
    };

    this.map = this.googleMaps.create('map', mapOptions);

    // Wait the MAP_READY before using any methods.
    this.map.one(GoogleMapsEvent.MAP_READY)
      .then(() => {
        console.log('Map is ready!');

        // Now you can use all methods safely.
        this.map.addMarker({
            title: 'Ionic',
            icon: 'blue',
            animation: 'DROP',
            position: {
              lat: 43.0741904,
              lng: -89.3809802
            }
          })
          .then(marker => {
            marker.on(GoogleMapsEvent.MARKER_CLICK)
              .subscribe(() => {
                alert('clicked');
              });
          });

      });
  }
}
</code>```

PS: the API key works on other projects (not Ionic projects), so idk where is the problem.

Thanks :)

答:
As I describe on the git repo, the maps plugin places the native map view under (or behind) the browser.

https://github.com/mapsplugin/cordova-plugin-googlemaps#how-does-this-plugin-work

That's why all parent elements of the map div becomes transparent.

If you need to set the background of application, you need to use Environment.setBackground("pink").

Since the map is displayed under the browser, this plugin CAN NOT display on dialogs.

ContentLicense: CC BY-SA 4.0

Body:
I have to add a view with Google maps map on my project. I followed the official ionic native Google maps documentation but it does not work.

I assigned background color pink to the div that contains the map (for testing), before adding the map to the div, the div shows correctly. But when the map is added to the div the background of the modal window turns to transparent, and the div disappears. But no error is shown.

I tried different ways to attach the map on the div, but the results are the same.

When I use the code of the Ionic docs I got this error message "GoogleMaps [deprecated] Please use GoogleMaps.create()". I tried using GoogleMaps.create() instead of the argument of the constructor avoiding this error message, but still not working.

My ion-content:

<ion-content fullscreen overflow-scroll="true" class="container">

</ion-content>

Part of the css:

#map {
        height: 90%;
        width: 100%;
        border-width: 5px;
        border-color: red;
        background: pink;
    }

And here we got fragments of the ts:

import {
  GoogleMaps,
  GoogleMap,
  GoogleMapsEvent,
  GoogleMapOptions,
  CameraPosition,
  MarkerOptions,
  Marker
 } from '@ionic-native/google-maps';

...

export class PerfilPage {
  @ViewChild(Content) content: Content;
  @ViewChild('map') mapElement: ElementRef;
  map: GoogleMap;

...

ionViewDidLoad() {
// I use this for changing the nab-bar color
    this.content.ionScroll.subscribe((scroll) => {
      // console.log('user scrolled', scroll);
      if ( scroll.scrollTop > 100 ) {
        this.toolbar_color = "bg_search"
      } else {
        this.toolbar_color = "transparent"
      }
      this.ref.detectChanges();
    });

    // this.loadMap();
    // this.initMap();
    // this.testMap();
    this.offiMap();
  }

// Official Ionic documentation code
 offiMap() {
    let mapOptions: GoogleMapOptions = {
      camera: {
        target: {
          lat: 43.0741904,
          lng: -89.3809802
        },
        zoom: 18,
        tilt: 30
      }
    };

    this.map = this.googleMaps.create('map', mapOptions);

    // Wait the MAP_READY before using any methods.
    this.map.one(GoogleMapsEvent.MAP_READY)
      .then(() => {
        console.log('Map is ready!');

        // Now you can use all methods safely.
        this.map.addMarker({
            title: 'Ionic',
            icon: 'blue',
            animation: 'DROP',
            position: {
              lat: 43.0741904,
              lng: -89.3809802
            }
          })
          .then(marker => {
            marker.on(GoogleMapsEvent.MARKER_CLICK)
              .subscribe(() => {
                alert('clicked');
              });
          });

      });
  }
}

PS: the API key works on other projects (not Ionic projects), so idk where is the problem.

Thanks :)


问:
jQuery each() behavior if changing DOM within loop
What is the behavior of jquery when using each() loop? Is it:

look for the first object, execute function, look for the next object...

gather all objects in a container, then execute the function on each of them

other (what exactly?)

An example, where it is relevant:

```<code><div id="a">
   A
   <div id="b">
      B
   </div>
</div>
<div id="c">
    C
</div>
</code>```

If I execute this javascript:

```<code>$('div').each(function(index){
   alert($(this).html());
   $(this).remove();
}
</code>```

Will I see three alerts or only two?

答:
Regardless of what action you will perform on a selection, jQuery will make that selection before applying that action. By which I mean $('div') is a selector, the selection process happens before and regardless of the other chained methods (such as each()). This is a product of the language, since $() must be evaluated before a method can be called upon it.

If that selection grabbed three divs from your page, then there are now 3 jQuery objects in a list ready to be iterated over. You can prove this by doing:

```<code>$('div').length
</code>```

Thus you are iterating over an array with three indexes (0, 1, 2), if you remove the div from the DOM for index 1, the next iteration of the each() callback will still be for the object at index 2. Checkout this live demo for proof:

DEMO: http://jsfiddle.net/marcuswhybrow/HYJa4/

ContentLicense: CC BY-SA 2.5

Body:
What is the behavior of jquery when using each() loop? Is it:

look for the first object, execute function, look for the next object...

gather all objects in a container, then execute the function on each of them

other (what exactly?)

An example, where it is relevant:

   A

      B

    C

If I execute this javascript:

$('div').each(function(index){
   alert($(this).html());
   $(this).remove();
}

Will I see three alerts or only two?

Body:
Regardless of what action you will perform on a selection, jQuery will make that selection before applying that action. By which I mean $('div') is a selector, the selection process happens before and regardless of the other chained methods (such as each()). This is a product of the language, since $() must be evaluated before a method can be called upon it.

If that selection grabbed three divs from your page, then there are now 3 jQuery objects in a list ready to be iterated over. You can prove this by doing:

$('div').length

Thus you are iterating over an array with three indexes (0, 1, 2), if you remove the div from the DOM for index 1, the next iteration of the each() callback will still be for the object at index 2. Checkout this live demo for proof:

DEMO: http://jsfiddle.net/marcuswhybrow/HYJa4/


问:
Unable to calculate vertical coordinates for tooltip on Y-axis legend in D3 v4
I have created a graph which has a mouseover/tooltop for each legend item in the y-axis. The mouseover creates a tooltip which spans the width of the graph at the height of the y legend item.  I have successfully positioned the height and width as well as x-axis location of the tooltip but cannot come up with the right formula to locate the top of the tooltip.

```<code>var countryBox = d3.select("body").append("div")
    .attr("class", "countryTip")
    .style("opacity", 0);
</code>```

...

```<code>/*  Build mouseover infobox for each country in y axis legend in 1800 */
h.selectAll(".axis--y .tick text")
    .on("mouseover", function() {
        totSpec = 0;
        var myElement = d3.select(this);
        var countryName = myElement.text();
        /*  determine absolute coordinates for left edge of SVG */
        var matrix = this.getScreenCTM()
            .translate(+this.getAttribute("cx"), +this.getAttribute("cy"));
        h.selectAll("." + countryName.replace(/\s+/g, '_')).each(function(d) {
            totSpec += d.freqEnd;
            totSpec -= d.freqStart;
            sumSpec = sumSpec + d.freqEnd - d.freqStart;
        });
        var availPercent = totSpec / availSpec;

        countryBox.transition()
            .duration(200)
            .style("opacity", .9);
        var yText = getTranslation(d3.select(this.parentNode).attr("transform"));
        countryBox.html(countryName + '</br>' + r(totSpec) + ' MHz assigned out of ' + r(availSpec) + ' MHz available. <br><b>Band occupancy ' + p(availPercent) + '</b>')
            .style("left", (window.pageXOffset + matrix.e) + "px")
            .style("top", (yText[1] - y.bandwidth()/2 - window.pageYOffset) + "px")
            .style("height", y.bandwidth() + "px")
            .style("width", width + "px");
        console.log("yText[1]: "  + yText[1] + " halfBand: " + halfBand + " margin.top: " + margin.top + " window.pageYOffset: " + window.pageYOffset );

    })
    .on("mouseout", function() {
        countryBox.transition()
            .duration(500)
            .style("opacity", 0);
    });
</code>```

where

getTranslation is a function to compensate for the absence of d3.transform in v4 to

```<code>function getTranslation(transform) {
    var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
    g.setAttributeNS(null, "transform", transform);
    var matrix = g.transform.baseVal.consolidate().matrix;
    return [matrix.e, matrix.f];
}
</code>```

For

.style("top", (yText[1] - y.bandwidth()/2 - window.pageYOffset) + "px")

yText[1] returns the y coordinates of the y legend item the mouse is passing over, essentially the vertical midpoint of the country band in    question.

y.bandwidth()/2 represents half the vertical height of the
band and

window.pageYOffset compensates for scroll

As far as I can see, that should put the top of the tooltip at the top of the relevant x band.  Obviously not though.  Is bootstrap a factor?  If it comes to pure svg, I find I can draw a circle perfect laid out on each band use yText[1] as the centre point of the circle. Am I mixing up svg and html?

CSS

```<code>div.countryTip {
    position: fixed;
    z-index: 99;
    text-align: left;
    font-family: arial;
    font-size: 1em;
    line-height: 1.5;
    padding: 1.5em;
    background: #144667;
    border: 0px;
    color: white;
    border-radius: 3px;
    pointer-events: none;
    -webkit-transform: translate3d(0, -0.5em, 0);
    -moz-transform: translate3d(0, -0.5em, 0);
    transform: translate3d(0, -0.5em, 0);
    -webkit-transition: opacity 0.1s, -webkit-transform 0.1s;
    -moz-transition: opacity 0.1s, -moz-transform 0.1s;
    transition: opacity 0.1s, transform 0.1s;
}
</code>```

Working site and full source

Update:  Added a Plunker

答:
Finally solved this.  I was confusing the SVG and HTML coordinate systems.  The answer was to use the y element of the matrix coordinate defined by getScreenCTM()

```<code>let matrix = this.getScreenCTM()
   .translate(+this.getAttribute('cx') +this.getAttribute('cy'))
</code>```

with the result being

```<code>.style('top', matrix.f - y.bandwidth() / 2 + 8 + 'px')
</code>```

This post on understanding SVG coordinates and this practical example on SVG tooltips helped me get there in the end.

Body:
I have created a graph which has a mouseover/tooltop for each legend item in the y-axis. The mouseover creates a tooltip which spans the width of the graph at the height of the y legend item.  I have successfully positioned the height and width as well as x-axis location of the tooltip but cannot come up with the right formula to locate the top of the tooltip.

var countryBox = d3.select("body").append("div")
    .attr("class", "countryTip")
    .style("opacity", 0);

...

/*  Build mouseover infobox for each country in y axis legend in 1800 */
h.selectAll(".axis--y .tick text")
    .on("mouseover", function() {
        totSpec = 0;
        var myElement = d3.select(this);
        var countryName = myElement.text();
        /*  determine absolute coordinates for left edge of SVG */
        var matrix = this.getScreenCTM()
            .translate(+this.getAttribute("cx"), +this.getAttribute("cy"));
        h.selectAll("." + countryName.replace(/\s+/g, '_')).each(function(d) {
            totSpec += d.freqEnd;
            totSpec -= d.freqStart;
            sumSpec = sumSpec + d.freqEnd - d.freqStart;
        });
        var availPercent = totSpec / availSpec;

        countryBox.transition()
            .duration(200)
            .style("opacity", .9);
        var yText = getTranslation(d3.select(this.parentNode).attr("transform"));
        countryBox.html(countryName + '
' + r(totSpec) + ' MHz assigned out of ' + r(availSpec) + ' MHz available.
Band occupancy ' + p(availPercent) + '')
            .style("left", (window.pageXOffset + matrix.e) + "px")
            .style("top", (yText[1] - y.bandwidth()/2 - window.pageYOffset) + "px")
            .style("height", y.bandwidth() + "px")
            .style("width", width + "px");
        console.log("yText[1]: "  + yText[1] + " halfBand: " + halfBand + " margin.top: " + margin.top + " window.pageYOffset: " + window.pageYOffset );

    })
    .on("mouseout", function() {
        countryBox.transition()
            .duration(500)
            .style("opacity", 0);
    });

where

getTranslation is a function to compensate for the absence of d3.transform in v4 to

function getTranslation(transform) {
    var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
    g.setAttributeNS(null, "transform", transform);
    var matrix = g.transform.baseVal.consolidate().matrix;
    return [matrix.e, matrix.f];
}

For

.style("top", (yText[1] - y.bandwidth()/2 - window.pageYOffset) + "px")

yText[1] returns the y coordinates of the y legend item the mouse is passing over, essentially the vertical midpoint of the country band in    question.

y.bandwidth()/2 represents half the vertical height of the
band and

window.pageYOffset compensates for scroll

As far as I can see, that should put the top of the tooltip at the top of the relevant x band.  Obviously not though.  Is bootstrap a factor?  If it comes to pure svg, I find I can draw a circle perfect laid out on each band use yText[1] as the centre point of the circle. Am I mixing up svg and html?

CSS

div.countryTip {
    position: fixed;
    z-index: 99;
    text-align: left;
    font-family: arial;
    font-size: 1em;
    line-height: 1.5;
    padding: 1.5em;
    background: #144667;
    border: 0px;
    color: white;
    border-radius: 3px;
    pointer-events: none;
    -webkit-transform: translate3d(0, -0.5em, 0);
    -moz-transform: translate3d(0, -0.5em, 0);
    transform: translate3d(0, -0.5em, 0);
    -webkit-transition: opacity 0.1s, -webkit-transform 0.1s;
    -moz-transition: opacity 0.1s, -moz-transform 0.1s;
    transition: opacity 0.1s, transform 0.1s;
}

Working site and full source

Update:  Added a Plunker

Body:
Finally solved this.  I was confusing the SVG and HTML coordinate systems.  The answer was to use the y element of the matrix coordinate defined by getScreenCTM()

let matrix = this.getScreenCTM()
   .translate(+this.getAttribute('cx') +this.getAttribute('cy'))

with the result being

.style('top', matrix.f - y.bandwidth() / 2 + 8 + 'px')

This post on understanding SVG coordinates and this practical example on SVG tooltips helped me get there in the end.


问:
Filter mapping url-pattern that excludes subdirectories
Is there any way to make a filtermapping not include subdirectories?

For example.

I have .xhtml files in my context root, and I also have a subfolder named "test" with files with the same extension. Is there any may to map a filter to the files in context root and not to the files in the "test" directory?

答:
You can add a url-mapping value for every file you have in the context root, therefore the filter will apply to those files but none to the files in the test folder (actually it will only apply to those specific files). The following worked for me </p>

```<code><url-pattern>/index.faces</url-pattern>
</code>```

Body:
You can add a url-mapping value for every file you have in the context root, therefore the filter will apply to those files but none to the files in the test folder (actually it will only apply to those specific files). The following worked for me

<url-pattern>/index.faces</url-pattern>


问:
Detect if an app has been installed on iOS in JavaScript
I have been searching around to see if it was possible to check for already installed apps on an iOS device using JavaScript or another web language.

I'm aware of ways to do this natively in Objective-C but due to the nature of this project this detection must be done using web technology. This app I am attempting to detect does not have a specific URL scheme like snapchat:// so this answer is of no use in my situation.

I have also seen native projects use Apple private APIs like this one to detect all the installed apps on that device but Apple has since then closed off that private API disallowing any such detection. If such a thing was still possible it doesn't fit my criteria of web-based detection of installed apps.

答: If an application doesn't handle a unique URL scheme, there isn't even any way to detect it from a native iOS application. There's certainly no way to do that from within the web browser.</p>


问:
Template type deduction in function return type
This is in continuation with the question posted at Template type deduction for member variables and function arguments

My .h file contains the following lines.

```<code>#include <iostream>
#include <complex>
#include <typeinfo>

template <typename T>
class MyClass
 {

 template <typename T0>
struct myTypeTraits
 { using type = T0; };

template <typename T0>
struct myTypeTraits<std::complex<T0>>
 { using type = T0; };

public:

   using T0 = typename myTypeTraits<T>::type;

   void setVar1(const T0& v);

   void setVar2(const T& v);

 T0 getVar1() const;
T getVar2() const;

   void print() const;

   T0 var1;
   T  var2;
 };
</code>```

The .cpp file has the following codes.

```<code>#include "tmp.h"
template <class T>
void MyClass<T>::setVar1(const T0& v)
{
    var1 = v;
}

template <class T>
void MyClass<T>::setVar2(const T& v)
{
    var2 = v;
}

template <class T>
T0 MyClass<T>::getVar1() const
{
    return var1;
}

template <class T>
T MyClass<T>::getVar2() const
{
    return var2;
}

template <typename T>
void MyClass<T>::print() const
{
    std::cout<<"var1: "<<var1<<std::endl;
    std::cout<<"var2: "<<var2<<std::endl;

}

int main()
{

    MyClass<float> tmp;

    MyClass<std::complex<float> > tmp1;

    tmp.print();
    tmp1.print();
    return 0;
}
</code>```

Now when I compile the code using C++ 11 support in g++, I get the following error.

```<code>tmp.cpp:17:1: error: ‘T0’ does not name a type
 T0 MyClass<T>::getVar1() const
 ^
</code>```

How can I remove the error?

答:
Try with

```<code>// ......................vvvvvvvvvvvvvvvvvvvvvvv
void MyClass<T>::setVar1(typename MyClass<T>::T0 const & v)
{
    var1 = v;
}
</code>```

and the same for getVar1()

Body:
This is in continuation with the question posted at Template type deduction for member variables and function arguments

My .h file contains the following lines.

#include <iostream>
#include <complex>
#include <typeinfo>

template <typename T>
class MyClass
 {

 template <typename T0>
struct myTypeTraits
 { using type = T0; };

template <typename T0>
struct myTypeTraits<std::complex<T0>>
 { using type = T0; };

public:

   using T0 = typename myTypeTraits<T>::type;

   void setVar1(const T0& v);

   void setVar2(const T& v);

 T0 getVar1() const;
T getVar2() const;

   void print() const;

   T0 var1;
   T  var2;
 };

The .cpp file has the following codes.

#include "tmp.h"
template <class T>
void MyClass<T>::setVar1(const T0& v)
{
    var1 = v;
}

template <class T>
void MyClass<T>::setVar2(const T& v)
{
    var2 = v;
}

template <class T>
T0 MyClass<T>::getVar1() const
{
    return var1;
}

template <class T>
T MyClass<T>::getVar2() const
{
    return var2;
}

template <typename T>
void MyClass<T>::print() const
{
    std::cout<<"var1: "<<var1<<std::endl;
    std::cout<<"var2: "<<var2<<std::endl;

}

int main()
{

    MyClass<float> tmp;

    MyClass<std::complex<float> > tmp1;

    tmp.print();
    tmp1.print();
    return 0;
}

Now when I compile the code using C++ 11 support in g++, I get the following error.

tmp.cpp:17:1: error: ‘T0’ does not name a type
 T0 MyClass<T>::getVar1() const
 ^

How can I remove the error?

Body:
Try with

// ......................vvvvvvvvvvvvvvvvvvvvvvv
void MyClass<T>::setVar1(typename MyClass<T>::T0 const & v)
{
    var1 = v;
}

and the same for getVar1()


问:
Accessing values from a multidimensional array in PHP
In my PHP application, I need to take a multidimensional array and extract values in a for loop. The query will always return 9 rows.

```<code>$w = mysqli_query($con,"SELECT age, percent FROM drive03_2_monthly_income WHERE birthYear='1956' AND (age LIKE '%.00%') ORDER BY birthYear,age ");

$row = mysqli_fetch_array($w);
    for($n=0;$n<9;$n++) {
        echo $row[$n]->age." -- ".$row[$n]->percent."<br />";
        }
</code>```

When I run this, I get the data I want in $w, but having a problem extracting values in the loop.

答:
The problem is that mysqli_fetch_array() gets a single row. You have a few options for next steps.

Option 1 - Use mysqli_fetch_array() in a loop:

```<code>while($row = mysqli_fetch_array($w)){
    // Do something with your associative row data
    echo $row['age'];
}
</code>```

Option 2 - Use mysqli_fetch_object() in a loop:

```<code>while($row = mysqli_fetch_object($w)){
    // Do something with your object row data
    echo $row->name;
}
</code>```

Option 3 - Use mysqli_fetch_all()

```<code>foreach(mysqli_fetch_all($w, MYSQLI_ASSOC) as $row){
    // Do something with your associative row data
    echo $row['age'];
}
</code>```

This is not recommended, as quoted on the documentation.

As mysqli_fetch_all() returns all the rows as an array in a single
  step, it may consume more memory than some similar functions such as
  mysqli_fetch_array(), which only returns one row at a time from the
  result set. Further, if you need to iterate over the result set, you
  will need a looping construct that will further impact performance.
  For these reasons mysqli_fetch_all() should only be used in those
  situations where the fetched result set will be sent to another layer
  for processing.

Body:
In my PHP application, I need to take a multidimensional array and extract values in a for loop. The query will always return 9 rows.

$w = mysqli_query($con,"SELECT age, percent FROM drive03_2_monthly_income WHERE birthYear='1956' AND (age LIKE '%.00%') ORDER BY birthYear,age ");

$row = mysqli_fetch_array($w);
    for($n=0;$n<9;$n++) {
        echo $row[$n]->age." -- ".$row[$n]->percent."
";
        }

When I run this, I get the data I want in $w, but having a problem extracting values in the loop.

Body:
The problem is that mysqli_fetch_array() gets a single row. You have a few options for next steps.

Option 1 - Use mysqli_fetch_array() in a loop:

while($row = mysqli_fetch_array($w)){
    // Do something with your associative row data
    echo $row['age'];
}

Option 2 - Use mysqli_fetch_object() in a loop:

while($row = mysqli_fetch_object($w)){
    // Do something with your object row data
    echo $row->name;
}

Option 3 - Use mysqli_fetch_all()

foreach(mysqli_fetch_all($w, MYSQLI_ASSOC) as $row){
    // Do something with your associative row data
    echo $row['age'];
}

This is not recommended, as quoted on the documentation.

As mysqli_fetch_all() returns all the rows as an array in a single
  step, it may consume more memory than some similar functions such as
  mysqli_fetch_array(), which only returns one row at a time from the
  result set. Further, if you need to iterate over the result set, you
  will need a looping construct that will further impact performance.
  For these reasons mysqli_fetch_all() should only be used in those
  situations where the fetched result set will be sent to another layer
  for processing.


问:
Extjs Modern Simple Button in Tab Panel Tab Bar
I have a Tab panel with multiple Tabs in it. Now I want to add a simple button with an action to the tab bar. When clicked it should not open a Tab like the other ones, just execute a javascript function.

How is this possible in Extjs?

答:
Yes it is possible. You can do it with tabBar configuration. You will need to add setActive method and will need to handle events to change tabs.

You can also specify different styles for each tab header, have different types of headers and can easily highlight specific tab in custom colors as shown in fiddle.

```<code>Ext.application({
    name: 'Fiddle',

    launch: function () {
        Ext.Viewport.add({
            xtype: 'panel',
            layout: 'fit',
            title: 'Tab Panel with custom button',
            items: [{
                xtype: 'tabpanel',
                id: 'tabPanel',
                tabBar: {
                    items: [{
                        xtype: 'button',
                        text: 'Batman',
                        ui: 'action',
                        setActive: function (active) {
                            this.setPressed(active);
                        },
                        handler: function () {
                            var tabPanel = Ext.getCmp('tabPanel');
                            tabPanel.setActiveItem(0);
                        }
                    }, {
                        xtype: 'button',
                        text: 'Goku',
                        ui: 'action',
                        setActive: function (active) {
                            this.setPressed(active);
                        },
                        handler: function () {
                            var tabPanel = Ext.getCmp('tabPanel');
                            tabPanel.setActiveItem(1);
                        }
                    }, {
                        xtype: 'spacer',
                        setActive: function () {}
                    }, {
                        xtype: 'button',
                        text: 'Custom button',
                        ui: 'decline',
                        setActive: function () {},
                        handler: function () {
                            Ext.Msg.alert('Custom Message', 'This way you can do custom js function execution on tab bar');
                        }
                    }]
                },
                items: [{
                    items: [{
                        html: 'Batman is cool'
                    }]
                }, {
                    items: [{
                        html: 'Goku can defeat superman'
                    }]
                }]
            }]
        });
    }
});
</code>```

Example Fiddle : https://fiddle.sencha.com/#view/editor&fiddle/29r1

Body:
Yes it is possible. You can do it with tabBar configuration. You will need to add setActive method and will need to handle events to change tabs.

You can also specify different styles for each tab header, have different types of headers and can easily highlight specific tab in custom colors as shown in fiddle.

Ext.application({
    name: 'Fiddle',

    launch: function () {
        Ext.Viewport.add({
            xtype: 'panel',
            layout: 'fit',
            title: 'Tab Panel with custom button',
            items: [{
                xtype: 'tabpanel',
                id: 'tabPanel',
                tabBar: {
                    items: [{
                        xtype: 'button',
                        text: 'Batman',
                        ui: 'action',
                        setActive: function (active) {
                            this.setPressed(active);
                        },
                        handler: function () {
                            var tabPanel = Ext.getCmp('tabPanel');
                            tabPanel.setActiveItem(0);
                        }
                    }, {
                        xtype: 'button',
                        text: 'Goku',
                        ui: 'action',
                        setActive: function (active) {
                            this.setPressed(active);
                        },
                        handler: function () {
                            var tabPanel = Ext.getCmp('tabPanel');
                            tabPanel.setActiveItem(1);
                        }
                    }, {
                        xtype: 'spacer',
                        setActive: function () {}
                    }, {
                        xtype: 'button',
                        text: 'Custom button',
                        ui: 'decline',
                        setActive: function () {},
                        handler: function () {
                            Ext.Msg.alert('Custom Message', 'This way you can do custom js function execution on tab bar');
                        }
                    }]
                },
                items: [{
                    items: [{
                        html: 'Batman is cool'
                    }]
                }, {
                    items: [{
                        html: 'Goku can defeat superman'
                    }]
                }]
            }]
        });
    }
});

Example Fiddle : https://fiddle.sencha.com/#view/editor&fiddle/29r1


问:
What is the mouse down selector in CSS?
I have noticed that buttons and other elements have a default styling and behave in 3 steps: normal view, hover/focus view and mousedown/click view, in CSS I can change the styling of normal view and hover view like this:

```<code>button{
  background:#333;
  color:#FFF;
}

button:hover{
  background:#000;
  color:#EEE;
}
</code>```

but how can I select the mousedown? I want something like this:

```<code>button:mousedown{
  //some styling
}
</code>```

thanks

答:
I figured out that this behaves like a mousedown event:</p>

```<code>button:active:hover {}
</code>```

Title: What is the mouse down selector in CSS?

Body:
I have noticed that buttons and other elements have a default styling and behave in 3 steps: normal view, hover/focus view and mousedown/click view, in CSS I can change the styling of normal view and hover view like this:

button{
  background:#333;
  color:#FFF;
}

button:hover{
  background:#000;
  color:#EEE;
}

but how can I select the mousedown? I want something like this:

button:mousedown{
  //some styling
}

thanks

Body:
I figured out that this behaves like a mousedown event:

button:active:hover {}


问:
How to generate a random int in C?
Is there a function to generate a random int number in C?  Or will I have to use a third party library?</p>

答:
Despite all the people suggestion rand() here, you don't want to use rand() unless you have to! The random numbers that rand() produces are often very bad. To quote from the Linux man page:

The versions of rand() and srand() in the Linux C Library use the same random number generator as random(3) and srandom(3), so the lower-order bits should be as random as the higher-order bits. However, on older rand() implementations, and on current implementations on different systems, the lower-order bits are much less random than the higher-order bits. Do not use this function in applications intended to be portable when good randomness is needed. (Use random(3) instead.)

Regarding portability, random() is also defined by the POSIX standard for quite some time now. rand() is older, it appeared already in the first POSIX.1 spec (IEEE Std 1003.1-1988), whereas random() first appeared in POSIX.1-2001 (IEEE Std 1003.1-2001), yet the current POSIX standard is already POSIX.1-2008 (IEEE Std 1003.1-2008), which received an update just a year ago (IEEE Std 1003.1-2008, 2016 Edition). So I would consider random() to be very portable.

POSIX.1-2001 also introduced the lrand48() and mrand48() functions, see here:

This family of functions shall generate pseudo-random numbers using a linear congruential algorithm and 48-bit integer arithmetic.

And a pretty good pseudo random source is the arc4random() function that is available on many systems. Not part of any official standard, appeared in BSD around 1997 but you can find it on systems like Linux and macOS/iOS.

Title: How to generate a random int in C?


答:
The compiler can't know that T0 is defined in MyClass<T>. So you need to properly qualify the reutrn type:

```<code>template <class T>
typename MyClass<T>::T0 MyClass<T>::getVar1() const {
  return var1;
}
</code>```

Alternatively, you can use a trailing return type, which you won't need to qualify either:

```<code>template <class T>
auto MyClass<T>::getVar1() const -> T0 {
  return var1;
}
</code>```

Title: Template type deduction in function return type

Body:
The compiler can't know that T0 is defined in MyClass<T>. So you need to properly qualify the reutrn type:

template <class T>
typename MyClass<T>::T0 MyClass<T>::getVar1() const {
  return var1;
}

Alternatively, you can use a trailing return type, which you won't need to qualify either:

template <class T>
auto MyClass<T>::getVar1() const -> T0 {
  return var1;
}


问:
Turn Pandas Multi-Index into column
I have a dataframe with 2 index levels:

```<code>                         value
Trial    measurement
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34
</code>```

Which I want to turn into this:

```<code>Trial    measurement       value

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34
</code>```

How can I best do this?

I need this because I want to aggregate the data as instructed here, but I can't select my columns like that if they are in use as indices.

答:
This doesn't really apply to your case but could be helpful for others (like myself 5 minutes ago) to know. If one's multindex have the same name like this:

```<code>                         value
Trial        Trial
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34
</code>```

df.reset_index(inplace=True) will fail, cause the columns that are created cannot have the same names.

So then you need to rename the multindex with df.index = df.index.set_names(['Trial', 'measurement']) to get:

```<code>                           value
Trial    measurement

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34
</code>```

And then df.reset_index(inplace=True) will work like a charm.

I encountered this problem after grouping by year and month on a datetime-column(not index) called live_date, which meant that both year and month were named live_date.

Title: Turn Pandas Multi-Index into column

Body:
I have a dataframe with 2 index levels:

                         value
Trial    measurement
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34

Which I want to turn into this:

Trial    measurement       value

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34

How can I best do this?

I need this because I want to aggregate the data as instructed here, but I can't select my columns like that if they are in use as indices.

Body:
This doesn't really apply to your case but could be helpful for others (like myself 5 minutes ago) to know. If one's multindex have the same name like this:

                         value
Trial        Trial
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34

df.reset_index(inplace=True) will fail, cause the columns that are created cannot have the same names.

So then you need to rename the multindex with df.index = df.index.set_names(['Trial', 'measurement']) to get:

                           value
Trial    measurement

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34

And then df.reset_index(inplace=True) will work like a charm.

I encountered this problem after grouping by year and month on a datetime-column(not index) called live_date, which meant that both year and month were named live_date.


问:
Why is this only printing one letter every time I try?
```<code>from random import choice
print ("Enigma")

list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
range (0,25)

cha2 = choice(list)

complete = choice(list)

for x in range (0, 90000):
    ("Type alphabet")
    cha1=input()
    print (complete)
</code>```

When I run it and input an alphabet the same alphabet outputs as the first time. However I want it to output a different random alphabet each time I enter an alphabet. Thanks

答:
To answer: "I want it to output a different random alphabet each time I enter an alphabet"

From the above, you will check cha1 against the complete, and while they are the same, keep calling choice to update

```<code>cha1=input()
complete = choice(list)
while cha1 == complete:
    complete = choice(list)
</code>```

Body:
from random import choice
print ("Enigma")

list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
range (0,25)

cha2 = choice(list)

complete = choice(list)

for x in range (0, 90000):
    ("Type alphabet")
    cha1=input()
    print (complete)

When I run it and input an alphabet the same alphabet outputs as the first time. However I want it to output a different random alphabet each time I enter an alphabet. Thanks

Body:
To answer: "I want it to output a different random alphabet each time I enter an alphabet"

From the above, you will check cha1 against the complete, and while they are the same, keep calling choice to update

cha1=input()
complete = choice(list)
while cha1 == complete:
    complete = choice(list)


问:
how to read the data without database name
If possible to read the data from sql without database name only Server name and table name using c#?? </p>

答:
In theory you could get a list of all databases using sp_databases (In SQL Server) and then iterate through them all checking system tables for a table with your name but in practical terms this will be slow, be a security nightmare (should you really be able to see all db's on the server?) and a table with the same name could exist in more than 1 database and you'd have no way of working out which was correct.

Short answer: Not really.


问:
Cannot connect to local sql server
I am having some issue that blocked me since early this morning, I cannot connect to my sql server 2016. It is on my local even with many research on google I have not found anything that make it work :/

Friday, it was working fine and I do not recall modifying anything.

Here is the 1st error, I get :

```<code>===================================

Cannot connect to ..

===================================

The client was unable to establish a connection because of an error during connection initialization process before login. Possible causes include the following:  the client tried to connect to an unsupported version of SQL Server; the server was too busy to accept new connections; or there was a resource limitation (insufficient memory or maximum allowed connections) on the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (.Net SqlClient Data Provider)

------------------------------
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=233&LinkId=20476

------------------------------
Server Name: .
Error Number: 233
Severity: 20
State: 0

------------------------------
Program Location:

   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo ci, IServerType server)
   at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()

===================================

No process is on the other end of the pipe
</code>```

and the second one :

```<code>===================================

Cannot connect to ..

===================================

A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (.Net SqlClient Data Provider)

------------------------------
For help, click: http://go.microsoft.com/fwlinkProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=233&LinkId=20476

------------------------------
Server Name: . Error Number: 233 Severity: 20 State: 0

------------------------------
Program Location:

   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo ci, IServerType server)
   at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()

===================================

No process is on the other end of the pipe
</code>```

The 2 message keep showing one after the other.

Named Pipes was enabled when the error appears, disable it after.

Thanks for your time :)

答: Finally, I have restart the Sql Server, connect instantly and change the number of Concurrent user. I had only 3 user connections for almost 20 connections.  </p>

Title: Cannot connect to local sql server

Body:
I am having some issue that blocked me since early this morning, I cannot connect to my sql server 2016. It is on my local even with many research on google I have not found anything that make it work :/

Friday, it was working fine and I do not recall modifying anything.

Here is the 1st error, I get :

===================================

Cannot connect to ..

===================================

The client was unable to establish a connection because of an error during connection initialization process before login. Possible causes include the following:  the client tried to connect to an unsupported version of SQL Server; the server was too busy to accept new connections; or there was a resource limitation (insufficient memory or maximum allowed connections) on the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (.Net SqlClient Data Provider)

------------------------------
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=233&LinkId=20476

------------------------------
Server Name: .
Error Number: 233
Severity: 20
State: 0

------------------------------
Program Location:

   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo ci, IServerType server)
   at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()

===================================

No process is on the other end of the pipe

and the second one :

===================================

Cannot connect to ..

===================================

A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (.Net SqlClient Data Provider)

------------------------------
For help, click: http://go.microsoft.com/fwlinkProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=233&LinkId=20476

------------------------------
Server Name: . Error Number: 233 Severity: 20 State: 0

------------------------------
Program Location:

   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo ci, IServerType server)
   at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()

===================================

No process is on the other end of the pipe

The 2 message keep showing one after the other.

Named Pipes was enabled when the error appears, disable it after.

Thanks for your time :)


问:
How to show all processes in Erlang?
I need get all registered process. I input register(). a

```<code> mnesia_event,kernel_safe_sup,mnesia_monitor,mnesia_snmp_sup,
 mnesia_recover,mnesia_late_loader,mnesia_kernel_sup,inet_db,
 rex,kernel_sup,global_name_server,mnesia_checkpoint_sup,
 file_server_2,user,error_logger,global_group,mnesia_locker,
 standard_error_sup,popd_listener_sup,pop_fsm_sup,dets_sup,
 smtpd_listener_sup,disk_log_sup,disk_log_server,dets|...]
</code>```

How can i get all names registered process, without | ...] (truncation)?

Thank you.

答:
As long as your are in shell you can use regs():

```<code>1> regs().

** Registered procs on node nonode@nohost **
Name                  Pid          Initial Call                      Reds Msgs
application_controlle <0.33.0>     erlang:apply/2                   65717    0
code_server           <0.38.0>     erlang:apply/2                  592348    0
disk_log_server       <0.129.0>    disk_log_server:init/1             323    0
disk_log_sup          <0.128.0>    supervisor:disk_log_sup/1          367    0
dtls_connection_sup   <0.70.0>     supervisor:dtls_connectio           84    0
dtls_udp_sup          <0.71.0>     supervisor:dtls_udp_sup/1           81    0
erl_prim_loader       <0.6.0>      erlang:apply/2                24923843    0
erl_signal_server     <0.46.0>     gen_event:init_it/6                 51    0
...

** Registered ports on node nonode@nohost **
Name                  Id              Command
ok
</code>```

Title: How to show all processes in Erlang?

Body:
I need get all registered process. I input register(). a

 mnesia_event,kernel_safe_sup,mnesia_monitor,mnesia_snmp_sup,
 mnesia_recover,mnesia_late_loader,mnesia_kernel_sup,inet_db,
 rex,kernel_sup,global_name_server,mnesia_checkpoint_sup,
 file_server_2,user,error_logger,global_group,mnesia_locker,
 standard_error_sup,popd_listener_sup,pop_fsm_sup,dets_sup,
 smtpd_listener_sup,disk_log_sup,disk_log_server,dets|...]

How can i get all names registered process, without | ...] (truncation)?

Thank you.

Body:
As long as your are in shell you can use regs():

1> regs().

** Registered procs on node nonode@nohost **
Name                  Pid          Initial Call                      Reds Msgs
application_controlle <0.33.0>     erlang:apply/2                   65717    0
code_server           <0.38.0>     erlang:apply/2                  592348    0
disk_log_server       <0.129.0>    disk_log_server:init/1             323    0
disk_log_sup          <0.128.0>    supervisor:disk_log_sup/1          367    0
dtls_connection_sup   <0.70.0>     supervisor:dtls_connectio           84    0
dtls_udp_sup          <0.71.0>     supervisor:dtls_udp_sup/1           81    0
erl_prim_loader       <0.6.0>      erlang:apply/2                24923843    0
erl_signal_server     <0.46.0>     gen_event:init_it/6                 51    0
...

** Registered ports on node nonode@nohost **
Name                  Id              Command
ok


问:
Remote Powershell scripting and Jenkins not working
I am having an issue running a remote script using Jenkins. I have installed the PowerShell plug-in and can run PowerShell scripts on the local build server, but when I try to run it on a remote server, it fails all the time. I can run the same script outside of Jenkins locally and remotely and it works just fine. My assumption is that there is a security setting I am missing but for the life of me, I can not find it.

Any insight/help would be greatly appreciate it.

The code below runs using PowerShell on the server but not through Jenkins:

```<code>$ErrorActionPreference = 'Stop'

# Create a PSCredential Object using the "User" and "Password" parameters
that you passed to the job
$SecurePassword = 'xxxxxxx' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'ci-user', $SecurePassword

# Invoke a command on the remote machine.
# It depends on the type of job you are executing on the remote machine as
to if you want to use "-ErrorAction Stop" on your Invoke-Command.
Invoke-Command -ComputerName xxx.xx.xx.xxx -Credential $cred -ScriptBlock {
    # Restart the W32Time service
    Restart-Service -Name W32Time
}
</code>```

The error below is what I get when I run it in Jenkins. I am using the same username and password when I run it outside of Jenkins and works:

```<code>Connecting to remote server xxx.xx.xx.xxx failed with the
following error message : WinRM cannot process the request. The following
error with errorcode 0x8009030d occurred while using Negotiate authentication:
A specified logon session does not exist. It may already have been terminated.

 Possible causes are:
  -The user name or password specified are invalid.
  -Kerberos is used when no authentication method and no user name are
specified.
  -Kerberos accepts domain user names, but not local user names.
  -The Service Principal Name (SPN) for the remote computer name and port does
not exist.
  -The client and remote computers are in different domains and there is no
trust between the two domains.
 After checking for the above issues, try the following:
  -Check the Event Viewer for events related to authentication.
  -Change the authentication method; add the destination computer to the WinRM
TrustedHosts configuration setting or use HTTPS transport.
 Note that computers in the TrustedHosts list might not be authenticated.
   -For more information about WinRM configuration, run the following command:
winrm help config. For more information, see the about_Remote_Troubleshooting
Help topic.
At C:\Windows\TEMP\jenkins3589460126620702793.ps1:12 char:1
+ Invoke-Command -ComputerName xxx.xx.xx.xxx -Credential $cred -ScriptBlock {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (xxx.xx.xx.xxx:String) [], PSRemoting
   TransportException
    + FullyQualifiedErrorId : 1312,PSSessionStateBroken
</code>```

答:
This could be caused by a few different issues:

Are your remote machine and connecting machine on the same domain? If not, verify the domain of your ci-user and retry.

$cred = New-Object System.Management.Automation.PSCredential -ArgumentList
'connectingserver/ci-user', $SecurePassword

Is WinRM enabled on your remote server, is the WinRM service running, are you setup to allow the appropriate remoting? Follow these steps to verify: https://technet.microsoft.com/en-us/library/ff700227.aspx?f=255&MSPPError=-2147217396

Are both the remote and connecting server setup with the same authentication method? You will want to use either Kerberos or CredSSP. I would consider CredSSP only if you are trying to solve the Double-Hop issue.

Body:
I am having an issue running a remote script using Jenkins. I have installed the PowerShell plug-in and can run PowerShell scripts on the local build server, but when I try to run it on a remote server, it fails all the time. I can run the same script outside of Jenkins locally and remotely and it works just fine. My assumption is that there is a security setting I am missing but for the life of me, I can not find it.

Any insight/help would be greatly appreciate it.

The code below runs using PowerShell on the server but not through Jenkins:

$ErrorActionPreference = 'Stop'

# Create a PSCredential Object using the "User" and "Password" parameters
that you passed to the job
$SecurePassword = 'xxxxxxx' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'ci-user', $SecurePassword

# Invoke a command on the remote machine.
# It depends on the type of job you are executing on the remote machine as
to if you want to use "-ErrorAction Stop" on your Invoke-Command.
Invoke-Command -ComputerName xxx.xx.xx.xxx -Credential $cred -ScriptBlock {
    # Restart the W32Time service
    Restart-Service -Name W32Time
}

The error below is what I get when I run it in Jenkins. I am using the same username and password when I run it outside of Jenkins and works:

Connecting to remote server xxx.xx.xx.xxx failed with the
following error message : WinRM cannot process the request. The following
error with errorcode 0x8009030d occurred while using Negotiate authentication:
A specified logon session does not exist. It may already have been terminated.

 Possible causes are:
  -The user name or password specified are invalid.
  -Kerberos is used when no authentication method and no user name are
specified.
  -Kerberos accepts domain user names, but not local user names.
  -The Service Principal Name (SPN) for the remote computer name and port does
not exist.
  -The client and remote computers are in different domains and there is no
trust between the two domains.
 After checking for the above issues, try the following:
  -Check the Event Viewer for events related to authentication.
  -Change the authentication method; add the destination computer to the WinRM
TrustedHosts configuration setting or use HTTPS transport.
 Note that computers in the TrustedHosts list might not be authenticated.
   -For more information about WinRM configuration, run the following command:
winrm help config. For more information, see the about_Remote_Troubleshooting
Help topic.
At C:\Windows\TEMP\jenkins3589460126620702793.ps1:12 char:1
+ Invoke-Command -ComputerName xxx.xx.xx.xxx -Credential $cred -ScriptBlock {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (xxx.xx.xx.xxx:String) [], PSRemoting
   TransportException
    + FullyQualifiedErrorId : 1312,PSSessionStateBroken


问:
pyspark dataframe filtering on multiple columns
I have a pyspark dataframe which looks like below

df

```<code>num11   num21
10     10
20     30
5      25
</code>```

I am filtering above dataframe on all columns present, and selecting rows with number greater than 10 [no of columns can be more than two]

```<code>from pyspark.sql.functions import col
col_list = df.schema.names
df_fltered = df.where(col(c) >= 10 for c in col_list)
</code>```

desired output is :

```<code>num11    num21
10       10
20       30
</code>```

How can we achieve filtering on multiple columns using iteration on column list as above. [all efforts are appriciated]

[error i reveive is : condition should be string or column]

答:
As an alternative, if you not averse to some sql-like snippets of code, the following should work:</p>

```<code>df.where("AND".join(["(%s >=10)"%(col) for col in col_list]))
</code>```

Body:
I have a pyspark dataframe which looks like below

df

num11   num21
10     10
20     30
5      25

I am filtering above dataframe on all columns present, and selecting rows with number greater than 10 [no of columns can be more than two]

from pyspark.sql.functions import col
col_list = df.schema.names
df_fltered = df.where(col(c) >= 10 for c in col_list)

desired output is :

num11    num21
10       10
20       30

How can we achieve filtering on multiple columns using iteration on column list as above. [all efforts are appriciated]

[error i reveive is : condition should be string or column]

Body:
As an alternative, if you not averse to some sql-like snippets of code, the following should work:

df.where("AND".join(["(%s >=10)"%(col) for col in col_list]))


问:
How do I add a attribute to a XmlArray (not element)
I want to create some XML like this using Serialization:

```<code><?xml version="1.0" encoding="utf-8"?>
<Person>
  <Name>Bob</Name>
  <Sex>Male</Sex>
  <links rel="relations">
    <link rel="self" href="/Persons/Bob" />
    <link rel="child" href="/Persons/Lisa" />
  </links>
<Person>
</code>```

Now I know I can set attribute on the link items using:

```<code>Public Class link
   <System.Xml.Serialization.XmlAttribute("rel")>
   Public rel As String = ""

   <System.Xml.Serialization.XmlAttribute("href")>
   Public href As String = ""
End Class
</code>```

but what I can't figure is how I set the rel attribute on the links element.  This would be the code for the Person Class to set the links element:

```<code>Public Class Person
   ...
   <System.Xml.Serialization.XmlArray("links")>
   Public links As New List(Of link)
End Class
</code>```

Am I going about this the right way?

答:
Custom serialization is an option, simply implement the IXmlSerializable interface on your Person's class then in the IXmlSerializable.WriteXml() method control how you want to write the xml yourself.

```<code>   public class Link
    {
        public string rel { get; set; }

        public string href { get; set; }
    }

    [Serializable]
    public class Person : IXmlSerializable
    {
        public Person()
        {
        }

        public string Name { get; set; }

        public string Sex { get; set; }

        public Link[]  Links {get; set;}

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteElementString("Name", this.Name);
            writer.WriteElementString("Sex", this.Sex);

            writer.WriteStartElement("links");
            writer.WriteAttributeString("rel", "relations");

            foreach(Link link in this.Links)
            {
                writer.WriteStartElement("link");
                writer.WriteAttributeString("rel", link.rel);
                writer.WriteAttributeString("href", link.href);
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
    }
</code>```

this is the caller code that will create a Person class then serialize it in the xml you want

```<code>public SerializePerson()
{

    Link link1 = new Link() { rel = "self", href = "/Persons/Bob" };
    Link link2 = new Link() { rel = "child", href = "/Persons/Lisa" };

    Person person = new Person() { Name = "Bob", Sex = "Male"};
    person.Links = new Link[] { link1, link2 };

    XmlSerializer serializer = new XmlSerializer(typeof(Person));
    StreamWriter streamWriter = new StreamWriter(@"C:\temp\serializedBob.txt");
    serializer.Serialize(streamWriter, person);
    streamWriter.Close();
}
</code>```

Body:
I want to create some XML like this using Serialization:

<?xml version="1.0" encoding="utf-8"?>
<Person>
  <Name>Bob</Name>
  <Sex>Male</Sex>
  <links rel="relations">
    <link rel="self" href="/Persons/Bob" />
    <link rel="child" href="/Persons/Lisa" />
  </links>
<Person>

Now I know I can set attribute on the link items using:

Public Class link
   <System.Xml.Serialization.XmlAttribute("rel")>
   Public rel As String = ""

   <System.Xml.Serialization.XmlAttribute("href")>
   Public href As String = ""
End Class

but what I can't figure is how I set the rel attribute on the links element.  This would be the code for the Person Class to set the links element:

Public Class Person
   ...
   <System.Xml.Serialization.XmlArray("links")>
   Public links As New List(Of link)
End Class

Am I going about this the right way?

Body:
Custom serialization is an option, simply implement the IXmlSerializable interface on your Person's class then in the IXmlSerializable.WriteXml() method control how you want to write the xml yourself.

   public class Link
    {
        public string rel { get; set; }

        public string href { get; set; }
    }

    [Serializable]
    public class Person : IXmlSerializable
    {
        public Person()
        {
        }

        public string Name { get; set; }

        public string Sex { get; set; }

        public Link[]  Links {get; set;}

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteElementString("Name", this.Name);
            writer.WriteElementString("Sex", this.Sex);

            writer.WriteStartElement("links");
            writer.WriteAttributeString("rel", "relations");

            foreach(Link link in this.Links)
            {
                writer.WriteStartElement("link");
                writer.WriteAttributeString("rel", link.rel);
                writer.WriteAttributeString("href", link.href);
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
    }

this is the caller code that will create a Person class then serialize it in the xml you want

public SerializePerson()
{

    Link link1 = new Link() { rel = "self", href = "/Persons/Bob" };
    Link link2 = new Link() { rel = "child", href = "/Persons/Lisa" };

    Person person = new Person() { Name = "Bob", Sex = "Male"};
    person.Links = new Link[] { link1, link2 };

    XmlSerializer serializer = new XmlSerializer(typeof(Person));
    StreamWriter streamWriter = new StreamWriter(@"C:\temp\serializedBob.txt");
    serializer.Serialize(streamWriter, person);
    streamWriter.Close();
}


问:
Android - InvalidKeySpecException - java lang runtime exception SSLInternal:TOO_LONG when trying to read .der file
I am trying to read a private key from a der file. I am getting the following error in my logcat. And the returned value is empty.

java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000af:ASN.1 encoding routines:OPENSSL_internal:TOO_LONG

I tried searching for situations where this had already happened but could find none. I would like to know what this error means and how I can solve it.

Here is my code:

```<code>public static String decryptionWithFile(String encrypted,String privateFile2)throws Exception  {
    PrivateKey privateKey = getPrivateKey(privateFile2);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] bts = Hex.decodeHex(encrypted.toCharArray());
    bts = cipher.doFinal(bts);

    bts = getFinalBytesOfDycryptedString(bts);
    String decryptedMessage = new String(cipher.doFinal(encrypted.getBytes()));
    return new String(bts,"UTF-8");
}
</code>```

And here is the getPrivateKey(); Method:

```<code>private static PrivateKey getPrivateKey(String privateFile2)throws Exception  {
    File f = new File(privateFile2);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int) f.length()];
    dis.readFully(keyBytes);
    dis.close();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec);
    return privKey;
}
</code>```

Important Note: I added the .der file to my assets folder and then saved it to a file in Internal Storage in order to access the path - which my function requires. Do you think, anything must have happened to the file during this process? (It worked fine with the Public Key)

答:
The problem turned out to be what I'd guessed. When I was writing the .der file to the Internal Storage, it was getting altered somehow and thus wasn't working.

So instead of that. I directly used the InputStream returned from getAssets().open(filename) to read the private key. That fixed it.

Body:
I am trying to read a private key from a der file. I am getting the following error in my logcat. And the returned value is empty.

java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000af:ASN.1 encoding routines:OPENSSL_internal:TOO_LONG

I tried searching for situations where this had already happened but could find none. I would like to know what this error means and how I can solve it.

Here is my code:

public static String decryptionWithFile(String encrypted,String privateFile2)throws Exception  {
    PrivateKey privateKey = getPrivateKey(privateFile2);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] bts = Hex.decodeHex(encrypted.toCharArray());
    bts = cipher.doFinal(bts);

    bts = getFinalBytesOfDycryptedString(bts);
    String decryptedMessage = new String(cipher.doFinal(encrypted.getBytes()));
    return new String(bts,"UTF-8");
}

And here is the getPrivateKey(); Method:

private static PrivateKey getPrivateKey(String privateFile2)throws Exception  {
    File f = new File(privateFile2);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int) f.length()];
    dis.readFully(keyBytes);
    dis.close();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec);
    return privKey;
}

Important Note: I added the .der file to my assets folder and then saved it to a file in Internal Storage in order to access the path - which my function requires. Do you think, anything must have happened to the file during this process? (It worked fine with the Public Key)


问:
How Exactly Does @param Work - Java
How does the annotation @param work?

If I had something like this:

```<code>/*
*@param testNumber;
*/

int testNumber = 5;
if (testNumber < 6) {
   //Something
}
</code>```

How would the @param affect the testNumber? Does it even affect the testNumber?

Thanks. Let me know if I used it wrong.

答: It is basically a comment. As we know, a number of people working on the same project must have knowledge about the code changes. We are making some notes in the program about the parameters.</p>

Title: How Exactly Does @param Work - Java

Body:
How does the annotation @param work?

If I had something like this:

/*
*@param testNumber;
*/

int testNumber = 5;
if (testNumber < 6) {
   //Something
}

How would the @param affect the testNumber? Does it even affect the testNumber?

Thanks. Let me know if I used it wrong.


问:
In Google's Colab notebook, How do I call a function from a Python file?
From a Colab notebook, I would like to call a python function that I wrote in a separate python file. How do I do that?</p>

答:
Edit: If you would like to import a local module, you'll want to edit your sys.path to point to that new directory. Here's an example notebook:
https://colab.research.google.com/notebook#fileId=1PtYW0hZit-B9y4PL978kV2ppJJPhjQua

Original reply:
Sure, here's an example notebook:
https://colab.research.google.com/notebook#fileId=1KBrq8aAiy8vYIIUiTb5UHG9GKOdEMF3n

There are two cells: the first defines a .py file with a function to be imported.

```<code>%%writefile example.py
def f():
  print 'This is a function defined in a Python source file.'
</code>```

The second cell uses execfile to evaluate that .py file in the notebook's Python interpreter.

```<code># Bring the file into the local Python environment.
execfile('example.py')

# Call the function defined in the file.
f()
</code>```

Body:
Edit: If you would like to import a local module, you'll want to edit your sys.path to point to that new directory. Here's an example notebook:
https://colab.research.google.com/notebook#fileId=1PtYW0hZit-B9y4PL978kV2ppJJPhjQua

Original reply:
Sure, here's an example notebook:
https://colab.research.google.com/notebook#fileId=1KBrq8aAiy8vYIIUiTb5UHG9GKOdEMF3n

There are two cells: the first defines a .py file with a function to be imported.

%%writefile example.py
def f():
  print 'This is a function defined in a Python source file.'

The second cell uses execfile to evaluate that .py file in the notebook's Python interpreter.

# Bring the file into the local Python environment.
execfile('example.py')

# Call the function defined in the file.
f()


问:
Microsoft Access: How to create a single report with multiple totals rows (totaling based on date)
I am very new to microsoft access. I work in an Immunization program where I routinely collect data about vaccinated children. I used to have excel spreadsheets (different spreadsheet for every campaign) but as the number of spreadsheets grew, comparison between data of different campaigns became difficult.

Now I am trying to get all the data into a database program in which I can bring data from multiple campaigns into a single report easily.
After jumping into access, first I need to get the basic things done that excel could do very easily. e.g.

This is sample data from day 1 and day 2 of the campaign. In access I can create a query which shows data from day 1 only and a totals row at the end. But how do I create a single query/report which shows separate totals row for each day. In other words, how do I reproduce the data in pictures above in a single access report.

Edit:

I am planning a single table that contains data from all the campaigns in various columns.
The table in microsoft access looks like this:

Link to the access database file:
link to access database file

答:
June7 has provided the correct advice - though it is cryptic.

Your table structure appears correct - you want a single table with the identity of the campaign and date (or whatever parameters you seek to differentiate them).

Your query is to collect those records into a record set.  (Although there is an aggregate query type - it is not meant for what you seek to do.)  You don't want to report on the entire database each time probably so one uses a query rather than the table itself to be the record set of the report.  How that query is delimited is up to you.

The report object is where one then groups - and a group can have a total.  You will want to look into online/text instructions on this for actual implementation.


问:
Top only corner radius for UIImage in UIStackView
I'm facing a very strange problem right now where the same code produces different results on a UIView and a UIImageView.

I have a custom UITableViewCell. To add a shadow and also got some separation between the cells. I've used a container view that contains the shadow and the rounded corners. Everything works as expected.

One layer below I use a UIStackView so I can easily remove the image of the cell if the post has no image at all. This stack view contains one image and another stack view. The corner radius on top of the outer container view doesn't work because the image has no rounded corners. So I've tried to implement this for the image and also for a view above that image that is used as an overlay.

The overlay is outside of the stack view. Now, I've written some code to also add the corner radius to these both views and it works perfectly on the overlay but not on the UIImageView. Even when I pull out the image out of the stack views.

Here is what it looks like:

I've used a slightly bigger corner radius to visualize it and added a border to the image.

What I expect to happen: The image has exactly the same width and corner radius on the correct sides like the overlay (grey).

Here is the code for the custom UIImageView class:

```<code>import UIKit

@IBDesignable
class RoundedImageView: UIImageView {

    @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { setUpView() } }
    @IBInspectable var isOnlyTop: Bool = false { didSet { setUpView() } }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func draw(_ rect: CGRect) {
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        self.clipsToBounds = true
        self.layer.borderColor = UIColor.green.cgColor
        self.layer.borderWidth = 2.0

        if isOnlyTop {
            setTopCornerRadius()
        } else {
            self.layer.cornerRadius = cornerRadius
        }
    }

    func setTopCornerRadius() {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
        self.layer.masksToBounds = true
    }
}
</code>```

I've copied the code from the rounded view. However, for completion I will add it below:

```<code>import UIKit

@IBDesignable
class RoundedView: UIView {

    @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { setUpView() } }
    @IBInspectable var isOnlyTop: Bool = false { didSet { setUpView() } }

    override func awakeFromNib() {
        super.awakeFromNib()
        setUpView()
    }

    override func draw(_ rect: CGRect) {
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        self.clipsToBounds = true
        self.layer.borderColor = UIColor.red.cgColor
        //self.layer.borderWidth = 2.0

        if isOnlyTop {
            setTopCornerRadius()
        } else {
            self.layer.cornerRadius = cornerRadius
        }
    }

    private func setTopCornerRadius() {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
    }
}
</code>```

Here is the whole view tree of the cell:

I know, that I am violating the DRY principle here, but I just have written the same code for UIView and UIImageView so I can verify why it doesn't work.

Hint: Notice that I have two times the same UIImage in this cell (Post Image and Image out of stack view) as I thought it is maybe caused by Constraints or the stack view. So the image outside of the stack view has exactly the same constraints as the Overlay View.

So long story short: Do you know why my UIImageView has the wrong size and also doesn't apply the corner radius that works perfectly on the Overlay View (UIView). Thanks in advance!

EDIT: The expected result should look like this. Unless the top corners of the image should also be rounded (you see that little difference at the top corners of the image? That's caused by the overlay. It has the correct corner radius but the image doesn't).

EDIT 2: I was asked to add the code of the view controller. However, I don't change anything here.

```<code>import UIKit

protocol PostListDisplayLogic: class {
}

class PostListViewController: UIViewController, PostListDisplayLogic, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var interactor: PostListBusinessLogic?
    var router: (NSObjectProtocol & PostListRoutingLogic & PostListDataPassing)?

    // MARK: Object lifecycle

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    // MARK: Setup

    private func setup() {
       let viewController = self
       let interactor = PostListInteractor()
       let presenter = PostListPresenter()
       let router = PostListRouter()
       viewController.interactor = interactor
       viewController.router = router
       interactor.presenter = presenter
       presenter.viewController = viewController
       router.viewController = viewController
       router.dataStore = interactor
   }

   // MARK: Routing

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let scene = segue.identifier {
            let selector = NSSelectorFromString("routeTo\(scene)WithSegue:")
            if let router = router, router.responds(to: selector) {
                router.perform(selector, with: segue)
            }
        }
   }

   // MARK: View lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.delegate = self
        self.tableView.dataSource = self
        tableView.register(UINib(nibName: "PostCell", bundle: nil), forCellReuseIdentifier: "PostCell")
    }

    // MARK: TableView DataSource & Delegate
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
            return cell
            }

        return UITableViewCell()
    }
}
</code>```

答: You should draw it manually into layer. There is no pre-defined function to achieve this.</p>

Body:
I'm facing a very strange problem right now where the same code produces different results on a UIView and a UIImageView.

I have a custom UITableViewCell. To add a shadow and also got some separation between the cells. I've used a container view that contains the shadow and the rounded corners. Everything works as expected.

One layer below I use a UIStackView so I can easily remove the image of the cell if the post has no image at all. This stack view contains one image and another stack view. The corner radius on top of the outer container view doesn't work because the image has no rounded corners. So I've tried to implement this for the image and also for a view above that image that is used as an overlay.

The overlay is outside of the stack view. Now, I've written some code to also add the corner radius to these both views and it works perfectly on the overlay but not on the UIImageView. Even when I pull out the image out of the stack views.

Here is what it looks like:

I've used a slightly bigger corner radius to visualize it and added a border to the image.

What I expect to happen: The image has exactly the same width and corner radius on the correct sides like the overlay (grey).

Here is the code for the custom UIImageView class:

import UIKit

@IBDesignable
class RoundedImageView: UIImageView {

    @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { setUpView() } }
    @IBInspectable var isOnlyTop: Bool = false { didSet { setUpView() } }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func draw(_ rect: CGRect) {
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        self.clipsToBounds = true
        self.layer.borderColor = UIColor.green.cgColor
        self.layer.borderWidth = 2.0

        if isOnlyTop {
            setTopCornerRadius()
        } else {
            self.layer.cornerRadius = cornerRadius
        }
    }

    func setTopCornerRadius() {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
        self.layer.masksToBounds = true
    }
}

I've copied the code from the rounded view. However, for completion I will add it below:

import UIKit

@IBDesignable
class RoundedView: UIView {

    @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { setUpView() } }
    @IBInspectable var isOnlyTop: Bool = false { didSet { setUpView() } }

    override func awakeFromNib() {
        super.awakeFromNib()
        setUpView()
    }

    override func draw(_ rect: CGRect) {
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        self.clipsToBounds = true
        self.layer.borderColor = UIColor.red.cgColor
        //self.layer.borderWidth = 2.0

        if isOnlyTop {
            setTopCornerRadius()
        } else {
            self.layer.cornerRadius = cornerRadius
        }
    }

    private func setTopCornerRadius() {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners:[.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
    }
}

Here is the whole view tree of the cell:

I know, that I am violating the DRY principle here, but I just have written the same code for UIView and UIImageView so I can verify why it doesn't work.

Hint: Notice that I have two times the same UIImage in this cell (Post Image and Image out of stack view) as I thought it is maybe caused by Constraints or the stack view. So the image outside of the stack view has exactly the same constraints as the Overlay View.

So long story short: Do you know why my UIImageView has the wrong size and also doesn't apply the corner radius that works perfectly on the Overlay View (UIView). Thanks in advance!

EDIT: The expected result should look like this. Unless the top corners of the image should also be rounded (you see that little difference at the top corners of the image? That's caused by the overlay. It has the correct corner radius but the image doesn't).

EDIT 2: I was asked to add the code of the view controller. However, I don't change anything here.

import UIKit

protocol PostListDisplayLogic: class {
}

class PostListViewController: UIViewController, PostListDisplayLogic, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var interactor: PostListBusinessLogic?
    var router: (NSObjectProtocol & PostListRoutingLogic & PostListDataPassing)?

    // MARK: Object lifecycle

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    // MARK: Setup

    private func setup() {
       let viewController = self
       let interactor = PostListInteractor()
       let presenter = PostListPresenter()
       let router = PostListRouter()
       viewController.interactor = interactor
       viewController.router = router
       interactor.presenter = presenter
       presenter.viewController = viewController
       router.viewController = viewController
       router.dataStore = interactor
   }

   // MARK: Routing

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let scene = segue.identifier {
            let selector = NSSelectorFromString("routeTo\(scene)WithSegue:")
            if let router = router, router.responds(to: selector) {
                router.perform(selector, with: segue)
            }
        }
   }

   // MARK: View lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.delegate = self
        self.tableView.dataSource = self
        tableView.register(UINib(nibName: "PostCell", bundle: nil), forCellReuseIdentifier: "PostCell")
    }

    // MARK: TableView DataSource & Delegate
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
            return cell
            }

        return UITableViewCell()
    }
}